repository_name
stringclasses 316
values | func_path_in_repository
stringlengths 6
223
| func_name
stringlengths 1
134
| language
stringclasses 1
value | func_code_string
stringlengths 57
65.5k
| func_documentation_string
stringlengths 1
46.3k
| split_name
stringclasses 1
value | func_code_url
stringlengths 91
315
| called_functions
listlengths 1
156
⌀ | enclosing_scope
stringlengths 2
1.48M
|
|---|---|---|---|---|---|---|---|---|---|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
show_storage_container
|
python
|
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
|
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L2618-L2651
|
[
"def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):\n '''\n .. versionadded:: 2015.8.0\n\n Return a storage_conn object for the storage account\n '''\n if conn_kwargs is None:\n conn_kwargs = {}\n\n if not storage_account:\n storage_account = config.get_cloud_config_value(\n 'storage_account',\n get_configured_provider(), __opts__, search_global=False,\n default=conn_kwargs.get('storage_account', None)\n )\n if not storage_key:\n storage_key = config.get_cloud_config_value(\n 'storage_key',\n get_configured_provider(), __opts__, search_global=False,\n default=conn_kwargs.get('storage_key', None)\n )\n return azure.storage.BlobService(storage_account, storage_key)\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
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 'azure',
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'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(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 create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
show_storage_container_metadata
|
python
|
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
|
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L2658-L2694
|
[
"def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):\n '''\n .. versionadded:: 2015.8.0\n\n Return a storage_conn object for the storage account\n '''\n if conn_kwargs is None:\n conn_kwargs = {}\n\n if not storage_account:\n storage_account = config.get_cloud_config_value(\n 'storage_account',\n get_configured_provider(), __opts__, search_global=False,\n default=conn_kwargs.get('storage_account', None)\n )\n if not storage_key:\n storage_key = config.get_cloud_config_value(\n 'storage_key',\n get_configured_provider(), __opts__, search_global=False,\n default=conn_kwargs.get('storage_key', None)\n )\n return azure.storage.BlobService(storage_account, storage_key)\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
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 'azure',
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'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(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 create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
set_storage_container_metadata
|
python
|
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
|
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L2701-L2749
|
[
"def safe_load(stream, Loader=SaltYamlSafeLoader):\n '''\n .. versionadded:: 2018.3.0\n\n Helper function which automagically uses our custom loader.\n '''\n return yaml.load(stream, Loader=Loader)\n",
"def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):\n '''\n .. versionadded:: 2015.8.0\n\n Return a storage_conn object for the storage account\n '''\n if conn_kwargs is None:\n conn_kwargs = {}\n\n if not storage_account:\n storage_account = config.get_cloud_config_value(\n 'storage_account',\n get_configured_provider(), __opts__, search_global=False,\n default=conn_kwargs.get('storage_account', None)\n )\n if not storage_key:\n storage_key = config.get_cloud_config_value(\n 'storage_key',\n get_configured_provider(), __opts__, search_global=False,\n default=conn_kwargs.get('storage_key', None)\n )\n return azure.storage.BlobService(storage_account, storage_key)\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
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 'azure',
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'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(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 create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
show_storage_container_acl
|
python
|
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
|
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L2752-L2788
|
[
"def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):\n '''\n .. versionadded:: 2015.8.0\n\n Return a storage_conn object for the storage account\n '''\n if conn_kwargs is None:\n conn_kwargs = {}\n\n if not storage_account:\n storage_account = config.get_cloud_config_value(\n 'storage_account',\n get_configured_provider(), __opts__, search_global=False,\n default=conn_kwargs.get('storage_account', None)\n )\n if not storage_key:\n storage_key = config.get_cloud_config_value(\n 'storage_key',\n get_configured_provider(), __opts__, search_global=False,\n default=conn_kwargs.get('storage_key', None)\n )\n return azure.storage.BlobService(storage_account, storage_key)\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
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 'azure',
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'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(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 create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
set_storage_container_acl
|
python
|
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
|
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L2795-L2834
|
[
"def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):\n '''\n .. versionadded:: 2015.8.0\n\n Return a storage_conn object for the storage account\n '''\n if conn_kwargs is None:\n conn_kwargs = {}\n\n if not storage_account:\n storage_account = config.get_cloud_config_value(\n 'storage_account',\n get_configured_provider(), __opts__, search_global=False,\n default=conn_kwargs.get('storage_account', None)\n )\n if not storage_key:\n storage_key = config.get_cloud_config_value(\n 'storage_key',\n get_configured_provider(), __opts__, search_global=False,\n default=conn_kwargs.get('storage_key', None)\n )\n return azure.storage.BlobService(storage_account, storage_key)\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
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 'azure',
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'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(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 create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
delete_storage_container
|
python
|
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
|
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L2837-L2876
|
[
"def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):\n '''\n .. versionadded:: 2015.8.0\n\n Return a storage_conn object for the storage account\n '''\n if conn_kwargs is None:\n conn_kwargs = {}\n\n if not storage_account:\n storage_account = config.get_cloud_config_value(\n 'storage_account',\n get_configured_provider(), __opts__, search_global=False,\n default=conn_kwargs.get('storage_account', None)\n )\n if not storage_key:\n storage_key = config.get_cloud_config_value(\n 'storage_key',\n get_configured_provider(), __opts__, search_global=False,\n default=conn_kwargs.get('storage_key', None)\n )\n return azure.storage.BlobService(storage_account, storage_key)\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
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 'azure',
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'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(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 create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
lease_storage_container
|
python
|
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
|
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L2879-L2955
| null |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
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 'azure',
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'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(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 create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
list_blobs
|
python
|
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
|
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L2958-L3028
|
[
"def list_blobs(storage_conn=None, **kwargs):\n '''\n .. versionadded:: 2015.8.0\n\n List blobs associated with the container\n '''\n if not storage_conn:\n storage_conn = get_storage_conn(opts=kwargs)\n\n if 'container' not in kwargs:\n raise SaltSystemExit(\n code=42,\n msg='An storage container name must be specified as \"container\"'\n )\n\n data = storage_conn.list_blobs(\n container_name=kwargs['container'],\n prefix=kwargs.get('prefix', None),\n marker=kwargs.get('marker', None),\n maxresults=kwargs.get('maxresults', None),\n include=kwargs.get('include', None),\n delimiter=kwargs.get('delimiter', None),\n )\n\n ret = {}\n for item in data.blobs:\n ret[item.name] = object_to_dict(item)\n return ret\n",
"def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):\n '''\n .. versionadded:: 2015.8.0\n\n Return a storage_conn object for the storage account\n '''\n if conn_kwargs is None:\n conn_kwargs = {}\n\n if not storage_account:\n storage_account = config.get_cloud_config_value(\n 'storage_account',\n get_configured_provider(), __opts__, search_global=False,\n default=conn_kwargs.get('storage_account', None)\n )\n if not storage_key:\n storage_key = config.get_cloud_config_value(\n 'storage_key',\n get_configured_provider(), __opts__, search_global=False,\n default=conn_kwargs.get('storage_key', None)\n )\n return azure.storage.BlobService(storage_account, storage_key)\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
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 'azure',
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'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(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 create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
show_blob_service_properties
|
python
|
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
|
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L3031-L3054
|
[
"def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):\n '''\n .. versionadded:: 2015.8.0\n\n Return a storage_conn object for the storage account\n '''\n if conn_kwargs is None:\n conn_kwargs = {}\n\n if not storage_account:\n storage_account = config.get_cloud_config_value(\n 'storage_account',\n get_configured_provider(), __opts__, search_global=False,\n default=conn_kwargs.get('storage_account', None)\n )\n if not storage_key:\n storage_key = config.get_cloud_config_value(\n 'storage_key',\n get_configured_provider(), __opts__, search_global=False,\n default=conn_kwargs.get('storage_key', None)\n )\n return azure.storage.BlobService(storage_account, storage_key)\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
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 'azure',
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'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(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 create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
set_blob_service_properties
|
python
|
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
|
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L3061-L3099
|
[
"def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):\n '''\n .. versionadded:: 2015.8.0\n\n Return a storage_conn object for the storage account\n '''\n if conn_kwargs is None:\n conn_kwargs = {}\n\n if not storage_account:\n storage_account = config.get_cloud_config_value(\n 'storage_account',\n get_configured_provider(), __opts__, search_global=False,\n default=conn_kwargs.get('storage_account', None)\n )\n if not storage_key:\n storage_key = config.get_cloud_config_value(\n 'storage_key',\n get_configured_provider(), __opts__, search_global=False,\n default=conn_kwargs.get('storage_key', None)\n )\n return azure.storage.BlobService(storage_account, storage_key)\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
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 'azure',
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'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(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 create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
show_blob_properties
|
python
|
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
|
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L3102-L3148
|
[
"def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):\n '''\n .. versionadded:: 2015.8.0\n\n Return a storage_conn object for the storage account\n '''\n if conn_kwargs is None:\n conn_kwargs = {}\n\n if not storage_account:\n storage_account = config.get_cloud_config_value(\n 'storage_account',\n get_configured_provider(), __opts__, search_global=False,\n default=conn_kwargs.get('storage_account', None)\n )\n if not storage_key:\n storage_key = config.get_cloud_config_value(\n 'storage_key',\n get_configured_provider(), __opts__, search_global=False,\n default=conn_kwargs.get('storage_key', None)\n )\n return azure.storage.BlobService(storage_account, storage_key)\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
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 'azure',
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'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(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 create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
set_blob_properties
|
python
|
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
|
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L3155-L3221
|
[
"def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):\n '''\n .. versionadded:: 2015.8.0\n\n Return a storage_conn object for the storage account\n '''\n if conn_kwargs is None:\n conn_kwargs = {}\n\n if not storage_account:\n storage_account = config.get_cloud_config_value(\n 'storage_account',\n get_configured_provider(), __opts__, search_global=False,\n default=conn_kwargs.get('storage_account', None)\n )\n if not storage_key:\n storage_key = config.get_cloud_config_value(\n 'storage_key',\n get_configured_provider(), __opts__, search_global=False,\n default=conn_kwargs.get('storage_key', None)\n )\n return azure.storage.BlobService(storage_account, storage_key)\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
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 'azure',
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'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(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 create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
put_blob
|
python
|
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
|
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L3224-L3296
|
[
"def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):\n '''\n .. versionadded:: 2015.8.0\n\n Return a storage_conn object for the storage account\n '''\n if conn_kwargs is None:\n conn_kwargs = {}\n\n if not storage_account:\n storage_account = config.get_cloud_config_value(\n 'storage_account',\n get_configured_provider(), __opts__, search_global=False,\n default=conn_kwargs.get('storage_account', None)\n )\n if not storage_key:\n storage_key = config.get_cloud_config_value(\n 'storage_key',\n get_configured_provider(), __opts__, search_global=False,\n default=conn_kwargs.get('storage_key', None)\n )\n return azure.storage.BlobService(storage_account, storage_key)\n",
"def put_blob(storage_conn=None, **kwargs):\n '''\n .. versionadded:: 2015.8.0\n\n Upload a blob\n '''\n if not storage_conn:\n storage_conn = get_storage_conn(opts=kwargs)\n\n if 'container' not in kwargs:\n raise SaltSystemExit(code=42, msg='The blob container name must be specified as \"container\"')\n\n if 'name' not in kwargs:\n raise SaltSystemExit(code=42, msg='The blob name must be specified as \"name\"')\n\n if 'blob_path' not in kwargs and 'blob_content' not in kwargs:\n raise SaltSystemExit(\n code=42,\n msg='Either a path to a file needs to be passed in as \"blob_path\" '\n 'or the contents of a blob as \"blob_content.\"'\n )\n\n blob_kwargs = {\n 'container_name': kwargs['container'],\n 'blob_name': kwargs['name'],\n 'cache_control': kwargs.get('cache_control', None),\n 'content_language': kwargs.get('content_language', None),\n 'content_md5': kwargs.get('content_md5', None),\n 'x_ms_blob_content_type': kwargs.get('blob_content_type', None),\n 'x_ms_blob_content_encoding': kwargs.get('blob_content_encoding', None),\n 'x_ms_blob_content_language': kwargs.get('blob_content_language', None),\n 'x_ms_blob_content_md5': kwargs.get('blob_content_md5', None),\n 'x_ms_blob_cache_control': kwargs.get('blob_cache_control', None),\n 'x_ms_meta_name_values': kwargs.get('meta_name_values', None),\n 'x_ms_lease_id': kwargs.get('lease_id', None),\n }\n if 'blob_path' in kwargs:\n data = storage_conn.put_block_blob_from_path(\n file_path=kwargs['blob_path'],\n **blob_kwargs\n )\n elif 'blob_content' in kwargs:\n data = storage_conn.put_block_blob_from_bytes(\n blob=kwargs['blob_content'],\n **blob_kwargs\n )\n\n return data\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
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 'azure',
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'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(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 create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
saltstack/salt
|
salt/cloud/clouds/msazure.py
|
query
|
python
|
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
'''
Perform a query directly against the Azure REST API
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
backend = config.get_cloud_config_value(
'backend',
get_configured_provider(), __opts__, search_global=False
)
url = 'https://{management_host}/{subscription_id}/{path}'.format(
management_host=management_host,
subscription_id=subscription_id,
path=path,
)
if header_dict is None:
header_dict = {}
header_dict['x-ms-version'] = '2014-06-01'
result = salt.utils.http.query(
url,
method=method,
params=params,
data=data,
header_dict=header_dict,
port=443,
text=True,
cert=certificate_path,
backend=backend,
decode=decode,
decode_type='xml',
)
if 'dict' in result:
return result['dict']
return
|
Perform a query directly against the Azure REST API
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/cloud/clouds/msazure.py#L3369-L3420
|
[
"def get_cloud_config_value(name, vm_, opts, default=None, search_global=True):\n '''\n Search and return a setting in a known order:\n\n 1. In the virtual machine's configuration\n 2. In the virtual machine's profile configuration\n 3. In the virtual machine's provider configuration\n 4. In the salt cloud configuration if global searching is enabled\n 5. Return the provided default\n '''\n\n # As a last resort, return the default\n value = default\n\n if search_global is True and opts.get(name, None) is not None:\n # The setting name exists in the cloud(global) configuration\n value = deepcopy(opts[name])\n\n if vm_ and name:\n # Let's get the value from the profile, if present\n if 'profile' in vm_ and vm_['profile'] is not None:\n if name in opts['profiles'][vm_['profile']]:\n if isinstance(value, dict):\n value.update(opts['profiles'][vm_['profile']][name].copy())\n else:\n value = deepcopy(opts['profiles'][vm_['profile']][name])\n\n # Let's get the value from the provider, if present.\n if ':' in vm_['driver']:\n # The provider is defined as <provider-alias>:<driver-name>\n alias, driver = vm_['driver'].split(':')\n if alias in opts['providers'] and \\\n driver in opts['providers'][alias]:\n details = opts['providers'][alias][driver]\n if name in details:\n if isinstance(value, dict):\n value.update(details[name].copy())\n else:\n value = deepcopy(details[name])\n elif len(opts['providers'].get(vm_['driver'], ())) > 1:\n # The provider is NOT defined as <provider-alias>:<driver-name>\n # and there's more than one entry under the alias.\n # WARN the user!!!!\n log.error(\n \"The '%s' cloud provider definition has more than one \"\n 'entry. Your VM configuration should be specifying the '\n \"provider as 'driver: %s:<driver-engine>'. Since \"\n \"it's not, we're returning the first definition which \"\n 'might not be what you intended.',\n vm_['driver'], vm_['driver']\n )\n\n if vm_['driver'] in opts['providers']:\n # There's only one driver defined for this provider. This is safe.\n alias_defs = opts['providers'].get(vm_['driver'])\n provider_driver_defs = alias_defs[next(iter(list(alias_defs.keys())))]\n if name in provider_driver_defs:\n # The setting name exists in the VM's provider configuration.\n # Return it!\n if isinstance(value, dict):\n value.update(provider_driver_defs[name].copy())\n else:\n value = deepcopy(provider_driver_defs[name])\n\n if name and vm_ and name in vm_:\n # The setting name exists in VM configuration.\n if isinstance(vm_[name], types.GeneratorType):\n value = next(vm_[name], '')\n else:\n if isinstance(value, dict) and isinstance(vm_[name], dict):\n value.update(vm_[name].copy())\n else:\n value = deepcopy(vm_[name])\n\n return value\n",
"def to_str(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str, bytes, bytearray, or unicode (py2), return str\n '''\n def _normalize(s):\n try:\n return unicodedata.normalize('NFC', s) if normalize else s\n except TypeError:\n return s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n # This shouldn't be six.string_types because if we're on PY2 and we already\n # have a string, we should just return it.\n if isinstance(s, str):\n return _normalize(s)\n\n exc = None\n if six.PY3:\n if isinstance(s, (bytes, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytes, or bytearray not {}'.format(type(s)))\n else:\n if isinstance(s, bytearray):\n return str(s) # future lint: disable=blacklisted-function\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n for enc in encoding:\n try:\n return _normalize(s).encode(enc, errors)\n except UnicodeEncodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytearray, or unicode')\n",
"def get_configured_provider():\n '''\n Return the first configured instance.\n '''\n return config.is_provider_configured(\n __opts__,\n __active_provider_name__ or __virtualname__,\n ('subscription_id', 'certificate_path')\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Azure Cloud Module
==================
The Azure cloud module is used to control access to Microsoft Azure
:depends:
* `Microsoft Azure SDK for Python <https://pypi.python.org/pypi/azure/1.0.2>`_ >= 1.0.2
* python-requests, for Python < 2.7.9
:configuration:
Required provider parameters:
* ``apikey``
* ``certificate_path``
* ``subscription_id``
* ``backend``
A Management Certificate (.pem and .crt files) must be created and the .pem
file placed on the same machine that salt-cloud is run from. Information on
creating the pem file to use, and uploading the associated cer file can be
found at:
http://www.windowsazure.com/en-us/develop/python/how-to-guides/service-management/
For users with Python < 2.7.9, ``backend`` must currently be set to ``requests``.
Example ``/etc/salt/cloud.providers`` or
``/etc/salt/cloud.providers.d/azure.conf`` configuration:
.. code-block:: yaml
my-azure-config:
driver: azure
subscription_id: 3287abc8-f98a-c678-3bde-326766fd3617
certificate_path: /etc/salt/azure.pem
management_host: management.core.windows.net
'''
# pylint: disable=E0102
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import pprint
import time
# Import salt libs
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
import salt.utils.cloud
import salt.utils.stringutils
import salt.utils.yaml
# Import 3rd-party libs
from salt.ext import six
HAS_LIBS = False
try:
import azure
import azure.storage
import azure.servicemanagement
from azure.common import (AzureConflictHttpError,
AzureMissingResourceHttpError,
AzureException)
import salt.utils.msazure
from salt.utils.msazure import object_to_dict
HAS_LIBS = True
except ImportError:
pass
__virtualname__ = 'azure'
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the AZURE configurations are in place
def __virtual__():
'''
Check for Azure configurations.
'''
if get_configured_provider() is False:
return False
if get_dependencies() is False:
return False
return __virtualname__
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or __virtualname__,
('subscription_id', 'certificate_path')
)
def get_dependencies():
'''
Warn if dependencies aren't met.
'''
return config.check_driver_dependencies(
__virtualname__,
{'azure': HAS_LIBS}
)
def get_conn():
'''
Return a conn object for the passed VM data
'''
certificate_path = config.get_cloud_config_value(
'certificate_path',
get_configured_provider(), __opts__, search_global=False
)
subscription_id = salt.utils.stringutils.to_str(
config.get_cloud_config_value(
'subscription_id',
get_configured_provider(), __opts__, search_global=False
)
)
management_host = config.get_cloud_config_value(
'management_host',
get_configured_provider(),
__opts__,
search_global=False,
default='management.core.windows.net'
)
return azure.servicemanagement.ServiceManagementService(
subscription_id, certificate_path, management_host
)
def script(vm_):
'''
Return the script deployment object
'''
return salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
def avail_locations(conn=None, call=None):
'''
List available locations for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
if not conn:
conn = get_conn()
ret = {}
locations = conn.list_locations()
for location in locations:
ret[location.name] = {
'name': location.name,
'display_name': location.display_name,
'available_services': location.available_services,
}
return ret
def avail_images(conn=None, call=None):
'''
List available images for Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
if not conn:
conn = get_conn()
ret = {}
for item in conn.list_os_images():
ret[item.name] = object_to_dict(item)
for item in conn.list_vm_images():
ret[item.name] = object_to_dict(item)
return ret
def avail_sizes(call=None):
'''
Return a list of sizes from Azure
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
conn = get_conn()
data = conn.list_role_sizes()
ret = {}
for item in data.role_sizes:
ret[item.name] = object_to_dict(item)
return ret
def list_nodes(conn=None, call=None):
'''
List VMs on this Azure account
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full(conn, call)
for node in nodes:
ret[node] = {'name': node}
for prop in ('id', 'image', 'size', 'state', 'private_ips', 'public_ips'):
ret[node][prop] = nodes[node].get(prop)
return ret
def list_nodes_full(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
ret = {}
services = list_hosted_services(conn=conn, call=call)
for service in services:
for deployment in services[service]['deployments']:
deploy_dict = services[service]['deployments'][deployment]
deploy_dict_no_role_info = copy.deepcopy(deploy_dict)
del deploy_dict_no_role_info['role_list']
del deploy_dict_no_role_info['role_instance_list']
roles = deploy_dict['role_list']
for role in roles:
role_instances = deploy_dict['role_instance_list']
ret[role] = roles[role]
ret[role].update(role_instances[role])
ret[role]['id'] = role
ret[role]['hosted_service'] = service
if role_instances[role]['power_state'] == 'Started':
ret[role]['state'] = 'running'
elif role_instances[role]['power_state'] == 'Stopped':
ret[role]['state'] = 'stopped'
else:
ret[role]['state'] = 'pending'
ret[role]['private_ips'] = []
ret[role]['public_ips'] = []
ret[role]['deployment'] = deploy_dict_no_role_info
ret[role]['url'] = deploy_dict['url']
ip_address = role_instances[role]['ip_address']
if ip_address:
if salt.utils.cloud.is_public_ip(ip_address):
ret[role]['public_ips'].append(ip_address)
else:
ret[role]['private_ips'].append(ip_address)
ret[role]['size'] = role_instances[role]['instance_size']
ret[role]['image'] = roles[role]['role_info']['os_virtual_hard_disk']['source_image_name']
return ret
def list_hosted_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_hosted_services function must be called with '
'-f or --function'
)
if not conn:
conn = get_conn()
ret = {}
services = conn.list_hosted_services()
for service in services:
props = service.hosted_service_properties
ret[service.service_name] = {
'name': service.service_name,
'url': service.url,
'affinity_group': props.affinity_group,
'date_created': props.date_created,
'date_last_modified': props.date_last_modified,
'description': props.description,
'extended_properties': props.extended_properties,
'label': props.label,
'location': props.location,
'status': props.status,
'deployments': {},
}
deployments = conn.get_hosted_service_properties(
service_name=service.service_name, embed_detail=True
)
for deployment in deployments.deployments:
ret[service.service_name]['deployments'][deployment.name] = {
'configuration': deployment.configuration,
'created_time': deployment.created_time,
'deployment_slot': deployment.deployment_slot,
'extended_properties': deployment.extended_properties,
'input_endpoint_list': deployment.input_endpoint_list,
'label': deployment.label,
'last_modified_time': deployment.last_modified_time,
'locked': deployment.locked,
'name': deployment.name,
'persistent_vm_downtime_info': deployment.persistent_vm_downtime_info,
'private_id': deployment.private_id,
'role_instance_list': {},
'role_list': {},
'rollback_allowed': deployment.rollback_allowed,
'sdk_version': deployment.sdk_version,
'status': deployment.status,
'upgrade_domain_count': deployment.upgrade_domain_count,
'upgrade_status': deployment.upgrade_status,
'url': deployment.url,
}
for role_instance in deployment.role_instance_list:
ret[service.service_name]['deployments'][deployment.name]['role_instance_list'][role_instance.role_name] = {
'fqdn': role_instance.fqdn,
'instance_error_code': role_instance.instance_error_code,
'instance_fault_domain': role_instance.instance_fault_domain,
'instance_name': role_instance.instance_name,
'instance_size': role_instance.instance_size,
'instance_state_details': role_instance.instance_state_details,
'instance_status': role_instance.instance_status,
'instance_upgrade_domain': role_instance.instance_upgrade_domain,
'ip_address': role_instance.ip_address,
'power_state': role_instance.power_state,
'role_name': role_instance.role_name,
}
for role in deployment.role_list:
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name] = {
'role_name': role.role_name,
'os_version': role.os_version,
}
role_info = conn.get_role(
service_name=service.service_name,
deployment_name=deployment.name,
role_name=role.role_name,
)
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info'] = {
'availability_set_name': role_info.availability_set_name,
'configuration_sets': role_info.configuration_sets,
'data_virtual_hard_disks': role_info.data_virtual_hard_disks,
'os_version': role_info.os_version,
'role_name': role_info.role_name,
'role_size': role_info.role_size,
'role_type': role_info.role_type,
}
ret[service.service_name]['deployments'][deployment.name]['role_list'][role.role_name]['role_info']['os_virtual_hard_disk'] = {
'disk_label': role_info.os_virtual_hard_disk.disk_label,
'disk_name': role_info.os_virtual_hard_disk.disk_name,
'host_caching': role_info.os_virtual_hard_disk.host_caching,
'media_link': role_info.os_virtual_hard_disk.media_link,
'os': role_info.os_virtual_hard_disk.os,
'source_image_name': role_info.os_virtual_hard_disk.source_image_name,
}
return ret
def list_nodes_select(conn=None, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if not conn:
conn = get_conn()
return salt.utils.cloud.list_nodes_select(
list_nodes_full(conn, 'function'), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from the provider concerning an instance
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
# Find under which cloud service the name is listed, if any
if name not in nodes:
return {}
if 'name' not in nodes[name]:
nodes[name]['name'] = nodes[name]['id']
try:
__utils__['cloud.cache_node'](nodes[name], __active_provider_name__, __opts__)
except TypeError:
log.warning('Unable to show cache node data; this may be because the node has been deleted')
return nodes[name]
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 'azure',
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'])
conn = get_conn()
label = vm_.get('label', vm_['name'])
service_name = vm_.get('service_name', vm_['name'])
service_kwargs = {
'service_name': service_name,
'label': label,
'description': vm_.get('desc', vm_['name']),
}
loc_error = False
if 'location' in vm_:
if 'affinity_group' in vm_:
loc_error = True
else:
service_kwargs['location'] = vm_['location']
elif 'affinity_group' in vm_:
service_kwargs['affinity_group'] = vm_['affinity_group']
else:
loc_error = True
if loc_error:
raise SaltCloudSystemExit(
'Either a location or affinity group must be specified, but not both'
)
ssh_port = config.get_cloud_config_value('port', vm_, __opts__,
default=22, search_global=True)
ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SSH',
protocol='TCP',
port=ssh_port,
local_port=22,
)
network_config = azure.servicemanagement.ConfigurationSet()
network_config.input_endpoints.input_endpoints.append(ssh_endpoint)
network_config.configuration_set_type = 'NetworkConfiguration'
if 'win_username' in vm_:
system_config = azure.servicemanagement.WindowsConfigurationSet(
computer_name=vm_['name'],
admin_username=vm_['win_username'],
admin_password=vm_['win_password'],
)
smb_port = '445'
if 'smb_port' in vm_:
smb_port = vm_['smb_port']
smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint(
name='SMB',
protocol='TCP',
port=smb_port,
local_port=smb_port,
)
network_config.input_endpoints.input_endpoints.append(smb_endpoint)
# Domain and WinRM configuration not yet supported by Salt Cloud
system_config.domain_join = None
system_config.win_rm = None
else:
system_config = azure.servicemanagement.LinuxConfigurationSet(
host_name=vm_['name'],
user_name=vm_['ssh_username'],
user_password=vm_['ssh_password'],
disable_ssh_password_authentication=False,
)
# TODO: Might need to create a storage account
media_link = vm_['media_link']
# TODO: Probably better to use more than just the name in the media_link
media_link += '/{0}.vhd'.format(vm_['name'])
os_hd = azure.servicemanagement.OSVirtualHardDisk(vm_['image'], media_link)
vm_kwargs = {
'service_name': service_name,
'deployment_name': service_name,
'deployment_slot': vm_['slot'],
'label': label,
'role_name': vm_['name'],
'system_config': system_config,
'os_virtual_hard_disk': os_hd,
'role_size': vm_['size'],
'network_config': network_config,
}
if 'virtual_network_name' in vm_:
vm_kwargs['virtual_network_name'] = vm_['virtual_network_name']
if 'subnet_name' in vm_:
network_config.subnet_names.append(vm_['subnet_name'])
log.debug('vm_kwargs: %s', vm_kwargs)
event_kwargs = {'service_kwargs': service_kwargs.copy(),
'vm_kwargs': vm_kwargs.copy()}
del event_kwargs['vm_kwargs']['system_config']
del event_kwargs['vm_kwargs']['os_virtual_hard_disk']
del event_kwargs['vm_kwargs']['network_config']
__utils__['cloud.fire_event'](
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
args=__utils__['cloud.filter_event']('requesting', event_kwargs, list(event_kwargs)),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.debug('vm_kwargs: %s', vm_kwargs)
# Azure lets you open winrm on a new VM
# Can open up specific ports in Azure; but not on Windows
try:
conn.create_hosted_service(**service_kwargs)
except AzureConflictHttpError:
log.debug('Cloud service already exists')
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The hosted service name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
try:
result = conn.create_virtual_machine_deployment(**vm_kwargs)
log.debug('Request ID for machine: %s', result.request_id)
_wait_for_async(conn, result.request_id)
except AzureConflictHttpError:
log.debug('Conflict error. The deployment may already exist, trying add_role')
# Deleting two useless keywords
del vm_kwargs['deployment_slot']
del vm_kwargs['label']
del vm_kwargs['virtual_network_name']
result = conn.add_role(**vm_kwargs)
_wait_for_async(conn, result.request_id)
except Exception as exc:
error = 'The hosted service name is invalid.'
if error in six.text_type(exc):
log.error(
'Error creating %s on Azure.\n\n'
'The VM name is invalid. The name can contain '
'only letters, numbers, and hyphens. The name must start with '
'a letter and must end with a letter or a number.',
vm_['name'],
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
else:
log.error(
'Error creating %s on Azure.\n\n'
'The Virtual Machine could not be created. If you '
'are using an already existing Cloud Service, '
'make sure you set up the `port` variable corresponding '
'to the SSH port exists and that the port number is not '
'already in use.\nThe following exception was thrown when trying to '
'run the initial deployment: \n%s',
vm_['name'], exc,
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_hostname():
'''
Wait for the IP address to become available
'''
try:
conn.get_role(service_name, service_name, vm_['name'])
data = show_instance(vm_['name'], call='action')
if 'url' in data and data['url'] != six.text_type(''):
return data['url']
except AzureMissingResourceHttpError:
pass
time.sleep(1)
return False
hostname = salt.utils.cloud.wait_for_fun(
wait_for_hostname,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
if not hostname:
log.error('Failed to get a value for the hostname.')
return False
vm_['ssh_host'] = hostname.replace('http://', '').replace('/', '')
vm_['password'] = config.get_cloud_config_value(
'ssh_password', vm_, __opts__
)
ret = __utils__['cloud.bootstrap'](vm_, __opts__)
# Attaching volumes
volumes = config.get_cloud_config_value(
'volumes', vm_, __opts__, search_global=True
)
if volumes:
__utils__['cloud.fire_event'](
'event',
'attaching volumes',
'salt/cloud/{0}/attaching_volumes'.format(vm_['name']),
args=__utils__['cloud.filter_event']('attaching_volumes', vm_, ['volumes']),
sock_dir=__opts__['sock_dir'],
transport=__opts__['transport']
)
log.info('Create and attach volumes to node %s', vm_['name'])
created = create_attach_volumes(
vm_['name'],
{
'volumes': volumes,
'service_name': service_name,
'deployment_name': vm_['name'],
'media_link': media_link,
'role_name': vm_['name'],
'del_all_vols_on_destroy': vm_.get('set_del_all_vols_on_destroy', False)
},
call='action'
)
ret['Attached Volumes'] = created
data = show_instance(vm_['name'], call='action')
log.info('Created Cloud VM \'%s\'', vm_)
log.debug('\'%s\' VM creation details:\n%s', vm_['name'], pprint.pformat(data))
ret.update(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 create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
attach = conn.add_data_disk(kwargs["service_name"], kwargs["deployment_name"], kwargs["role_name"],
**volume)
log.debug(attach)
# If attach is None then everything is fine
if attach:
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name,
)
)
log.info(msg)
ret.append(msg)
else:
log.error('Error attaching %s on Azure', volume_dict)
return ret
def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True):
'''
Create and attach volumes to created node
'''
if call != 'action':
raise SaltCloudSystemExit(
'The create_attach_volumes action must be called with '
'-a or --action.'
)
if kwargs is None:
kwargs = {}
if isinstance(kwargs['volumes'], six.string_types):
volumes = salt.utils.yaml.safe_load(kwargs['volumes'])
else:
volumes = kwargs['volumes']
# From the Azure .NET SDK doc
#
# The Create Data Disk operation adds a data disk to a virtual
# machine. There are three ways to create the data disk using the
# Add Data Disk operation.
# Option 1 - Attach an empty data disk to
# the role by specifying the disk label and location of the disk
# image. Do not include the DiskName and SourceMediaLink elements in
# the request body. Include the MediaLink element and reference a
# blob that is in the same geographical region as the role. You can
# also omit the MediaLink element. In this usage, Azure will create
# the data disk in the storage account configured as default for the
# role.
# Option 2 - Attach an existing data disk that is in the image
# repository. Do not include the DiskName and SourceMediaLink
# elements in the request body. Specify the data disk to use by
# including the DiskName element. Note: If included the in the
# response body, the MediaLink and LogicalDiskSizeInGB elements are
# ignored.
# Option 3 - Specify the location of a blob in your storage
# account that contain a disk image to use. Include the
# SourceMediaLink element. Note: If the MediaLink element
# isincluded, it is ignored. (see
# http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx
# for more information)
#
# Here only option 1 is implemented
conn = get_conn()
ret = []
for volume in volumes:
if "disk_name" in volume:
log.error("You cannot specify a disk_name. Only new volumes are allowed")
return False
# Use the size keyword to set a size, but you can use the
# azure name too. If neither is set, the disk has size 100GB
volume.setdefault("logical_disk_size_in_gb", volume.get("size", 100))
volume.setdefault("host_caching", "ReadOnly")
volume.setdefault("lun", 0)
# The media link is vm_name-disk-[0-15].vhd
volume.setdefault("media_link",
kwargs["media_link"][:-4] + "-disk-{0}.vhd".format(volume["lun"]))
volume.setdefault("disk_label",
kwargs["role_name"] + "-disk-{0}".format(volume["lun"]))
volume_dict = {
'volume_name': volume["lun"],
'disk_label': volume["disk_label"]
}
# Preparing the volume dict to be passed with **
kwargs_add_data_disk = ["lun", "host_caching", "media_link",
"disk_label", "disk_name",
"logical_disk_size_in_gb",
"source_media_link"]
for key in set(volume.keys()) - set(kwargs_add_data_disk):
del volume[key]
result = conn.add_data_disk(kwargs["service_name"],
kwargs["deployment_name"],
kwargs["role_name"],
**volume)
_wait_for_async(conn, result.request_id)
msg = (
'{0} attached to {1} (aka {2})'.format(
volume_dict['volume_name'],
kwargs['role_name'],
name)
)
log.info(msg)
ret.append(msg)
return ret
# Helper function for azure tests
def _wait_for_async(conn, request_id):
'''
Helper function for azure tests
'''
count = 0
log.debug('Waiting for asynchronous operation to complete')
result = conn.get_operation_status(request_id)
while result.status == 'InProgress':
count = count + 1
if count > 120:
raise ValueError('Timed out waiting for asynchronous operation to complete.')
time.sleep(5)
result = conn.get_operation_status(request_id)
if result.status != 'Succeeded':
raise AzureException('Operation failed. {message} ({code})'
.format(message=result.error.message,
code=result.error.code))
def destroy(name, conn=None, call=None, kwargs=None):
'''
Destroy a VM
CLI Examples:
.. code-block:: bash
salt-cloud -d myminion
salt-cloud -a destroy myminion service_name=myservice
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
instance_data = show_instance(name, call='action')
service_name = instance_data['deployment']['name']
disk_name = instance_data['role_info']['os_virtual_hard_disk']['disk_name']
ret = {}
# TODO: Add the ability to delete or not delete a hosted service when
# deleting a VM
try:
log.debug('Deleting role')
result = conn.delete_role(service_name, service_name, name)
delete_type = 'delete_role'
except AzureException:
log.debug('Failed to delete role, deleting deployment')
try:
result = conn.delete_deployment(service_name, service_name)
except AzureConflictHttpError as exc:
log.error(exc.message)
raise SaltCloudSystemExit('{0}: {1}'.format(name, exc.message))
delete_type = 'delete_deployment'
_wait_for_async(conn, result.request_id)
ret[name] = {
delete_type: {'request_id': result.request_id},
}
if __opts__.get('update_cachedir', False) is True:
__utils__['cloud.delete_minion_cachedir'](name, __active_provider_name__.split(':')[0], __opts__)
cleanup_disks = config.get_cloud_config_value(
'cleanup_disks',
get_configured_provider(), __opts__, search_global=False, default=False,
)
if cleanup_disks:
cleanup_vhds = kwargs.get('delete_vhd', config.get_cloud_config_value(
'cleanup_vhds',
get_configured_provider(), __opts__, search_global=False, default=False,
))
log.debug('Deleting disk %s', disk_name)
if cleanup_vhds:
log.debug('Deleting vhd')
def wait_for_destroy():
'''
Wait for the VM to be deleted
'''
try:
data = delete_disk(kwargs={'name': disk_name, 'delete_vhd': cleanup_vhds}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for VM to be destroyed...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_destroy,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_disk'] = {
'name': disk_name,
'delete_vhd': cleanup_vhds,
'data': data
}
# Services can't be cleaned up unless disks are too
cleanup_services = config.get_cloud_config_value(
'cleanup_services',
get_configured_provider(), __opts__, search_global=False, default=False
)
if cleanup_services:
log.debug('Deleting service %s', service_name)
def wait_for_disk_delete():
'''
Wait for the disk to be deleted
'''
try:
data = delete_service(kwargs={'name': service_name}, call='function')
return data
except AzureConflictHttpError:
log.debug('Waiting for disk to be deleted...')
time.sleep(5)
return False
data = salt.utils.cloud.wait_for_fun(
wait_for_disk_delete,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', {}, __opts__, default=15 * 60),
)
ret[name]['delete_services'] = {
'name': service_name,
'data': data
}
return ret
def list_storage_services(conn=None, call=None):
'''
List VMs on this Azure account, with full information
'''
if call != 'function':
raise SaltCloudSystemExit(
('The list_storage_services function must be called '
'with -f or --function.')
)
if not conn:
conn = get_conn()
ret = {}
accounts = conn.list_storage_accounts()
for service in accounts.storage_services:
ret[service.service_name] = {
'capabilities': service.capabilities,
'service_name': service.service_name,
'storage_service_properties': service.storage_service_properties,
'extended_properties': service.extended_properties,
'storage_service_keys': service.storage_service_keys,
'url': service.url,
}
return ret
def get_operation_status(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Get Operation Status, based on a request ID
CLI Example:
.. code-block:: bash
salt-cloud -f get_operation_status my-azure id=0123456789abcdef0123456789abcdef
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_instance function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'id' not in kwargs:
raise SaltCloudSystemExit('A request ID must be specified as "id"')
if not conn:
conn = get_conn()
data = conn.get_operation_status(kwargs['id'])
ret = {
'http_status_code': data.http_status_code,
'id': kwargs['id'],
'status': data.status
}
if hasattr(data.error, 'code'):
ret['error'] = {
'code': data.error.code,
'message': data.error.message,
}
return ret
def list_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage accounts associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_storage_accounts()
pprint.pprint(dir(data))
ret = {}
for item in data.storage_services:
ret[item.service_name] = object_to_dict(item)
return ret
def show_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List storage service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_storage_account_properties(
kwargs['name'],
)
return object_to_dict(data)
# To reflect the Azure API
get_storage = show_storage
def show_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show storage account keys
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_keys my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_keys function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
try:
data = conn.get_storage_account_keys(
kwargs['name'],
)
except AzureMissingResourceHttpError as exc:
storage_data = show_storage(kwargs={'name': kwargs['name']}, call='function')
if storage_data['storage_service_properties']['status'] == 'Creating':
raise SaltCloudSystemExit('The storage account keys have not yet been created.')
else:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
return object_to_dict(data)
# To reflect the Azure API
get_storage_keys = show_storage_keys
def create_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new storage account
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage my-azure name=my_storage label=my_storage location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if not conn:
conn = get_conn()
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'description' not in kwargs:
raise SaltCloudSystemExit('A description must be specified as "description"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_storage_account(
service_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
location=kwargs.get('location', None),
affinity_group=kwargs.get('affinity_group', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return {'Success': 'The storage account was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def update_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a storage account's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_storage my-azure name=my_storage label=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.update_storage_account(
service_name=kwargs['name'],
label=kwargs.get('label', None),
description=kwargs.get('description', None),
extended_properties=kwargs.get('extended_properties', None),
geo_replication_enabled=kwargs.get('geo_replication_enabled', None),
account_type=kwargs.get('account_type', 'Standard_GRS'),
)
return show_storage(kwargs={'name': kwargs['name']}, call='function')
def regenerate_storage_keys(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Regenerate storage account keys. Requires a key_type ("primary" or
"secondary") to be specified.
CLI Example:
.. code-block:: bash
salt-cloud -f regenerate_storage_keys my-azure name=my_storage key_type=primary
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'key_type' not in kwargs or kwargs['key_type'] not in ('primary', 'secondary'):
raise SaltCloudSystemExit('A key_type must be specified ("primary" or "secondary")')
try:
data = conn.regenerate_storage_account_keys(
service_name=kwargs['name'],
key_type=kwargs['key_type'],
)
return show_storage_keys(kwargs={'name': kwargs['name']}, call='function')
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage account already exists.')
def delete_storage(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific storage account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_storage my-azure name=my_storage
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_storage_account(kwargs['name'])
return {'Success': 'The storage account was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_services(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted services associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_services my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_services function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_hosted_services()
ret = {}
for item in data.hosted_services:
ret[item.service_name] = object_to_dict(item)
ret[item.service_name]['name'] = item.service_name
return ret
def show_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List hosted service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_hosted_service_properties(
kwargs['name'],
kwargs.get('details', False)
)
ret = object_to_dict(data)
return ret
def create_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new hosted service
CLI Example:
.. code-block:: bash
salt-cloud -f create_service my-azure name=my_service label=my_service location='West US'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_service function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs and 'affinity_group' not in kwargs:
raise SaltCloudSystemExit('Either a location or an affinity_group '
'must be specified (but not both)')
try:
data = conn.create_hosted_service(
kwargs['name'],
kwargs['label'],
kwargs.get('description', None),
kwargs.get('location', None),
kwargs.get('affinity_group', None),
kwargs.get('extended_properties', None),
)
return {'Success': 'The service was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the service already exists.')
def delete_service(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific service associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_hosted_service(kwargs['name'])
return {'Success': 'The service was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List disks associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f list_disks my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_disks function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_disks()
ret = {}
for item in data.disks:
ret[item.name] = object_to_dict(item)
return ret
def show_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a disk
CLI Example:
.. code-block:: bash
salt-cloud -f show_disk my-azure name=my_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
data = conn.get_disk(kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_disk = show_disk
def cleanup_unattached_disks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Cleans up all disks associated with the account, which are not attached.
*** CAUTION *** This is a destructive function with no undo button, and no
"Are you sure?" confirmation!
CLI Examples:
.. code-block:: bash
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk
salt-cloud -f cleanup_unattached_disks my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
disks = list_disks(kwargs=kwargs, conn=conn, call='function')
for disk in disks:
if disks[disk]['attached_to'] is None:
del_kwargs = {
'name': disks[disk]['name'],
'delete_vhd': kwargs.get('delete_vhd', False)
}
log.info(
'Deleting disk %s, deleting VHD: %s',
del_kwargs['name'], del_kwargs['delete_vhd']
)
data = delete_disk(kwargs=del_kwargs, call='function')
return True
def delete_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific disk associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_disk my-azure name=my_disk
salt-cloud -f delete_disk my-azure name=my_disk delete_vhd=True
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_disk function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
data = conn.delete_disk(kwargs['name'], kwargs.get('delete_vhd', False))
return {'Success': 'The disk was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def update_disk(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update a disk's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_disk my-azure name=my_disk label=my_disk
salt-cloud -f update_disk my-azure name=my_disk new_name=another_disk
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_disk function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
old_data = show_disk(kwargs={'name': kwargs['name']}, call='function')
data = conn.update_disk(
disk_name=kwargs['name'],
has_operating_system=kwargs.get('has_operating_system', old_data['has_operating_system']),
label=kwargs.get('label', old_data['label']),
media_link=kwargs.get('media_link', old_data['media_link']),
name=kwargs.get('new_name', old_data['name']),
os=kwargs.get('os', old_data['os']),
)
return show_disk(kwargs={'name': kwargs['name']}, call='function')
def list_service_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List certificates associated with the service
CLI Example:
.. code-block:: bash
salt-cloud -f list_service_certificates my-azure name=my_service
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_service_certificates function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if not conn:
conn = get_conn()
data = conn.list_service_certificates(service_name=kwargs['name'])
ret = {}
for item in data.certificates:
ret[item.thumbprint] = object_to_dict(item)
return ret
def show_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f show_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_service_certificate = show_service_certificate
def add_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new service certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_service_certificate my-azure name=my_service_certificate \\
data='...CERT_DATA...' certificate_format=sha1 password=verybadpass
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_service_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
if 'certificate_format' not in kwargs:
raise SaltCloudSystemExit('A certificate_format must be specified as "certificate_format"')
if 'password' not in kwargs:
raise SaltCloudSystemExit('A password must be specified as "password"')
try:
data = conn.add_service_certificate(
kwargs['name'],
kwargs['data'],
kwargs['certificate_format'],
kwargs['password'],
)
return {'Success': 'The service certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the '
'service certificate already exists.')
def delete_service_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the service
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_service_certificate my-azure name=my_service_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_service_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'thumbalgorithm' not in kwargs:
raise SaltCloudSystemExit('A thumbalgorithm must be specified as "thumbalgorithm"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
data = conn.delete_service_certificate(
kwargs['name'],
kwargs['thumbalgorithm'],
kwargs['thumbprint'],
)
return {'Success': 'The service certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def list_management_certificates(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List management certificates associated with the subscription
CLI Example:
.. code-block:: bash
salt-cloud -f list_management_certificates my-azure name=my_management
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_management_certificates function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_management_certificates()
ret = {}
for item in data.subscription_certificates:
ret[item.subscription_certificate_thumbprint] = object_to_dict(item)
return ret
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
data = conn.get_management_certificate(kwargs['thumbprint'])
return object_to_dict(data)
# For consistency with Azure SDK
get_management_certificate = show_management_certificate
def add_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add a new management certificate
CLI Example:
.. code-block:: bash
salt-cloud -f add_management_certificate my-azure public_key='...PUBKEY...' \\
thumbprint=0123456789ABCDEF data='...CERT_DATA...'
'''
if call != 'function':
raise SaltCloudSystemExit(
'The add_management_certificate function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'public_key' not in kwargs:
raise SaltCloudSystemExit('A public_key must be specified as "public_key"')
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if 'data' not in kwargs:
raise SaltCloudSystemExit('Certificate data must be specified as "data"')
try:
conn.add_management_certificate(
kwargs['name'],
kwargs['thumbprint'],
kwargs['data'],
)
return {'Success': 'The management certificate was successfully added'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. '
'This usually means that the management certificate already exists.')
def delete_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific certificate associated with the management
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_management_certificate my-azure name=my_management_certificate \\
thumbalgorithm=sha1 thumbprint=0123456789ABCDEF
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_management_certificate function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'thumbprint' not in kwargs:
raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"')
if not conn:
conn = get_conn()
try:
conn.delete_management_certificate(kwargs['thumbprint'])
return {'Success': 'The management certificate was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['thumbprint'], exc.message))
def list_virtual_networks(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_virtual_networks my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_virtual_networks function must be called with -f or --function.'
)
path = 'services/networking/virtualnetwork'
data = query(path)
return data
def list_input_endpoints(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_input_endpoints my-azure service=myservice deployment=mydeployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_input_endpoints function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
path = 'services/hostedservices/{0}/deployments/{1}'.format(
kwargs['service'],
kwargs['deployment'],
)
data = query(path)
if data is None:
raise SaltCloudSystemExit(
'There was an error listing endpoints with the {0} service on the {1} deployment.'.format(
kwargs['service'],
kwargs['deployment']
)
)
ret = {}
for item in data:
if 'Role' in item:
role = item['Role']
if not isinstance(role, dict):
return ret
input_endpoint = role['ConfigurationSets']['ConfigurationSet'].get('InputEndpoints', {}).get('InputEndpoint')
if not input_endpoint:
continue
if not isinstance(input_endpoint, list):
input_endpoint = [input_endpoint]
for endpoint in input_endpoint:
ret[endpoint['Name']] = endpoint
return ret
return ret
def show_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an input endpoint associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_input_endpoint my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
data = list_input_endpoints(kwargs=kwargs, call='function')
return data.get(kwargs['name'], None)
# For consistency with Azure SDK
get_input_endpoint = show_input_endpoint
def update_input_endpoint(kwargs=None, conn=None, call=None, activity='update'):
'''
.. versionadded:: 2015.8.0
Update an input endpoint associated with the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f update_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_input_endpoint function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'service' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service"')
if 'deployment' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('An endpoint name must be specified as "name"')
if 'role' not in kwargs:
raise SaltCloudSystemExit('An role name must be specified as "role"')
if activity != 'delete':
if 'port' not in kwargs:
raise SaltCloudSystemExit('An endpoint port must be specified as "port"')
if 'protocol' not in kwargs:
raise SaltCloudSystemExit('An endpoint protocol (tcp or udp) must be specified as "protocol"')
if 'local_port' not in kwargs:
kwargs['local_port'] = kwargs['port']
if 'enable_direct_server_return' not in kwargs:
kwargs['enable_direct_server_return'] = False
kwargs['enable_direct_server_return'] = six.text_type(kwargs['enable_direct_server_return']).lower()
if 'timeout_for_tcp_idle_connection' not in kwargs:
kwargs['timeout_for_tcp_idle_connection'] = 4
old_endpoints = list_input_endpoints(kwargs, call='function')
endpoints_xml = ''
endpoint_xml = '''
<InputEndpoint>
<LocalPort>{local_port}</LocalPort>
<Name>{name}</Name>
<Port>{port}</Port>
<Protocol>{protocol}</Protocol>
<EnableDirectServerReturn>{enable_direct_server_return}</EnableDirectServerReturn>
<IdleTimeoutInMinutes>{timeout_for_tcp_idle_connection}</IdleTimeoutInMinutes>
</InputEndpoint>'''
if activity == 'add':
old_endpoints[kwargs['name']] = kwargs
old_endpoints[kwargs['name']]['Name'] = kwargs['name']
for endpoint in old_endpoints:
if old_endpoints[endpoint]['Name'] == kwargs['name']:
if activity != 'delete':
this_endpoint_xml = endpoint_xml.format(**kwargs)
endpoints_xml += this_endpoint_xml
else:
this_endpoint_xml = endpoint_xml.format(
local_port=old_endpoints[endpoint]['LocalPort'],
name=old_endpoints[endpoint]['Name'],
port=old_endpoints[endpoint]['Port'],
protocol=old_endpoints[endpoint]['Protocol'],
enable_direct_server_return=old_endpoints[endpoint]['EnableDirectServerReturn'],
timeout_for_tcp_idle_connection=old_endpoints[endpoint].get('IdleTimeoutInMinutes', 4),
)
endpoints_xml += this_endpoint_xml
request_xml = '''<PersistentVMRole xmlns="http://schemas.microsoft.com/windowsazure"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ConfigurationSets>
<ConfigurationSet>
<ConfigurationSetType>NetworkConfiguration</ConfigurationSetType>
<InputEndpoints>{0}
</InputEndpoints>
</ConfigurationSet>
</ConfigurationSets>
<OSVirtualHardDisk>
</OSVirtualHardDisk>
</PersistentVMRole>'''.format(endpoints_xml)
path = 'services/hostedservices/{0}/deployments/{1}/roles/{2}'.format(
kwargs['service'],
kwargs['deployment'],
kwargs['role'],
)
query(
path=path,
method='PUT',
header_dict={'Content-Type': 'application/xml'},
data=request_xml,
decode=False,
)
return True
def add_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Add an input endpoint to the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f add_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP local_port=80 \\
port=80 protocol=tcp enable_direct_server_return=False \\
timeout_for_tcp_idle_connection=4
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='add',
)
def delete_input_endpoint(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete an input endpoint from the deployment. Please note that
there may be a delay before the changes show up.
CLI Example:
.. code-block:: bash
salt-cloud -f delete_input_endpoint my-azure service=myservice \\
deployment=mydeployment role=myrole name=HTTP
'''
return update_input_endpoint(
kwargs=kwargs,
conn=conn,
call='function',
activity='delete',
)
def show_deployment(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a deployment
CLI Example:
.. code-block:: bash
salt-cloud -f show_deployment my-azure name=my_deployment
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_deployment function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'service_name' not in kwargs:
raise SaltCloudSystemExit('A service name must be specified as "service_name"')
if 'deployment_name' not in kwargs:
raise SaltCloudSystemExit('A deployment name must be specified as "deployment_name"')
data = conn.get_deployment_by_name(
service_name=kwargs['service_name'],
deployment_name=kwargs['deployment_name'],
)
return object_to_dict(data)
# For consistency with Azure SDK
get_deployment = show_deployment
def list_affinity_groups(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List input endpoints associated with the deployment
CLI Example:
.. code-block:: bash
salt-cloud -f list_affinity_groups my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_affinity_groups function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
data = conn.list_affinity_groups()
ret = {}
for item in data.affinity_groups:
ret[item.name] = object_to_dict(item)
return ret
def show_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show an affinity group associated with the account
CLI Example:
.. code-block:: bash
salt-cloud -f show_affinity_group my-azure service=myservice \\
deployment=mydeployment name=SSH
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An affinity group name must be specified as "name"')
data = conn.get_affinity_group_properties(affinity_group_name=kwargs['name'])
return object_to_dict(data)
# For consistency with Azure SDK
get_affinity_group = show_affinity_group
def create_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a new affinity group
CLI Example:
.. code-block:: bash
salt-cloud -f create_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
if 'location' not in kwargs:
raise SaltCloudSystemExit('A location must be specified as "location"')
try:
conn.create_affinity_group(
kwargs['name'],
kwargs['label'],
kwargs['location'],
kwargs.get('description', None),
)
return {'Success': 'The affinity group was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the affinity group already exists.')
def update_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Update an affinity group's properties
CLI Example:
.. code-block:: bash
salt-cloud -f update_affinity_group my-azure name=my_group label=my_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The update_affinity_group function must be called with -f or --function.'
)
if not conn:
conn = get_conn()
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if 'label' not in kwargs:
raise SaltCloudSystemExit('A label must be specified as "label"')
conn.update_affinity_group(
affinity_group_name=kwargs['name'],
label=kwargs['label'],
description=kwargs.get('description', None),
)
return show_affinity_group(kwargs={'name': kwargs['name']}, call='function')
def delete_affinity_group(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a specific affinity group associated with the account
CLI Examples:
.. code-block:: bash
salt-cloud -f delete_affinity_group my-azure name=my_affinity_group
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_affinity_group function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('A name must be specified as "name"')
if not conn:
conn = get_conn()
try:
conn.delete_affinity_group(kwargs['name'])
return {'Success': 'The affinity group was successfully deleted'}
except AzureMissingResourceHttpError as exc:
raise SaltCloudSystemExit('{0}: {1}'.format(kwargs['name'], exc.message))
def get_storage_conn(storage_account=None, storage_key=None, conn_kwargs=None):
'''
.. versionadded:: 2015.8.0
Return a storage_conn object for the storage account
'''
if conn_kwargs is None:
conn_kwargs = {}
if not storage_account:
storage_account = config.get_cloud_config_value(
'storage_account',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_account', None)
)
if not storage_key:
storage_key = config.get_cloud_config_value(
'storage_key',
get_configured_provider(), __opts__, search_global=False,
default=conn_kwargs.get('storage_key', None)
)
return azure.storage.BlobService(storage_account, storage_key)
def make_blob_url(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Creates the URL to access a blob
CLI Example:
.. code-block:: bash
salt-cloud -f make_blob_url my-azure container=mycontainer blob=myblob
container:
Name of the container.
blob:
Name of the blob.
account:
Name of the storage account. If not specified, derives the host base
from the provider configuration.
protocol:
Protocol to use: 'http' or 'https'. If not specified, derives the host
base from the provider configuration.
host_base:
Live host base URL. If not specified, derives the host base from the
provider configuration.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The make_blob_url function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('A container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('A blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.make_blob_url(
kwargs['container'],
kwargs['blob'],
kwargs.get('account', None),
kwargs.get('protocol', None),
kwargs.get('host_base', None),
)
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def list_storage_containers(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List containers associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f list_storage_containers my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_storage_containers function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.list_containers()
ret = {}
for item in data.containers:
ret[item.name] = object_to_dict(item)
return ret
def create_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Create a storage container
CLI Example:
.. code-block:: bash
salt-cloud -f create_storage_container my-azure name=mycontainer
name:
Name of container to create.
meta_name_values:
Optional. A dict with name_value pairs to associate with the
container as metadata. Example:{'Category':'test'}
blob_public_access:
Optional. Possible values include: container, blob
fail_on_exist:
Specify whether to throw an exception when the container exists.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.create_container(
container_name=kwargs['name'],
x_ms_meta_name_values=kwargs.get('meta_name_values', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
fail_on_exist=kwargs.get('fail_on_exist', False),
)
return {'Success': 'The storage container was successfully created'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict. This usually means that the storage container already exists.')
def show_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container my-azure name=myservice
name:
Name of container to show.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_properties(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container = show_storage_container
def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_metadata my-azure name=myservice
name:
Name of container to show.
lease_id:
If specified, show_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_metadata(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_metadata = show_storage_container_metadata
def set_storage_container_metadata(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's metadata
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer \\
x_ms_meta_name_values='{"my_name": "my_value"}'
name:
Name of existing container.
meta_name_values:
A dict containing name, value for metadata.
Example: {'category':'test'}
lease_id:
If specified, set_storage_container_metadata only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
x_ms_meta_name_values = salt.utils.yaml.safe_load(
kwargs.get('meta_name_values', '')
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
storage_conn.set_container_metadata(
container_name=kwargs['name'],
x_ms_meta_name_values=x_ms_meta_name_values,
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def show_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f show_storage_container_acl my-azure name=myservice
name:
Name of existing container.
lease_id:
If specified, show_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_container_acl(
container_name=kwargs['name'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
# For consistency with Azure SDK
get_storage_container_acl = show_storage_container_acl
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed_identifiers:
SignedIdentifers instance
blob_public_access:
Optional. Possible values include: container, blob
lease_id:
If specified, set_storage_container_acl only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The create_storage_container function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.set_container_acl(
container_name=kwargs['name'],
signed_identifiers=kwargs.get('signed_identifiers', None),
x_ms_blob_public_access=kwargs.get('blob_public_access', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return {'Success': 'The storage container was successfully updated'}
except AzureConflictHttpError:
raise SaltCloudSystemExit('There was a conflict.')
def delete_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Delete a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f delete_storage_container my-azure name=mycontainer
name:
Name of container to create.
fail_not_exist:
Specify whether to throw an exception when the container exists.
lease_id:
If specified, delete_storage_container only succeeds if the
container's lease is active and matches this ID.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The delete_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.delete_container(
container_name=kwargs['name'],
fail_not_exist=kwargs.get('fail_not_exist', None),
x_ms_lease_id=kwargs.get('lease_id', None),
)
return data
def lease_storage_container(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Lease a container associated with the storage account
CLI Example:
.. code-block:: bash
salt-cloud -f lease_storage_container my-azure name=mycontainer
name:
Name of container to create.
lease_action:
Required. Possible values: acquire|renew|release|break|change
lease_id:
Required if the container has an active lease.
lease_duration:
Specifies the duration of the lease, in seconds, or negative one
(-1) for a lease that never expires. A non-infinite lease can be
between 15 and 60 seconds. A lease duration cannot be changed
using renew or change. For backwards compatibility, the default is
60, and the value is only used on an acquire operation.
lease_break_period:
Optional. For a break operation, this is the proposed duration of
seconds that the lease should continue before it is broken, between
0 and 60 seconds. This break period is only used if it is shorter
than the time remaining on the lease. If longer, the time remaining
on the lease is used. A new lease will not be available before the
break period has expired, but the lease may be held for longer than
the break period. If this header does not appear with a break
operation, a fixed-duration lease breaks after the remaining lease
period elapses, and an infinite lease breaks immediately.
proposed_lease_id:
Optional for acquire, required for change. Proposed lease ID, in a
GUID string format.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The lease_storage_container function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'name' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "name"')
lease_actions = ('acquire', 'renew', 'release', 'break', 'change')
if kwargs.get('lease_action', None) not in lease_actions:
raise SaltCloudSystemExit(
'A lease_action must be one of: {0}'.format(
', '.join(lease_actions)
)
)
if kwargs['lease_action'] != 'acquire' and 'lease_id' not in kwargs:
raise SaltCloudSystemExit(
'A lease ID must be specified for the "{0}" lease action '
'as "lease_id"'.format(kwargs['lease_action'])
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.lease_container(
container_name=kwargs['name'],
x_ms_lease_action=kwargs['lease_action'],
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_lease_duration=kwargs.get('lease_duration', 60),
x_ms_lease_break_period=kwargs.get('lease_break_period', None),
x_ms_proposed_lease_id=kwargs.get('proposed_lease_id', None),
)
return data
def list_blobs(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
List blobs associated with the container
CLI Example:
.. code-block:: bash
salt-cloud -f list_blobs my-azure container=mycontainer
container:
The name of the storage container
prefix:
Optional. Filters the results to return only blobs whose names
begin with the specified prefix.
marker:
Optional. A string value that identifies the portion of the list
to be returned with the next list operation. The operation returns
a marker value within the response body if the list returned was
not complete. The marker value may then be used in a subsequent
call to request the next set of list items. The marker value is
opaque to the client.
maxresults:
Optional. Specifies the maximum number of blobs to return,
including all BlobPrefix elements. If the request does not specify
maxresults or specifies a value greater than 5,000, the server will
return up to 5,000 items. Setting maxresults to a value less than
or equal to zero results in error response code 400 (Bad Request).
include:
Optional. Specifies one or more datasets to include in the
response. To specify more than one of these options on the URI,
you must separate each option with a comma. Valid values are:
snapshots:
Specifies that snapshots should be included in the
enumeration. Snapshots are listed from oldest to newest in
the response.
metadata:
Specifies that blob metadata be returned in the response.
uncommittedblobs:
Specifies that blobs for which blocks have been uploaded,
but which have not been committed using Put Block List
(REST API), be included in the response.
copy:
Version 2012-02-12 and newer. Specifies that metadata
related to any current or previous Copy Blob operation
should be included in the response.
delimiter:
Optional. When the request includes this parameter, the operation
returns a BlobPrefix element in the response body that acts as a
placeholder for all blobs whose names begin with the same
substring up to the appearance of the delimiter character. The
delimiter may be a single character or a string.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_blobs function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('An storage container name must be specified as "container"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.list_blobs(storage_conn=storage_conn, **kwargs)
def show_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Show a blob's service properties
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_service_properties my-azure
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_service_properties function must be called with -f or --function.'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
timeout=kwargs.get('timeout', None),
)
return data
# For consistency with Azure SDK
get_blob_service_properties = show_blob_service_properties
def set_blob_service_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Sets the properties of a storage account's Blob service, including
Windows Azure Storage Analytics. You can also use this operation to
set the default request version for all incoming requests that do not
have a version specified.
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_service_properties my-azure
properties:
a StorageServiceProperties object.
timeout:
Optional. The timeout parameter is expressed in seconds.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_service_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'properties' not in kwargs:
raise SaltCloudSystemExit('The blob service properties name must be specified as "properties"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_service_properties(
storage_service_properties=kwargs['properties'],
timeout=kwargs.get('timeout', None),
)
return data
def show_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Returns all user-defined metadata, standard HTTP properties, and
system properties for the blob.
CLI Example:
.. code-block:: bash
salt-cloud -f show_blob_properties my-azure container=mycontainer blob=myblob
container:
Name of existing container.
blob:
Name of existing blob.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The show_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
try:
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_lease_id=kwargs.get('lease_id', None),
)
except AzureMissingResourceHttpError:
raise SaltCloudSystemExit('The specified blob does not exist.')
return data
# For consistency with Azure SDK
get_blob_properties = show_blob_properties
def set_blob_properties(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a blob's properties
CLI Example:
.. code-block:: bash
salt-cloud -f set_blob_properties my-azure
container:
Name of existing container.
blob:
Name of existing blob.
blob_cache_control:
Optional. Modifies the cache control string for the blob.
blob_content_type:
Optional. Sets the blob's content type.
blob_content_md5:
Optional. Sets the blob's MD5 hash.
blob_content_encoding:
Optional. Sets the blob's content encoding.
blob_content_language:
Optional. Sets the blob's content language.
lease_id:
Required if the blob has an active lease.
blob_content_disposition:
Optional. Sets the blob's Content-Disposition header.
The Content-Disposition response header field conveys additional
information about how to process the response payload, and also can
be used to attach additional metadata. For example, if set to
attachment, it indicates that the user-agent should not display the
response, but instead show a Save As dialog with a filename other
than the blob name specified.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The set_blob_properties function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'blob' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "blob"')
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
data = storage_conn.get_blob_properties(
container_name=kwargs['container'],
blob_name=kwargs['blob'],
x_ms_blob_cache_control=kwargs.get('blob_cache_control', None),
x_ms_blob_content_type=kwargs.get('blob_content_type', None),
x_ms_blob_content_md5=kwargs.get('blob_content_md5', None),
x_ms_blob_content_encoding=kwargs.get('blob_content_encoding', None),
x_ms_blob_content_language=kwargs.get('blob_content_language', None),
x_ms_lease_id=kwargs.get('lease_id', None),
x_ms_blob_content_disposition=kwargs.get('blob_content_disposition', None),
)
return data
def put_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Upload a blob
CLI Examples:
.. code-block:: bash
salt-cloud -f put_blob my-azure container=base name=top.sls blob_path=/srv/salt/top.sls
salt-cloud -f put_blob my-azure container=base name=content.txt blob_content='Some content'
container:
Name of existing container.
name:
Name of existing blob.
blob_path:
The path on the local machine of the file to upload as a blob. Either
this or blob_content must be specified.
blob_content:
The actual content to be uploaded as a blob. Either this or blob_path
must me specified.
cache_control:
Optional. The Blob service stores this value but does not use or
modify it.
content_language:
Optional. Specifies the natural languages used by this resource.
content_md5:
Optional. An MD5 hash of the blob content. This hash is used to
verify the integrity of the blob during transport. When this header
is specified, the storage service checks the hash that has arrived
with the one that was sent. If the two hashes do not match, the
operation will fail with error code 400 (Bad Request).
blob_content_type:
Optional. Set the blob's content type.
blob_content_encoding:
Optional. Set the blob's content encoding.
blob_content_language:
Optional. Set the blob's content language.
blob_content_md5:
Optional. Set the blob's MD5 hash.
blob_cache_control:
Optional. Sets the blob's cache control.
meta_name_values:
A dict containing name, value for metadata.
lease_id:
Required if the blob has an active lease.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The put_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'blob_path' not in kwargs and 'blob_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a path to a file needs to be passed in as "blob_path" or '
'the contents of a blob as "blob_content."'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.put_blob(storage_conn=storage_conn, **kwargs)
def get_blob(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Download a blob
CLI Example:
.. code-block:: bash
salt-cloud -f get_blob my-azure container=base name=top.sls local_path=/srv/salt/top.sls
salt-cloud -f get_blob my-azure container=base name=content.txt return_content=True
container:
Name of existing container.
name:
Name of existing blob.
local_path:
The path on the local machine to download the blob to. Either this or
return_content must be specified.
return_content:
Whether or not to return the content directly from the blob. If
specified, must be True or False. Either this or the local_path must
be specified.
snapshot:
Optional. The snapshot parameter is an opaque DateTime value that,
when present, specifies the blob snapshot to retrieve.
lease_id:
Required if the blob has an active lease.
progress_callback:
callback for progress with signature function(current, total) where
current is the number of bytes transferred so far, and total is the
size of the blob.
max_connections:
Maximum number of parallel connections to use when the blob size
exceeds 64MB.
Set to 1 to download the blob chunks sequentially.
Set to 2 or more to download the blob chunks in parallel. This uses
more system resources but will download faster.
max_retries:
Number of times to retry download of blob chunk if an error occurs.
retry_wait:
Sleep time in secs between retries.
'''
if call != 'function':
raise SaltCloudSystemExit(
'The get_blob function must be called with -f or --function.'
)
if kwargs is None:
kwargs = {}
if 'container' not in kwargs:
raise SaltCloudSystemExit('The blob container name must be specified as "container"')
if 'name' not in kwargs:
raise SaltCloudSystemExit('The blob name must be specified as "name"')
if 'local_path' not in kwargs and 'return_content' not in kwargs:
raise SaltCloudSystemExit(
'Either a local path needs to be passed in as "local_path" or '
'"return_content" to return the blob contents directly'
)
if not storage_conn:
storage_conn = get_storage_conn(conn_kwargs=kwargs)
return salt.utils.msazure.get_blob(storage_conn=storage_conn, **kwargs)
|
saltstack/salt
|
salt/modules/daemontools.py
|
start
|
python
|
def start(name):
'''
Starts service via daemontools
CLI Example:
.. code-block:: bash
salt '*' daemontools.start <service name>
'''
__salt__['file.remove']('{0}/down'.format(_service_path(name)))
cmd = 'svc -u {0}'.format(_service_path(name))
return not __salt__['cmd.retcode'](cmd, python_shell=False)
|
Starts service via daemontools
CLI Example:
.. code-block:: bash
salt '*' daemontools.start <service name>
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/daemontools.py#L66-L78
|
[
"def _service_path(name):\n '''\n build service path\n '''\n if not SERVICE_DIR:\n raise CommandExecutionError(\"Could not find service directory.\")\n return '{0}/{1}'.format(SERVICE_DIR, name)\n"
] |
# -*- coding: utf-8 -*-
'''
daemontools service module. This module will create daemontools type
service watcher.
This module is compatible with the :mod:`service <salt.states.service>` states,
so it can be used to maintain services using the ``provider`` argument:
.. code-block:: yaml
myservice:
service.running:
- provider: daemontools
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import os
import os.path
import re
# Import salt libs
import salt.utils.path
from salt.exceptions import CommandExecutionError
# Function alias to not shadow built-ins.
__func_alias__ = {
'reload_': 'reload'
}
log = logging.getLogger(__name__)
__virtualname__ = 'daemontools'
VALID_SERVICE_DIRS = [
'/service',
'/var/service',
'/etc/service',
]
SERVICE_DIR = None
for service_dir in VALID_SERVICE_DIRS:
if os.path.exists(service_dir):
SERVICE_DIR = service_dir
break
def __virtual__():
# Ensure that daemontools is installed properly.
BINS = frozenset(('svc', 'supervise', 'svok'))
if all(salt.utils.path.which(b) for b in BINS) and SERVICE_DIR:
return __virtualname__
return False
def _service_path(name):
'''
build service path
'''
if not SERVICE_DIR:
raise CommandExecutionError("Could not find service directory.")
return '{0}/{1}'.format(SERVICE_DIR, name)
#-- states.service compatible args
#-- states.service compatible args
def stop(name):
'''
Stops service via daemontools
CLI Example:
.. code-block:: bash
salt '*' daemontools.stop <service name>
'''
__salt__['file.touch']('{0}/down'.format(_service_path(name)))
cmd = 'svc -d {0}'.format(_service_path(name))
return not __salt__['cmd.retcode'](cmd, python_shell=False)
def term(name):
'''
Send a TERM to service via daemontools
CLI Example:
.. code-block:: bash
salt '*' daemontools.term <service name>
'''
cmd = 'svc -t {0}'.format(_service_path(name))
return not __salt__['cmd.retcode'](cmd, python_shell=False)
#-- states.service compatible
def reload_(name):
'''
Wrapper for term()
CLI Example:
.. code-block:: bash
salt '*' daemontools.reload <service name>
'''
term(name)
#-- states.service compatible
def restart(name):
'''
Restart service via daemontools. This will stop/start service
CLI Example:
.. code-block:: bash
salt '*' daemontools.restart <service name>
'''
ret = 'restart False'
if stop(name) and start(name):
ret = 'restart True'
return ret
#-- states.service compatible
def full_restart(name):
'''
Calls daemontools.restart() function
CLI Example:
.. code-block:: bash
salt '*' daemontools.full_restart <service name>
'''
restart(name)
#-- states.service compatible
def status(name, sig=None):
'''
Return the status for a service via daemontools, return pid if running
CLI Example:
.. code-block:: bash
salt '*' daemontools.status <service name>
'''
cmd = 'svstat {0}'.format(_service_path(name))
out = __salt__['cmd.run_stdout'](cmd, python_shell=False)
try:
pid = re.search(r'\(pid (\d+)\)', out).group(1)
except AttributeError:
pid = ''
return pid
def available(name):
'''
Returns ``True`` if the specified service is available, otherwise returns
``False``.
CLI Example:
.. code-block:: bash
salt '*' daemontools.available foo
'''
return name in get_all()
def missing(name):
'''
The inverse of daemontools.available.
Returns ``True`` if the specified service is not available, otherwise returns
``False``.
CLI Example:
.. code-block:: bash
salt '*' daemontools.missing foo
'''
return name not in get_all()
def get_all():
'''
Return a list of all available services
CLI Example:
.. code-block:: bash
salt '*' daemontools.get_all
'''
if not SERVICE_DIR:
raise CommandExecutionError("Could not find service directory.")
#- List all daemontools services in
return sorted(os.listdir(SERVICE_DIR))
def enabled(name, **kwargs):
'''
Return True if the named service is enabled, false otherwise
A service is considered enabled if in your service directory:
- an executable ./run file exist
- a file named "down" does not exist
.. versionadded:: 2015.5.7
name
Service name
CLI Example:
.. code-block:: bash
salt '*' daemontools.enabled <service name>
'''
if not available(name):
log.error('Service %s not found', name)
return False
run_file = os.path.join(SERVICE_DIR, name, 'run')
down_file = os.path.join(SERVICE_DIR, name, 'down')
return (
os.path.isfile(run_file) and
os.access(run_file, os.X_OK) and not
os.path.isfile(down_file)
)
def disabled(name):
'''
Return True if the named service is enabled, false otherwise
.. versionadded:: 2015.5.6
CLI Example:
.. code-block:: bash
salt '*' daemontools.disabled <service name>
'''
return not enabled(name)
|
saltstack/salt
|
salt/modules/daemontools.py
|
stop
|
python
|
def stop(name):
'''
Stops service via daemontools
CLI Example:
.. code-block:: bash
salt '*' daemontools.stop <service name>
'''
__salt__['file.touch']('{0}/down'.format(_service_path(name)))
cmd = 'svc -d {0}'.format(_service_path(name))
return not __salt__['cmd.retcode'](cmd, python_shell=False)
|
Stops service via daemontools
CLI Example:
.. code-block:: bash
salt '*' daemontools.stop <service name>
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/daemontools.py#L82-L94
|
[
"def _service_path(name):\n '''\n build service path\n '''\n if not SERVICE_DIR:\n raise CommandExecutionError(\"Could not find service directory.\")\n return '{0}/{1}'.format(SERVICE_DIR, name)\n"
] |
# -*- coding: utf-8 -*-
'''
daemontools service module. This module will create daemontools type
service watcher.
This module is compatible with the :mod:`service <salt.states.service>` states,
so it can be used to maintain services using the ``provider`` argument:
.. code-block:: yaml
myservice:
service.running:
- provider: daemontools
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import os
import os.path
import re
# Import salt libs
import salt.utils.path
from salt.exceptions import CommandExecutionError
# Function alias to not shadow built-ins.
__func_alias__ = {
'reload_': 'reload'
}
log = logging.getLogger(__name__)
__virtualname__ = 'daemontools'
VALID_SERVICE_DIRS = [
'/service',
'/var/service',
'/etc/service',
]
SERVICE_DIR = None
for service_dir in VALID_SERVICE_DIRS:
if os.path.exists(service_dir):
SERVICE_DIR = service_dir
break
def __virtual__():
# Ensure that daemontools is installed properly.
BINS = frozenset(('svc', 'supervise', 'svok'))
if all(salt.utils.path.which(b) for b in BINS) and SERVICE_DIR:
return __virtualname__
return False
def _service_path(name):
'''
build service path
'''
if not SERVICE_DIR:
raise CommandExecutionError("Could not find service directory.")
return '{0}/{1}'.format(SERVICE_DIR, name)
#-- states.service compatible args
def start(name):
'''
Starts service via daemontools
CLI Example:
.. code-block:: bash
salt '*' daemontools.start <service name>
'''
__salt__['file.remove']('{0}/down'.format(_service_path(name)))
cmd = 'svc -u {0}'.format(_service_path(name))
return not __salt__['cmd.retcode'](cmd, python_shell=False)
#-- states.service compatible args
def term(name):
'''
Send a TERM to service via daemontools
CLI Example:
.. code-block:: bash
salt '*' daemontools.term <service name>
'''
cmd = 'svc -t {0}'.format(_service_path(name))
return not __salt__['cmd.retcode'](cmd, python_shell=False)
#-- states.service compatible
def reload_(name):
'''
Wrapper for term()
CLI Example:
.. code-block:: bash
salt '*' daemontools.reload <service name>
'''
term(name)
#-- states.service compatible
def restart(name):
'''
Restart service via daemontools. This will stop/start service
CLI Example:
.. code-block:: bash
salt '*' daemontools.restart <service name>
'''
ret = 'restart False'
if stop(name) and start(name):
ret = 'restart True'
return ret
#-- states.service compatible
def full_restart(name):
'''
Calls daemontools.restart() function
CLI Example:
.. code-block:: bash
salt '*' daemontools.full_restart <service name>
'''
restart(name)
#-- states.service compatible
def status(name, sig=None):
'''
Return the status for a service via daemontools, return pid if running
CLI Example:
.. code-block:: bash
salt '*' daemontools.status <service name>
'''
cmd = 'svstat {0}'.format(_service_path(name))
out = __salt__['cmd.run_stdout'](cmd, python_shell=False)
try:
pid = re.search(r'\(pid (\d+)\)', out).group(1)
except AttributeError:
pid = ''
return pid
def available(name):
'''
Returns ``True`` if the specified service is available, otherwise returns
``False``.
CLI Example:
.. code-block:: bash
salt '*' daemontools.available foo
'''
return name in get_all()
def missing(name):
'''
The inverse of daemontools.available.
Returns ``True`` if the specified service is not available, otherwise returns
``False``.
CLI Example:
.. code-block:: bash
salt '*' daemontools.missing foo
'''
return name not in get_all()
def get_all():
'''
Return a list of all available services
CLI Example:
.. code-block:: bash
salt '*' daemontools.get_all
'''
if not SERVICE_DIR:
raise CommandExecutionError("Could not find service directory.")
#- List all daemontools services in
return sorted(os.listdir(SERVICE_DIR))
def enabled(name, **kwargs):
'''
Return True if the named service is enabled, false otherwise
A service is considered enabled if in your service directory:
- an executable ./run file exist
- a file named "down" does not exist
.. versionadded:: 2015.5.7
name
Service name
CLI Example:
.. code-block:: bash
salt '*' daemontools.enabled <service name>
'''
if not available(name):
log.error('Service %s not found', name)
return False
run_file = os.path.join(SERVICE_DIR, name, 'run')
down_file = os.path.join(SERVICE_DIR, name, 'down')
return (
os.path.isfile(run_file) and
os.access(run_file, os.X_OK) and not
os.path.isfile(down_file)
)
def disabled(name):
'''
Return True if the named service is enabled, false otherwise
.. versionadded:: 2015.5.6
CLI Example:
.. code-block:: bash
salt '*' daemontools.disabled <service name>
'''
return not enabled(name)
|
saltstack/salt
|
salt/modules/daemontools.py
|
term
|
python
|
def term(name):
'''
Send a TERM to service via daemontools
CLI Example:
.. code-block:: bash
salt '*' daemontools.term <service name>
'''
cmd = 'svc -t {0}'.format(_service_path(name))
return not __salt__['cmd.retcode'](cmd, python_shell=False)
|
Send a TERM to service via daemontools
CLI Example:
.. code-block:: bash
salt '*' daemontools.term <service name>
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/daemontools.py#L97-L108
|
[
"def _service_path(name):\n '''\n build service path\n '''\n if not SERVICE_DIR:\n raise CommandExecutionError(\"Could not find service directory.\")\n return '{0}/{1}'.format(SERVICE_DIR, name)\n"
] |
# -*- coding: utf-8 -*-
'''
daemontools service module. This module will create daemontools type
service watcher.
This module is compatible with the :mod:`service <salt.states.service>` states,
so it can be used to maintain services using the ``provider`` argument:
.. code-block:: yaml
myservice:
service.running:
- provider: daemontools
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import os
import os.path
import re
# Import salt libs
import salt.utils.path
from salt.exceptions import CommandExecutionError
# Function alias to not shadow built-ins.
__func_alias__ = {
'reload_': 'reload'
}
log = logging.getLogger(__name__)
__virtualname__ = 'daemontools'
VALID_SERVICE_DIRS = [
'/service',
'/var/service',
'/etc/service',
]
SERVICE_DIR = None
for service_dir in VALID_SERVICE_DIRS:
if os.path.exists(service_dir):
SERVICE_DIR = service_dir
break
def __virtual__():
# Ensure that daemontools is installed properly.
BINS = frozenset(('svc', 'supervise', 'svok'))
if all(salt.utils.path.which(b) for b in BINS) and SERVICE_DIR:
return __virtualname__
return False
def _service_path(name):
'''
build service path
'''
if not SERVICE_DIR:
raise CommandExecutionError("Could not find service directory.")
return '{0}/{1}'.format(SERVICE_DIR, name)
#-- states.service compatible args
def start(name):
'''
Starts service via daemontools
CLI Example:
.. code-block:: bash
salt '*' daemontools.start <service name>
'''
__salt__['file.remove']('{0}/down'.format(_service_path(name)))
cmd = 'svc -u {0}'.format(_service_path(name))
return not __salt__['cmd.retcode'](cmd, python_shell=False)
#-- states.service compatible args
def stop(name):
'''
Stops service via daemontools
CLI Example:
.. code-block:: bash
salt '*' daemontools.stop <service name>
'''
__salt__['file.touch']('{0}/down'.format(_service_path(name)))
cmd = 'svc -d {0}'.format(_service_path(name))
return not __salt__['cmd.retcode'](cmd, python_shell=False)
#-- states.service compatible
def reload_(name):
'''
Wrapper for term()
CLI Example:
.. code-block:: bash
salt '*' daemontools.reload <service name>
'''
term(name)
#-- states.service compatible
def restart(name):
'''
Restart service via daemontools. This will stop/start service
CLI Example:
.. code-block:: bash
salt '*' daemontools.restart <service name>
'''
ret = 'restart False'
if stop(name) and start(name):
ret = 'restart True'
return ret
#-- states.service compatible
def full_restart(name):
'''
Calls daemontools.restart() function
CLI Example:
.. code-block:: bash
salt '*' daemontools.full_restart <service name>
'''
restart(name)
#-- states.service compatible
def status(name, sig=None):
'''
Return the status for a service via daemontools, return pid if running
CLI Example:
.. code-block:: bash
salt '*' daemontools.status <service name>
'''
cmd = 'svstat {0}'.format(_service_path(name))
out = __salt__['cmd.run_stdout'](cmd, python_shell=False)
try:
pid = re.search(r'\(pid (\d+)\)', out).group(1)
except AttributeError:
pid = ''
return pid
def available(name):
'''
Returns ``True`` if the specified service is available, otherwise returns
``False``.
CLI Example:
.. code-block:: bash
salt '*' daemontools.available foo
'''
return name in get_all()
def missing(name):
'''
The inverse of daemontools.available.
Returns ``True`` if the specified service is not available, otherwise returns
``False``.
CLI Example:
.. code-block:: bash
salt '*' daemontools.missing foo
'''
return name not in get_all()
def get_all():
'''
Return a list of all available services
CLI Example:
.. code-block:: bash
salt '*' daemontools.get_all
'''
if not SERVICE_DIR:
raise CommandExecutionError("Could not find service directory.")
#- List all daemontools services in
return sorted(os.listdir(SERVICE_DIR))
def enabled(name, **kwargs):
'''
Return True if the named service is enabled, false otherwise
A service is considered enabled if in your service directory:
- an executable ./run file exist
- a file named "down" does not exist
.. versionadded:: 2015.5.7
name
Service name
CLI Example:
.. code-block:: bash
salt '*' daemontools.enabled <service name>
'''
if not available(name):
log.error('Service %s not found', name)
return False
run_file = os.path.join(SERVICE_DIR, name, 'run')
down_file = os.path.join(SERVICE_DIR, name, 'down')
return (
os.path.isfile(run_file) and
os.access(run_file, os.X_OK) and not
os.path.isfile(down_file)
)
def disabled(name):
'''
Return True if the named service is enabled, false otherwise
.. versionadded:: 2015.5.6
CLI Example:
.. code-block:: bash
salt '*' daemontools.disabled <service name>
'''
return not enabled(name)
|
saltstack/salt
|
salt/modules/daemontools.py
|
status
|
python
|
def status(name, sig=None):
'''
Return the status for a service via daemontools, return pid if running
CLI Example:
.. code-block:: bash
salt '*' daemontools.status <service name>
'''
cmd = 'svstat {0}'.format(_service_path(name))
out = __salt__['cmd.run_stdout'](cmd, python_shell=False)
try:
pid = re.search(r'\(pid (\d+)\)', out).group(1)
except AttributeError:
pid = ''
return pid
|
Return the status for a service via daemontools, return pid if running
CLI Example:
.. code-block:: bash
salt '*' daemontools.status <service name>
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/daemontools.py#L157-L173
|
[
"def _service_path(name):\n '''\n build service path\n '''\n if not SERVICE_DIR:\n raise CommandExecutionError(\"Could not find service directory.\")\n return '{0}/{1}'.format(SERVICE_DIR, name)\n"
] |
# -*- coding: utf-8 -*-
'''
daemontools service module. This module will create daemontools type
service watcher.
This module is compatible with the :mod:`service <salt.states.service>` states,
so it can be used to maintain services using the ``provider`` argument:
.. code-block:: yaml
myservice:
service.running:
- provider: daemontools
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import os
import os.path
import re
# Import salt libs
import salt.utils.path
from salt.exceptions import CommandExecutionError
# Function alias to not shadow built-ins.
__func_alias__ = {
'reload_': 'reload'
}
log = logging.getLogger(__name__)
__virtualname__ = 'daemontools'
VALID_SERVICE_DIRS = [
'/service',
'/var/service',
'/etc/service',
]
SERVICE_DIR = None
for service_dir in VALID_SERVICE_DIRS:
if os.path.exists(service_dir):
SERVICE_DIR = service_dir
break
def __virtual__():
# Ensure that daemontools is installed properly.
BINS = frozenset(('svc', 'supervise', 'svok'))
if all(salt.utils.path.which(b) for b in BINS) and SERVICE_DIR:
return __virtualname__
return False
def _service_path(name):
'''
build service path
'''
if not SERVICE_DIR:
raise CommandExecutionError("Could not find service directory.")
return '{0}/{1}'.format(SERVICE_DIR, name)
#-- states.service compatible args
def start(name):
'''
Starts service via daemontools
CLI Example:
.. code-block:: bash
salt '*' daemontools.start <service name>
'''
__salt__['file.remove']('{0}/down'.format(_service_path(name)))
cmd = 'svc -u {0}'.format(_service_path(name))
return not __salt__['cmd.retcode'](cmd, python_shell=False)
#-- states.service compatible args
def stop(name):
'''
Stops service via daemontools
CLI Example:
.. code-block:: bash
salt '*' daemontools.stop <service name>
'''
__salt__['file.touch']('{0}/down'.format(_service_path(name)))
cmd = 'svc -d {0}'.format(_service_path(name))
return not __salt__['cmd.retcode'](cmd, python_shell=False)
def term(name):
'''
Send a TERM to service via daemontools
CLI Example:
.. code-block:: bash
salt '*' daemontools.term <service name>
'''
cmd = 'svc -t {0}'.format(_service_path(name))
return not __salt__['cmd.retcode'](cmd, python_shell=False)
#-- states.service compatible
def reload_(name):
'''
Wrapper for term()
CLI Example:
.. code-block:: bash
salt '*' daemontools.reload <service name>
'''
term(name)
#-- states.service compatible
def restart(name):
'''
Restart service via daemontools. This will stop/start service
CLI Example:
.. code-block:: bash
salt '*' daemontools.restart <service name>
'''
ret = 'restart False'
if stop(name) and start(name):
ret = 'restart True'
return ret
#-- states.service compatible
def full_restart(name):
'''
Calls daemontools.restart() function
CLI Example:
.. code-block:: bash
salt '*' daemontools.full_restart <service name>
'''
restart(name)
#-- states.service compatible
def available(name):
'''
Returns ``True`` if the specified service is available, otherwise returns
``False``.
CLI Example:
.. code-block:: bash
salt '*' daemontools.available foo
'''
return name in get_all()
def missing(name):
'''
The inverse of daemontools.available.
Returns ``True`` if the specified service is not available, otherwise returns
``False``.
CLI Example:
.. code-block:: bash
salt '*' daemontools.missing foo
'''
return name not in get_all()
def get_all():
'''
Return a list of all available services
CLI Example:
.. code-block:: bash
salt '*' daemontools.get_all
'''
if not SERVICE_DIR:
raise CommandExecutionError("Could not find service directory.")
#- List all daemontools services in
return sorted(os.listdir(SERVICE_DIR))
def enabled(name, **kwargs):
'''
Return True if the named service is enabled, false otherwise
A service is considered enabled if in your service directory:
- an executable ./run file exist
- a file named "down" does not exist
.. versionadded:: 2015.5.7
name
Service name
CLI Example:
.. code-block:: bash
salt '*' daemontools.enabled <service name>
'''
if not available(name):
log.error('Service %s not found', name)
return False
run_file = os.path.join(SERVICE_DIR, name, 'run')
down_file = os.path.join(SERVICE_DIR, name, 'down')
return (
os.path.isfile(run_file) and
os.access(run_file, os.X_OK) and not
os.path.isfile(down_file)
)
def disabled(name):
'''
Return True if the named service is enabled, false otherwise
.. versionadded:: 2015.5.6
CLI Example:
.. code-block:: bash
salt '*' daemontools.disabled <service name>
'''
return not enabled(name)
|
saltstack/salt
|
salt/modules/daemontools.py
|
enabled
|
python
|
def enabled(name, **kwargs):
'''
Return True if the named service is enabled, false otherwise
A service is considered enabled if in your service directory:
- an executable ./run file exist
- a file named "down" does not exist
.. versionadded:: 2015.5.7
name
Service name
CLI Example:
.. code-block:: bash
salt '*' daemontools.enabled <service name>
'''
if not available(name):
log.error('Service %s not found', name)
return False
run_file = os.path.join(SERVICE_DIR, name, 'run')
down_file = os.path.join(SERVICE_DIR, name, 'down')
return (
os.path.isfile(run_file) and
os.access(run_file, os.X_OK) and not
os.path.isfile(down_file)
)
|
Return True if the named service is enabled, false otherwise
A service is considered enabled if in your service directory:
- an executable ./run file exist
- a file named "down" does not exist
.. versionadded:: 2015.5.7
name
Service name
CLI Example:
.. code-block:: bash
salt '*' daemontools.enabled <service name>
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/daemontools.py#L221-L250
|
[
"def available(name):\n '''\n Returns ``True`` if the specified service is available, otherwise returns\n ``False``.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' daemontools.available foo\n '''\n return name in get_all()\n"
] |
# -*- coding: utf-8 -*-
'''
daemontools service module. This module will create daemontools type
service watcher.
This module is compatible with the :mod:`service <salt.states.service>` states,
so it can be used to maintain services using the ``provider`` argument:
.. code-block:: yaml
myservice:
service.running:
- provider: daemontools
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
import os
import os.path
import re
# Import salt libs
import salt.utils.path
from salt.exceptions import CommandExecutionError
# Function alias to not shadow built-ins.
__func_alias__ = {
'reload_': 'reload'
}
log = logging.getLogger(__name__)
__virtualname__ = 'daemontools'
VALID_SERVICE_DIRS = [
'/service',
'/var/service',
'/etc/service',
]
SERVICE_DIR = None
for service_dir in VALID_SERVICE_DIRS:
if os.path.exists(service_dir):
SERVICE_DIR = service_dir
break
def __virtual__():
# Ensure that daemontools is installed properly.
BINS = frozenset(('svc', 'supervise', 'svok'))
if all(salt.utils.path.which(b) for b in BINS) and SERVICE_DIR:
return __virtualname__
return False
def _service_path(name):
'''
build service path
'''
if not SERVICE_DIR:
raise CommandExecutionError("Could not find service directory.")
return '{0}/{1}'.format(SERVICE_DIR, name)
#-- states.service compatible args
def start(name):
'''
Starts service via daemontools
CLI Example:
.. code-block:: bash
salt '*' daemontools.start <service name>
'''
__salt__['file.remove']('{0}/down'.format(_service_path(name)))
cmd = 'svc -u {0}'.format(_service_path(name))
return not __salt__['cmd.retcode'](cmd, python_shell=False)
#-- states.service compatible args
def stop(name):
'''
Stops service via daemontools
CLI Example:
.. code-block:: bash
salt '*' daemontools.stop <service name>
'''
__salt__['file.touch']('{0}/down'.format(_service_path(name)))
cmd = 'svc -d {0}'.format(_service_path(name))
return not __salt__['cmd.retcode'](cmd, python_shell=False)
def term(name):
'''
Send a TERM to service via daemontools
CLI Example:
.. code-block:: bash
salt '*' daemontools.term <service name>
'''
cmd = 'svc -t {0}'.format(_service_path(name))
return not __salt__['cmd.retcode'](cmd, python_shell=False)
#-- states.service compatible
def reload_(name):
'''
Wrapper for term()
CLI Example:
.. code-block:: bash
salt '*' daemontools.reload <service name>
'''
term(name)
#-- states.service compatible
def restart(name):
'''
Restart service via daemontools. This will stop/start service
CLI Example:
.. code-block:: bash
salt '*' daemontools.restart <service name>
'''
ret = 'restart False'
if stop(name) and start(name):
ret = 'restart True'
return ret
#-- states.service compatible
def full_restart(name):
'''
Calls daemontools.restart() function
CLI Example:
.. code-block:: bash
salt '*' daemontools.full_restart <service name>
'''
restart(name)
#-- states.service compatible
def status(name, sig=None):
'''
Return the status for a service via daemontools, return pid if running
CLI Example:
.. code-block:: bash
salt '*' daemontools.status <service name>
'''
cmd = 'svstat {0}'.format(_service_path(name))
out = __salt__['cmd.run_stdout'](cmd, python_shell=False)
try:
pid = re.search(r'\(pid (\d+)\)', out).group(1)
except AttributeError:
pid = ''
return pid
def available(name):
'''
Returns ``True`` if the specified service is available, otherwise returns
``False``.
CLI Example:
.. code-block:: bash
salt '*' daemontools.available foo
'''
return name in get_all()
def missing(name):
'''
The inverse of daemontools.available.
Returns ``True`` if the specified service is not available, otherwise returns
``False``.
CLI Example:
.. code-block:: bash
salt '*' daemontools.missing foo
'''
return name not in get_all()
def get_all():
'''
Return a list of all available services
CLI Example:
.. code-block:: bash
salt '*' daemontools.get_all
'''
if not SERVICE_DIR:
raise CommandExecutionError("Could not find service directory.")
#- List all daemontools services in
return sorted(os.listdir(SERVICE_DIR))
def disabled(name):
'''
Return True if the named service is enabled, false otherwise
.. versionadded:: 2015.5.6
CLI Example:
.. code-block:: bash
salt '*' daemontools.disabled <service name>
'''
return not enabled(name)
|
saltstack/salt
|
salt/modules/reg.py
|
key_exists
|
python
|
def key_exists(hive, key, use_32bit_registry=False):
r'''
Check that the key is found in the registry. This refers to keys and not
value/data pairs.
Args:
hive (str): The hive to connect to
key (str): The key to check
use_32bit_registry (bool): Look in the 32bit portion of the registry
Returns:
bool: True if exists, otherwise False
CLI Example:
.. code-block:: bash
salt '*' reg.key_exists HKLM SOFTWARE\Microsoft
'''
return __utils__['reg.key_exists'](hive=hive,
key=key,
use_32bit_registry=use_32bit_registry)
|
r'''
Check that the key is found in the registry. This refers to keys and not
value/data pairs.
Args:
hive (str): The hive to connect to
key (str): The key to check
use_32bit_registry (bool): Look in the 32bit portion of the registry
Returns:
bool: True if exists, otherwise False
CLI Example:
.. code-block:: bash
salt '*' reg.key_exists HKLM SOFTWARE\Microsoft
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/reg.py#L99-L123
| null |
# -*- coding: utf-8 -*-
r'''
Manage the Windows registry
Hives
-----
Hives are the main sections of the registry and all begin with the word HKEY.
- HKEY_LOCAL_MACHINE
- HKEY_CURRENT_USER
- HKEY_USER
Keys
----
Keys are the folders in the registry. Keys can have many nested subkeys. Keys
can have a value assigned to them under the (Default)
When passing a key on the CLI it must be quoted correctly depending on the
backslashes being used (``\`` vs ``\\``). The following are valid methods of
passing the the key on the CLI:
Using single backslashes:
``"SOFTWARE\Python"``
``'SOFTWARE\Python'`` (will not work on a Windows Master)
Using double backslashes:
``SOFTWARE\\Python``
-----------------
Values or Entries
-----------------
Values or Entries are the name/data pairs beneath the keys and subkeys. All keys
have a default name/data pair. The name is ``(Default)`` with a displayed value
of ``(value not set)``. The actual value is Null.
Example
-------
The following example is an export from the Windows startup portion of the
registry:
.. code-block:: bash
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run]
"RTHDVCPL"="\"C:\\Program Files\\Realtek\\Audio\\HDA\\RtkNGUI64.exe\" -s"
"NvBackend"="\"C:\\Program Files (x86)\\NVIDIA Corporation\\Update Core\\NvBackend.exe\""
"BTMTrayAgent"="rundll32.exe \"C:\\Program Files (x86)\\Intel\\Bluetooth\\btmshellex.dll\",TrayApp"
In this example these are the values for each:
Hive:
``HKEY_LOCAL_MACHINE``
Key and subkeys:
``SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run``
Value:
- There are 3 value names:
- `RTHDVCPL`
- `NvBackend`
- `BTMTrayAgent`
- Each value name has a corresponding value
:depends: - salt.utils.win_reg
'''
# When production windows installer is using Python 3, Python 2 code can be removed
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
# Import Salt libs
import salt.utils.platform
from salt.exceptions import CommandExecutionError
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'reg'
def __virtual__():
'''
Only works on Windows systems with PyWin32
'''
if not salt.utils.platform.is_windows():
return (False, 'reg execution module failed to load: '
'The module will only run on Windows systems')
if 'reg.read_value' not in __utils__:
return (False, 'reg execution module failed to load: '
'The reg salt util is unavailable')
return __virtualname__
def broadcast_change():
'''
Refresh the windows environment.
.. note::
This will only effect new processes and windows. Services will not see
the change until the system restarts.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' reg.broadcast_change
'''
return salt.utils.win_functions.broadcast_setting_change('Environment')
def list_keys(hive, key=None, use_32bit_registry=False):
'''
Enumerates the subkeys in a registry key or hive.
Args:
hive (str):
The name of the hive. Can be one of the following:
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name. If a key is not
passed, the keys under the hive will be returned.
use_32bit_registry (bool):
Accesses the 32bit portion of the registry on 64 bit installations.
On 32bit machines this is ignored.
Returns:
list: A list of keys/subkeys under the hive or key.
CLI Example:
.. code-block:: bash
salt '*' reg.list_keys HKLM 'SOFTWARE'
'''
return __utils__['reg.list_keys'](hive=hive,
key=key,
use_32bit_registry=use_32bit_registry)
def list_values(hive, key=None, use_32bit_registry=False, include_default=True):
r'''
Enumerates the values in a registry key or hive.
Args:
hive (str):
The name of the hive. Can be one of the following:
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name. If a key is not
passed, the values under the hive will be returned.
use_32bit_registry (bool):
Accesses the 32bit portion of the registry on 64 bit installations.
On 32bit machines this is ignored.
include_default (bool):
Toggle whether to include the '(Default)' value.
Returns:
list: A list of values under the hive or key.
CLI Example:
.. code-block:: bash
salt '*' reg.list_values HKLM 'SYSTEM\\CurrentControlSet\\Services\\Tcpip'
'''
return __utils__['reg.list_values'](hive=hive,
key=key,
use_32bit_registry=use_32bit_registry,
include_default=include_default)
def read_value(hive, key, vname=None, use_32bit_registry=False):
r'''
Reads a registry value entry or the default value for a key. To read the
default value, don't pass ``vname``
Args:
hive (str): The name of the hive. Can be one of the following:
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name.
vname (str):
The value name. These are the individual name/data pairs under the
key. If not passed, the key (Default) value will be returned.
use_32bit_registry (bool):
Accesses the 32bit portion of the registry on 64bit installations.
On 32bit machines this is ignored.
Returns:
dict: A dictionary containing the passed settings as well as the
value_data if successful. If unsuccessful, sets success to False.
bool: Returns False if the key is not found
If vname is not passed:
- Returns the first unnamed value (Default) as a string.
- Returns none if first unnamed value is empty.
CLI Example:
The following will get the value of the ``version`` value name in the
``HKEY_LOCAL_MACHINE\\SOFTWARE\\Salt`` key
.. code-block:: bash
salt '*' reg.read_value HKEY_LOCAL_MACHINE 'SOFTWARE\Salt' 'version'
CLI Example:
The following will get the default value of the
``HKEY_LOCAL_MACHINE\\SOFTWARE\\Salt`` key
.. code-block:: bash
salt '*' reg.read_value HKEY_LOCAL_MACHINE 'SOFTWARE\Salt'
'''
return __utils__['reg.read_value'](hive=hive,
key=key,
vname=vname,
use_32bit_registry=use_32bit_registry)
def set_value(hive,
key,
vname=None,
vdata=None,
vtype='REG_SZ',
use_32bit_registry=False,
volatile=False):
'''
Sets a value in the registry. If ``vname`` is passed, it will be the value
for that value name, otherwise it will be the default value for the
specified key
Args:
hive (str):
The name of the hive. Can be one of the following
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name.
vname (str):
The value name. These are the individual name/data pairs under the
key. If not passed, the key (Default) value will be set.
vdata (str, int, list, bytes):
The value you'd like to set. If a value name (vname) is passed, this
will be the data for that value name. If not, this will be the
(Default) value for the key.
The type of data this parameter expects is determined by the value
type specified in ``vtype``. The correspondence is as follows:
- REG_BINARY: Binary data (str in Py2, bytes in Py3)
- REG_DWORD: int
- REG_EXPAND_SZ: str
- REG_MULTI_SZ: list of str
- REG_QWORD: int
- REG_SZ: str
.. note::
When setting REG_BINARY, string data will be converted to
binary.
.. note::
The type for the (Default) value is always REG_SZ and cannot be
changed.
.. note::
This parameter is optional. If ``vdata`` is not passed, the Key
will be created with no associated item/value pairs.
vtype (str):
The value type. The possible values of the vtype parameter are
indicated above in the description of the vdata parameter.
use_32bit_registry (bool):
Sets the 32bit portion of the registry on 64bit installations. On
32bit machines this is ignored.
volatile (bool):
When this parameter has a value of True, the registry key will be
made volatile (i.e. it will not persist beyond a system reset or
shutdown). This parameter only has an effect when a key is being
created and at no other time.
Returns:
bool: True if successful, otherwise False
CLI Example:
This will set the version value to 2015.5.2 in the SOFTWARE\\Salt key in
the HKEY_LOCAL_MACHINE hive
.. code-block:: bash
salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'version' '2015.5.2'
CLI Example:
This function is strict about the type of vdata. For instance this
example will fail because vtype has a value of REG_SZ and vdata has a
type of int (as opposed to str as expected).
.. code-block:: bash
salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'str_data' 1.2
CLI Example:
In this next example vdata is properly quoted and should succeed.
.. code-block:: bash
salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'str_data' vtype=REG_SZ vdata="'1.2'"
CLI Example:
This is an example of using vtype REG_BINARY.
.. code-block:: bash
salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'bin_data' vtype=REG_BINARY vdata='Salty Data'
CLI Example:
An example of using vtype REG_MULTI_SZ is as follows:
.. code-block:: bash
salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'list_data' vtype=REG_MULTI_SZ vdata='["Salt", "is", "great"]'
'''
return __utils__['reg.set_value'](hive=hive,
key=key,
vname=vname,
vdata=vdata,
vtype=vtype,
use_32bit_registry=use_32bit_registry,
volatile=volatile)
def delete_key_recursive(hive, key, use_32bit_registry=False):
r'''
.. versionadded:: 2015.5.4
Delete a registry key to include all subkeys and value/data pairs.
Args:
hive (str):
The name of the hive. Can be one of the following
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key to remove (looks like a path)
use_32bit_registry (bool):
Deletes the 32bit portion of the registry on 64bit
installations. On 32bit machines this is ignored.
Returns:
dict: A dictionary listing the keys that deleted successfully as well as
those that failed to delete.
CLI Example:
The following example will remove ``delete_me`` and all its subkeys from the
``SOFTWARE`` key in ``HKEY_LOCAL_MACHINE``:
.. code-block:: bash
salt '*' reg.delete_key_recursive HKLM SOFTWARE\\delete_me
'''
return __utils__['reg.delete_key_recursive'](hive=hive,
key=key,
use_32bit_registry=use_32bit_registry)
def delete_value(hive, key, vname=None, use_32bit_registry=False):
r'''
Delete a registry value entry or the default value for a key.
Args:
hive (str):
The name of the hive. Can be one of the following
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name.
vname (str):
The value name. These are the individual name/data pairs under the
key. If not passed, the key (Default) value will be deleted.
use_32bit_registry (bool):
Deletes the 32bit portion of the registry on 64bit installations. On
32bit machines this is ignored.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' reg.delete_value HKEY_CURRENT_USER 'SOFTWARE\\Salt' 'version'
'''
return __utils__['reg.delete_value'](hive=hive,
key=key,
vname=vname,
use_32bit_registry=use_32bit_registry)
def import_file(source, use_32bit_registry=False):
'''
Import registry settings from a Windows ``REG`` file by invoking ``REG.EXE``.
.. versionadded:: 2018.3.0
Args:
source (str):
The full path of the ``REG`` file. This can be either a local file
path or a URL type supported by salt (e.g. ``salt://salt_master_path``)
use_32bit_registry (bool):
If the value of this parameter is ``True`` then the ``REG`` file
will be imported into the Windows 32 bit registry. Otherwise the
Windows 64 bit registry will be used.
Returns:
bool: True if successful, otherwise an error is raised
Raises:
ValueError: If the value of ``source`` is an invalid path or otherwise
causes ``cp.cache_file`` to return ``False``
CommandExecutionError: If ``reg.exe`` exits with a non-0 exit code
CLI Example:
.. code-block:: bash
salt machine1 reg.import_file salt://win/printer_config/110_Canon/postinstall_config.reg
'''
cache_path = __salt__['cp.cache_file'](source)
if not cache_path:
error_msg = "File/URL '{0}' probably invalid.".format(source)
raise ValueError(error_msg)
if use_32bit_registry:
word_sz_txt = "32"
else:
word_sz_txt = "64"
cmd = 'reg import "{0}" /reg:{1}'.format(cache_path, word_sz_txt)
cmd_ret_dict = __salt__['cmd.run_all'](cmd, python_shell=True)
retcode = cmd_ret_dict['retcode']
if retcode != 0:
raise CommandExecutionError(
'reg.exe import failed',
info=cmd_ret_dict
)
return True
|
saltstack/salt
|
salt/modules/reg.py
|
list_keys
|
python
|
def list_keys(hive, key=None, use_32bit_registry=False):
'''
Enumerates the subkeys in a registry key or hive.
Args:
hive (str):
The name of the hive. Can be one of the following:
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name. If a key is not
passed, the keys under the hive will be returned.
use_32bit_registry (bool):
Accesses the 32bit portion of the registry on 64 bit installations.
On 32bit machines this is ignored.
Returns:
list: A list of keys/subkeys under the hive or key.
CLI Example:
.. code-block:: bash
salt '*' reg.list_keys HKLM 'SOFTWARE'
'''
return __utils__['reg.list_keys'](hive=hive,
key=key,
use_32bit_registry=use_32bit_registry)
|
Enumerates the subkeys in a registry key or hive.
Args:
hive (str):
The name of the hive. Can be one of the following:
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name. If a key is not
passed, the keys under the hive will be returned.
use_32bit_registry (bool):
Accesses the 32bit portion of the registry on 64 bit installations.
On 32bit machines this is ignored.
Returns:
list: A list of keys/subkeys under the hive or key.
CLI Example:
.. code-block:: bash
salt '*' reg.list_keys HKLM 'SOFTWARE'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/reg.py#L146-L180
| null |
# -*- coding: utf-8 -*-
r'''
Manage the Windows registry
Hives
-----
Hives are the main sections of the registry and all begin with the word HKEY.
- HKEY_LOCAL_MACHINE
- HKEY_CURRENT_USER
- HKEY_USER
Keys
----
Keys are the folders in the registry. Keys can have many nested subkeys. Keys
can have a value assigned to them under the (Default)
When passing a key on the CLI it must be quoted correctly depending on the
backslashes being used (``\`` vs ``\\``). The following are valid methods of
passing the the key on the CLI:
Using single backslashes:
``"SOFTWARE\Python"``
``'SOFTWARE\Python'`` (will not work on a Windows Master)
Using double backslashes:
``SOFTWARE\\Python``
-----------------
Values or Entries
-----------------
Values or Entries are the name/data pairs beneath the keys and subkeys. All keys
have a default name/data pair. The name is ``(Default)`` with a displayed value
of ``(value not set)``. The actual value is Null.
Example
-------
The following example is an export from the Windows startup portion of the
registry:
.. code-block:: bash
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run]
"RTHDVCPL"="\"C:\\Program Files\\Realtek\\Audio\\HDA\\RtkNGUI64.exe\" -s"
"NvBackend"="\"C:\\Program Files (x86)\\NVIDIA Corporation\\Update Core\\NvBackend.exe\""
"BTMTrayAgent"="rundll32.exe \"C:\\Program Files (x86)\\Intel\\Bluetooth\\btmshellex.dll\",TrayApp"
In this example these are the values for each:
Hive:
``HKEY_LOCAL_MACHINE``
Key and subkeys:
``SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run``
Value:
- There are 3 value names:
- `RTHDVCPL`
- `NvBackend`
- `BTMTrayAgent`
- Each value name has a corresponding value
:depends: - salt.utils.win_reg
'''
# When production windows installer is using Python 3, Python 2 code can be removed
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
# Import Salt libs
import salt.utils.platform
from salt.exceptions import CommandExecutionError
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'reg'
def __virtual__():
'''
Only works on Windows systems with PyWin32
'''
if not salt.utils.platform.is_windows():
return (False, 'reg execution module failed to load: '
'The module will only run on Windows systems')
if 'reg.read_value' not in __utils__:
return (False, 'reg execution module failed to load: '
'The reg salt util is unavailable')
return __virtualname__
def key_exists(hive, key, use_32bit_registry=False):
r'''
Check that the key is found in the registry. This refers to keys and not
value/data pairs.
Args:
hive (str): The hive to connect to
key (str): The key to check
use_32bit_registry (bool): Look in the 32bit portion of the registry
Returns:
bool: True if exists, otherwise False
CLI Example:
.. code-block:: bash
salt '*' reg.key_exists HKLM SOFTWARE\Microsoft
'''
return __utils__['reg.key_exists'](hive=hive,
key=key,
use_32bit_registry=use_32bit_registry)
def broadcast_change():
'''
Refresh the windows environment.
.. note::
This will only effect new processes and windows. Services will not see
the change until the system restarts.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' reg.broadcast_change
'''
return salt.utils.win_functions.broadcast_setting_change('Environment')
def list_values(hive, key=None, use_32bit_registry=False, include_default=True):
r'''
Enumerates the values in a registry key or hive.
Args:
hive (str):
The name of the hive. Can be one of the following:
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name. If a key is not
passed, the values under the hive will be returned.
use_32bit_registry (bool):
Accesses the 32bit portion of the registry on 64 bit installations.
On 32bit machines this is ignored.
include_default (bool):
Toggle whether to include the '(Default)' value.
Returns:
list: A list of values under the hive or key.
CLI Example:
.. code-block:: bash
salt '*' reg.list_values HKLM 'SYSTEM\\CurrentControlSet\\Services\\Tcpip'
'''
return __utils__['reg.list_values'](hive=hive,
key=key,
use_32bit_registry=use_32bit_registry,
include_default=include_default)
def read_value(hive, key, vname=None, use_32bit_registry=False):
r'''
Reads a registry value entry or the default value for a key. To read the
default value, don't pass ``vname``
Args:
hive (str): The name of the hive. Can be one of the following:
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name.
vname (str):
The value name. These are the individual name/data pairs under the
key. If not passed, the key (Default) value will be returned.
use_32bit_registry (bool):
Accesses the 32bit portion of the registry on 64bit installations.
On 32bit machines this is ignored.
Returns:
dict: A dictionary containing the passed settings as well as the
value_data if successful. If unsuccessful, sets success to False.
bool: Returns False if the key is not found
If vname is not passed:
- Returns the first unnamed value (Default) as a string.
- Returns none if first unnamed value is empty.
CLI Example:
The following will get the value of the ``version`` value name in the
``HKEY_LOCAL_MACHINE\\SOFTWARE\\Salt`` key
.. code-block:: bash
salt '*' reg.read_value HKEY_LOCAL_MACHINE 'SOFTWARE\Salt' 'version'
CLI Example:
The following will get the default value of the
``HKEY_LOCAL_MACHINE\\SOFTWARE\\Salt`` key
.. code-block:: bash
salt '*' reg.read_value HKEY_LOCAL_MACHINE 'SOFTWARE\Salt'
'''
return __utils__['reg.read_value'](hive=hive,
key=key,
vname=vname,
use_32bit_registry=use_32bit_registry)
def set_value(hive,
key,
vname=None,
vdata=None,
vtype='REG_SZ',
use_32bit_registry=False,
volatile=False):
'''
Sets a value in the registry. If ``vname`` is passed, it will be the value
for that value name, otherwise it will be the default value for the
specified key
Args:
hive (str):
The name of the hive. Can be one of the following
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name.
vname (str):
The value name. These are the individual name/data pairs under the
key. If not passed, the key (Default) value will be set.
vdata (str, int, list, bytes):
The value you'd like to set. If a value name (vname) is passed, this
will be the data for that value name. If not, this will be the
(Default) value for the key.
The type of data this parameter expects is determined by the value
type specified in ``vtype``. The correspondence is as follows:
- REG_BINARY: Binary data (str in Py2, bytes in Py3)
- REG_DWORD: int
- REG_EXPAND_SZ: str
- REG_MULTI_SZ: list of str
- REG_QWORD: int
- REG_SZ: str
.. note::
When setting REG_BINARY, string data will be converted to
binary.
.. note::
The type for the (Default) value is always REG_SZ and cannot be
changed.
.. note::
This parameter is optional. If ``vdata`` is not passed, the Key
will be created with no associated item/value pairs.
vtype (str):
The value type. The possible values of the vtype parameter are
indicated above in the description of the vdata parameter.
use_32bit_registry (bool):
Sets the 32bit portion of the registry on 64bit installations. On
32bit machines this is ignored.
volatile (bool):
When this parameter has a value of True, the registry key will be
made volatile (i.e. it will not persist beyond a system reset or
shutdown). This parameter only has an effect when a key is being
created and at no other time.
Returns:
bool: True if successful, otherwise False
CLI Example:
This will set the version value to 2015.5.2 in the SOFTWARE\\Salt key in
the HKEY_LOCAL_MACHINE hive
.. code-block:: bash
salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'version' '2015.5.2'
CLI Example:
This function is strict about the type of vdata. For instance this
example will fail because vtype has a value of REG_SZ and vdata has a
type of int (as opposed to str as expected).
.. code-block:: bash
salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'str_data' 1.2
CLI Example:
In this next example vdata is properly quoted and should succeed.
.. code-block:: bash
salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'str_data' vtype=REG_SZ vdata="'1.2'"
CLI Example:
This is an example of using vtype REG_BINARY.
.. code-block:: bash
salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'bin_data' vtype=REG_BINARY vdata='Salty Data'
CLI Example:
An example of using vtype REG_MULTI_SZ is as follows:
.. code-block:: bash
salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'list_data' vtype=REG_MULTI_SZ vdata='["Salt", "is", "great"]'
'''
return __utils__['reg.set_value'](hive=hive,
key=key,
vname=vname,
vdata=vdata,
vtype=vtype,
use_32bit_registry=use_32bit_registry,
volatile=volatile)
def delete_key_recursive(hive, key, use_32bit_registry=False):
r'''
.. versionadded:: 2015.5.4
Delete a registry key to include all subkeys and value/data pairs.
Args:
hive (str):
The name of the hive. Can be one of the following
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key to remove (looks like a path)
use_32bit_registry (bool):
Deletes the 32bit portion of the registry on 64bit
installations. On 32bit machines this is ignored.
Returns:
dict: A dictionary listing the keys that deleted successfully as well as
those that failed to delete.
CLI Example:
The following example will remove ``delete_me`` and all its subkeys from the
``SOFTWARE`` key in ``HKEY_LOCAL_MACHINE``:
.. code-block:: bash
salt '*' reg.delete_key_recursive HKLM SOFTWARE\\delete_me
'''
return __utils__['reg.delete_key_recursive'](hive=hive,
key=key,
use_32bit_registry=use_32bit_registry)
def delete_value(hive, key, vname=None, use_32bit_registry=False):
r'''
Delete a registry value entry or the default value for a key.
Args:
hive (str):
The name of the hive. Can be one of the following
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name.
vname (str):
The value name. These are the individual name/data pairs under the
key. If not passed, the key (Default) value will be deleted.
use_32bit_registry (bool):
Deletes the 32bit portion of the registry on 64bit installations. On
32bit machines this is ignored.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' reg.delete_value HKEY_CURRENT_USER 'SOFTWARE\\Salt' 'version'
'''
return __utils__['reg.delete_value'](hive=hive,
key=key,
vname=vname,
use_32bit_registry=use_32bit_registry)
def import_file(source, use_32bit_registry=False):
'''
Import registry settings from a Windows ``REG`` file by invoking ``REG.EXE``.
.. versionadded:: 2018.3.0
Args:
source (str):
The full path of the ``REG`` file. This can be either a local file
path or a URL type supported by salt (e.g. ``salt://salt_master_path``)
use_32bit_registry (bool):
If the value of this parameter is ``True`` then the ``REG`` file
will be imported into the Windows 32 bit registry. Otherwise the
Windows 64 bit registry will be used.
Returns:
bool: True if successful, otherwise an error is raised
Raises:
ValueError: If the value of ``source`` is an invalid path or otherwise
causes ``cp.cache_file`` to return ``False``
CommandExecutionError: If ``reg.exe`` exits with a non-0 exit code
CLI Example:
.. code-block:: bash
salt machine1 reg.import_file salt://win/printer_config/110_Canon/postinstall_config.reg
'''
cache_path = __salt__['cp.cache_file'](source)
if not cache_path:
error_msg = "File/URL '{0}' probably invalid.".format(source)
raise ValueError(error_msg)
if use_32bit_registry:
word_sz_txt = "32"
else:
word_sz_txt = "64"
cmd = 'reg import "{0}" /reg:{1}'.format(cache_path, word_sz_txt)
cmd_ret_dict = __salt__['cmd.run_all'](cmd, python_shell=True)
retcode = cmd_ret_dict['retcode']
if retcode != 0:
raise CommandExecutionError(
'reg.exe import failed',
info=cmd_ret_dict
)
return True
|
saltstack/salt
|
salt/modules/reg.py
|
list_values
|
python
|
def list_values(hive, key=None, use_32bit_registry=False, include_default=True):
r'''
Enumerates the values in a registry key or hive.
Args:
hive (str):
The name of the hive. Can be one of the following:
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name. If a key is not
passed, the values under the hive will be returned.
use_32bit_registry (bool):
Accesses the 32bit portion of the registry on 64 bit installations.
On 32bit machines this is ignored.
include_default (bool):
Toggle whether to include the '(Default)' value.
Returns:
list: A list of values under the hive or key.
CLI Example:
.. code-block:: bash
salt '*' reg.list_values HKLM 'SYSTEM\\CurrentControlSet\\Services\\Tcpip'
'''
return __utils__['reg.list_values'](hive=hive,
key=key,
use_32bit_registry=use_32bit_registry,
include_default=include_default)
|
r'''
Enumerates the values in a registry key or hive.
Args:
hive (str):
The name of the hive. Can be one of the following:
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name. If a key is not
passed, the values under the hive will be returned.
use_32bit_registry (bool):
Accesses the 32bit portion of the registry on 64 bit installations.
On 32bit machines this is ignored.
include_default (bool):
Toggle whether to include the '(Default)' value.
Returns:
list: A list of values under the hive or key.
CLI Example:
.. code-block:: bash
salt '*' reg.list_values HKLM 'SYSTEM\\CurrentControlSet\\Services\\Tcpip'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/reg.py#L183-L221
| null |
# -*- coding: utf-8 -*-
r'''
Manage the Windows registry
Hives
-----
Hives are the main sections of the registry and all begin with the word HKEY.
- HKEY_LOCAL_MACHINE
- HKEY_CURRENT_USER
- HKEY_USER
Keys
----
Keys are the folders in the registry. Keys can have many nested subkeys. Keys
can have a value assigned to them under the (Default)
When passing a key on the CLI it must be quoted correctly depending on the
backslashes being used (``\`` vs ``\\``). The following are valid methods of
passing the the key on the CLI:
Using single backslashes:
``"SOFTWARE\Python"``
``'SOFTWARE\Python'`` (will not work on a Windows Master)
Using double backslashes:
``SOFTWARE\\Python``
-----------------
Values or Entries
-----------------
Values or Entries are the name/data pairs beneath the keys and subkeys. All keys
have a default name/data pair. The name is ``(Default)`` with a displayed value
of ``(value not set)``. The actual value is Null.
Example
-------
The following example is an export from the Windows startup portion of the
registry:
.. code-block:: bash
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run]
"RTHDVCPL"="\"C:\\Program Files\\Realtek\\Audio\\HDA\\RtkNGUI64.exe\" -s"
"NvBackend"="\"C:\\Program Files (x86)\\NVIDIA Corporation\\Update Core\\NvBackend.exe\""
"BTMTrayAgent"="rundll32.exe \"C:\\Program Files (x86)\\Intel\\Bluetooth\\btmshellex.dll\",TrayApp"
In this example these are the values for each:
Hive:
``HKEY_LOCAL_MACHINE``
Key and subkeys:
``SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run``
Value:
- There are 3 value names:
- `RTHDVCPL`
- `NvBackend`
- `BTMTrayAgent`
- Each value name has a corresponding value
:depends: - salt.utils.win_reg
'''
# When production windows installer is using Python 3, Python 2 code can be removed
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
# Import Salt libs
import salt.utils.platform
from salt.exceptions import CommandExecutionError
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'reg'
def __virtual__():
'''
Only works on Windows systems with PyWin32
'''
if not salt.utils.platform.is_windows():
return (False, 'reg execution module failed to load: '
'The module will only run on Windows systems')
if 'reg.read_value' not in __utils__:
return (False, 'reg execution module failed to load: '
'The reg salt util is unavailable')
return __virtualname__
def key_exists(hive, key, use_32bit_registry=False):
r'''
Check that the key is found in the registry. This refers to keys and not
value/data pairs.
Args:
hive (str): The hive to connect to
key (str): The key to check
use_32bit_registry (bool): Look in the 32bit portion of the registry
Returns:
bool: True if exists, otherwise False
CLI Example:
.. code-block:: bash
salt '*' reg.key_exists HKLM SOFTWARE\Microsoft
'''
return __utils__['reg.key_exists'](hive=hive,
key=key,
use_32bit_registry=use_32bit_registry)
def broadcast_change():
'''
Refresh the windows environment.
.. note::
This will only effect new processes and windows. Services will not see
the change until the system restarts.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' reg.broadcast_change
'''
return salt.utils.win_functions.broadcast_setting_change('Environment')
def list_keys(hive, key=None, use_32bit_registry=False):
'''
Enumerates the subkeys in a registry key or hive.
Args:
hive (str):
The name of the hive. Can be one of the following:
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name. If a key is not
passed, the keys under the hive will be returned.
use_32bit_registry (bool):
Accesses the 32bit portion of the registry on 64 bit installations.
On 32bit machines this is ignored.
Returns:
list: A list of keys/subkeys under the hive or key.
CLI Example:
.. code-block:: bash
salt '*' reg.list_keys HKLM 'SOFTWARE'
'''
return __utils__['reg.list_keys'](hive=hive,
key=key,
use_32bit_registry=use_32bit_registry)
def read_value(hive, key, vname=None, use_32bit_registry=False):
r'''
Reads a registry value entry or the default value for a key. To read the
default value, don't pass ``vname``
Args:
hive (str): The name of the hive. Can be one of the following:
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name.
vname (str):
The value name. These are the individual name/data pairs under the
key. If not passed, the key (Default) value will be returned.
use_32bit_registry (bool):
Accesses the 32bit portion of the registry on 64bit installations.
On 32bit machines this is ignored.
Returns:
dict: A dictionary containing the passed settings as well as the
value_data if successful. If unsuccessful, sets success to False.
bool: Returns False if the key is not found
If vname is not passed:
- Returns the first unnamed value (Default) as a string.
- Returns none if first unnamed value is empty.
CLI Example:
The following will get the value of the ``version`` value name in the
``HKEY_LOCAL_MACHINE\\SOFTWARE\\Salt`` key
.. code-block:: bash
salt '*' reg.read_value HKEY_LOCAL_MACHINE 'SOFTWARE\Salt' 'version'
CLI Example:
The following will get the default value of the
``HKEY_LOCAL_MACHINE\\SOFTWARE\\Salt`` key
.. code-block:: bash
salt '*' reg.read_value HKEY_LOCAL_MACHINE 'SOFTWARE\Salt'
'''
return __utils__['reg.read_value'](hive=hive,
key=key,
vname=vname,
use_32bit_registry=use_32bit_registry)
def set_value(hive,
key,
vname=None,
vdata=None,
vtype='REG_SZ',
use_32bit_registry=False,
volatile=False):
'''
Sets a value in the registry. If ``vname`` is passed, it will be the value
for that value name, otherwise it will be the default value for the
specified key
Args:
hive (str):
The name of the hive. Can be one of the following
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name.
vname (str):
The value name. These are the individual name/data pairs under the
key. If not passed, the key (Default) value will be set.
vdata (str, int, list, bytes):
The value you'd like to set. If a value name (vname) is passed, this
will be the data for that value name. If not, this will be the
(Default) value for the key.
The type of data this parameter expects is determined by the value
type specified in ``vtype``. The correspondence is as follows:
- REG_BINARY: Binary data (str in Py2, bytes in Py3)
- REG_DWORD: int
- REG_EXPAND_SZ: str
- REG_MULTI_SZ: list of str
- REG_QWORD: int
- REG_SZ: str
.. note::
When setting REG_BINARY, string data will be converted to
binary.
.. note::
The type for the (Default) value is always REG_SZ and cannot be
changed.
.. note::
This parameter is optional. If ``vdata`` is not passed, the Key
will be created with no associated item/value pairs.
vtype (str):
The value type. The possible values of the vtype parameter are
indicated above in the description of the vdata parameter.
use_32bit_registry (bool):
Sets the 32bit portion of the registry on 64bit installations. On
32bit machines this is ignored.
volatile (bool):
When this parameter has a value of True, the registry key will be
made volatile (i.e. it will not persist beyond a system reset or
shutdown). This parameter only has an effect when a key is being
created and at no other time.
Returns:
bool: True if successful, otherwise False
CLI Example:
This will set the version value to 2015.5.2 in the SOFTWARE\\Salt key in
the HKEY_LOCAL_MACHINE hive
.. code-block:: bash
salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'version' '2015.5.2'
CLI Example:
This function is strict about the type of vdata. For instance this
example will fail because vtype has a value of REG_SZ and vdata has a
type of int (as opposed to str as expected).
.. code-block:: bash
salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'str_data' 1.2
CLI Example:
In this next example vdata is properly quoted and should succeed.
.. code-block:: bash
salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'str_data' vtype=REG_SZ vdata="'1.2'"
CLI Example:
This is an example of using vtype REG_BINARY.
.. code-block:: bash
salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'bin_data' vtype=REG_BINARY vdata='Salty Data'
CLI Example:
An example of using vtype REG_MULTI_SZ is as follows:
.. code-block:: bash
salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'list_data' vtype=REG_MULTI_SZ vdata='["Salt", "is", "great"]'
'''
return __utils__['reg.set_value'](hive=hive,
key=key,
vname=vname,
vdata=vdata,
vtype=vtype,
use_32bit_registry=use_32bit_registry,
volatile=volatile)
def delete_key_recursive(hive, key, use_32bit_registry=False):
r'''
.. versionadded:: 2015.5.4
Delete a registry key to include all subkeys and value/data pairs.
Args:
hive (str):
The name of the hive. Can be one of the following
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key to remove (looks like a path)
use_32bit_registry (bool):
Deletes the 32bit portion of the registry on 64bit
installations. On 32bit machines this is ignored.
Returns:
dict: A dictionary listing the keys that deleted successfully as well as
those that failed to delete.
CLI Example:
The following example will remove ``delete_me`` and all its subkeys from the
``SOFTWARE`` key in ``HKEY_LOCAL_MACHINE``:
.. code-block:: bash
salt '*' reg.delete_key_recursive HKLM SOFTWARE\\delete_me
'''
return __utils__['reg.delete_key_recursive'](hive=hive,
key=key,
use_32bit_registry=use_32bit_registry)
def delete_value(hive, key, vname=None, use_32bit_registry=False):
r'''
Delete a registry value entry or the default value for a key.
Args:
hive (str):
The name of the hive. Can be one of the following
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name.
vname (str):
The value name. These are the individual name/data pairs under the
key. If not passed, the key (Default) value will be deleted.
use_32bit_registry (bool):
Deletes the 32bit portion of the registry on 64bit installations. On
32bit machines this is ignored.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' reg.delete_value HKEY_CURRENT_USER 'SOFTWARE\\Salt' 'version'
'''
return __utils__['reg.delete_value'](hive=hive,
key=key,
vname=vname,
use_32bit_registry=use_32bit_registry)
def import_file(source, use_32bit_registry=False):
'''
Import registry settings from a Windows ``REG`` file by invoking ``REG.EXE``.
.. versionadded:: 2018.3.0
Args:
source (str):
The full path of the ``REG`` file. This can be either a local file
path or a URL type supported by salt (e.g. ``salt://salt_master_path``)
use_32bit_registry (bool):
If the value of this parameter is ``True`` then the ``REG`` file
will be imported into the Windows 32 bit registry. Otherwise the
Windows 64 bit registry will be used.
Returns:
bool: True if successful, otherwise an error is raised
Raises:
ValueError: If the value of ``source`` is an invalid path or otherwise
causes ``cp.cache_file`` to return ``False``
CommandExecutionError: If ``reg.exe`` exits with a non-0 exit code
CLI Example:
.. code-block:: bash
salt machine1 reg.import_file salt://win/printer_config/110_Canon/postinstall_config.reg
'''
cache_path = __salt__['cp.cache_file'](source)
if not cache_path:
error_msg = "File/URL '{0}' probably invalid.".format(source)
raise ValueError(error_msg)
if use_32bit_registry:
word_sz_txt = "32"
else:
word_sz_txt = "64"
cmd = 'reg import "{0}" /reg:{1}'.format(cache_path, word_sz_txt)
cmd_ret_dict = __salt__['cmd.run_all'](cmd, python_shell=True)
retcode = cmd_ret_dict['retcode']
if retcode != 0:
raise CommandExecutionError(
'reg.exe import failed',
info=cmd_ret_dict
)
return True
|
saltstack/salt
|
salt/modules/reg.py
|
read_value
|
python
|
def read_value(hive, key, vname=None, use_32bit_registry=False):
r'''
Reads a registry value entry or the default value for a key. To read the
default value, don't pass ``vname``
Args:
hive (str): The name of the hive. Can be one of the following:
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name.
vname (str):
The value name. These are the individual name/data pairs under the
key. If not passed, the key (Default) value will be returned.
use_32bit_registry (bool):
Accesses the 32bit portion of the registry on 64bit installations.
On 32bit machines this is ignored.
Returns:
dict: A dictionary containing the passed settings as well as the
value_data if successful. If unsuccessful, sets success to False.
bool: Returns False if the key is not found
If vname is not passed:
- Returns the first unnamed value (Default) as a string.
- Returns none if first unnamed value is empty.
CLI Example:
The following will get the value of the ``version`` value name in the
``HKEY_LOCAL_MACHINE\\SOFTWARE\\Salt`` key
.. code-block:: bash
salt '*' reg.read_value HKEY_LOCAL_MACHINE 'SOFTWARE\Salt' 'version'
CLI Example:
The following will get the default value of the
``HKEY_LOCAL_MACHINE\\SOFTWARE\\Salt`` key
.. code-block:: bash
salt '*' reg.read_value HKEY_LOCAL_MACHINE 'SOFTWARE\Salt'
'''
return __utils__['reg.read_value'](hive=hive,
key=key,
vname=vname,
use_32bit_registry=use_32bit_registry)
|
r'''
Reads a registry value entry or the default value for a key. To read the
default value, don't pass ``vname``
Args:
hive (str): The name of the hive. Can be one of the following:
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name.
vname (str):
The value name. These are the individual name/data pairs under the
key. If not passed, the key (Default) value will be returned.
use_32bit_registry (bool):
Accesses the 32bit portion of the registry on 64bit installations.
On 32bit machines this is ignored.
Returns:
dict: A dictionary containing the passed settings as well as the
value_data if successful. If unsuccessful, sets success to False.
bool: Returns False if the key is not found
If vname is not passed:
- Returns the first unnamed value (Default) as a string.
- Returns none if first unnamed value is empty.
CLI Example:
The following will get the value of the ``version`` value name in the
``HKEY_LOCAL_MACHINE\\SOFTWARE\\Salt`` key
.. code-block:: bash
salt '*' reg.read_value HKEY_LOCAL_MACHINE 'SOFTWARE\Salt' 'version'
CLI Example:
The following will get the default value of the
``HKEY_LOCAL_MACHINE\\SOFTWARE\\Salt`` key
.. code-block:: bash
salt '*' reg.read_value HKEY_LOCAL_MACHINE 'SOFTWARE\Salt'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/reg.py#L224-L282
| null |
# -*- coding: utf-8 -*-
r'''
Manage the Windows registry
Hives
-----
Hives are the main sections of the registry and all begin with the word HKEY.
- HKEY_LOCAL_MACHINE
- HKEY_CURRENT_USER
- HKEY_USER
Keys
----
Keys are the folders in the registry. Keys can have many nested subkeys. Keys
can have a value assigned to them under the (Default)
When passing a key on the CLI it must be quoted correctly depending on the
backslashes being used (``\`` vs ``\\``). The following are valid methods of
passing the the key on the CLI:
Using single backslashes:
``"SOFTWARE\Python"``
``'SOFTWARE\Python'`` (will not work on a Windows Master)
Using double backslashes:
``SOFTWARE\\Python``
-----------------
Values or Entries
-----------------
Values or Entries are the name/data pairs beneath the keys and subkeys. All keys
have a default name/data pair. The name is ``(Default)`` with a displayed value
of ``(value not set)``. The actual value is Null.
Example
-------
The following example is an export from the Windows startup portion of the
registry:
.. code-block:: bash
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run]
"RTHDVCPL"="\"C:\\Program Files\\Realtek\\Audio\\HDA\\RtkNGUI64.exe\" -s"
"NvBackend"="\"C:\\Program Files (x86)\\NVIDIA Corporation\\Update Core\\NvBackend.exe\""
"BTMTrayAgent"="rundll32.exe \"C:\\Program Files (x86)\\Intel\\Bluetooth\\btmshellex.dll\",TrayApp"
In this example these are the values for each:
Hive:
``HKEY_LOCAL_MACHINE``
Key and subkeys:
``SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run``
Value:
- There are 3 value names:
- `RTHDVCPL`
- `NvBackend`
- `BTMTrayAgent`
- Each value name has a corresponding value
:depends: - salt.utils.win_reg
'''
# When production windows installer is using Python 3, Python 2 code can be removed
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
# Import Salt libs
import salt.utils.platform
from salt.exceptions import CommandExecutionError
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'reg'
def __virtual__():
'''
Only works on Windows systems with PyWin32
'''
if not salt.utils.platform.is_windows():
return (False, 'reg execution module failed to load: '
'The module will only run on Windows systems')
if 'reg.read_value' not in __utils__:
return (False, 'reg execution module failed to load: '
'The reg salt util is unavailable')
return __virtualname__
def key_exists(hive, key, use_32bit_registry=False):
r'''
Check that the key is found in the registry. This refers to keys and not
value/data pairs.
Args:
hive (str): The hive to connect to
key (str): The key to check
use_32bit_registry (bool): Look in the 32bit portion of the registry
Returns:
bool: True if exists, otherwise False
CLI Example:
.. code-block:: bash
salt '*' reg.key_exists HKLM SOFTWARE\Microsoft
'''
return __utils__['reg.key_exists'](hive=hive,
key=key,
use_32bit_registry=use_32bit_registry)
def broadcast_change():
'''
Refresh the windows environment.
.. note::
This will only effect new processes and windows. Services will not see
the change until the system restarts.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' reg.broadcast_change
'''
return salt.utils.win_functions.broadcast_setting_change('Environment')
def list_keys(hive, key=None, use_32bit_registry=False):
'''
Enumerates the subkeys in a registry key or hive.
Args:
hive (str):
The name of the hive. Can be one of the following:
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name. If a key is not
passed, the keys under the hive will be returned.
use_32bit_registry (bool):
Accesses the 32bit portion of the registry on 64 bit installations.
On 32bit machines this is ignored.
Returns:
list: A list of keys/subkeys under the hive or key.
CLI Example:
.. code-block:: bash
salt '*' reg.list_keys HKLM 'SOFTWARE'
'''
return __utils__['reg.list_keys'](hive=hive,
key=key,
use_32bit_registry=use_32bit_registry)
def list_values(hive, key=None, use_32bit_registry=False, include_default=True):
r'''
Enumerates the values in a registry key or hive.
Args:
hive (str):
The name of the hive. Can be one of the following:
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name. If a key is not
passed, the values under the hive will be returned.
use_32bit_registry (bool):
Accesses the 32bit portion of the registry on 64 bit installations.
On 32bit machines this is ignored.
include_default (bool):
Toggle whether to include the '(Default)' value.
Returns:
list: A list of values under the hive or key.
CLI Example:
.. code-block:: bash
salt '*' reg.list_values HKLM 'SYSTEM\\CurrentControlSet\\Services\\Tcpip'
'''
return __utils__['reg.list_values'](hive=hive,
key=key,
use_32bit_registry=use_32bit_registry,
include_default=include_default)
def set_value(hive,
key,
vname=None,
vdata=None,
vtype='REG_SZ',
use_32bit_registry=False,
volatile=False):
'''
Sets a value in the registry. If ``vname`` is passed, it will be the value
for that value name, otherwise it will be the default value for the
specified key
Args:
hive (str):
The name of the hive. Can be one of the following
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name.
vname (str):
The value name. These are the individual name/data pairs under the
key. If not passed, the key (Default) value will be set.
vdata (str, int, list, bytes):
The value you'd like to set. If a value name (vname) is passed, this
will be the data for that value name. If not, this will be the
(Default) value for the key.
The type of data this parameter expects is determined by the value
type specified in ``vtype``. The correspondence is as follows:
- REG_BINARY: Binary data (str in Py2, bytes in Py3)
- REG_DWORD: int
- REG_EXPAND_SZ: str
- REG_MULTI_SZ: list of str
- REG_QWORD: int
- REG_SZ: str
.. note::
When setting REG_BINARY, string data will be converted to
binary.
.. note::
The type for the (Default) value is always REG_SZ and cannot be
changed.
.. note::
This parameter is optional. If ``vdata`` is not passed, the Key
will be created with no associated item/value pairs.
vtype (str):
The value type. The possible values of the vtype parameter are
indicated above in the description of the vdata parameter.
use_32bit_registry (bool):
Sets the 32bit portion of the registry on 64bit installations. On
32bit machines this is ignored.
volatile (bool):
When this parameter has a value of True, the registry key will be
made volatile (i.e. it will not persist beyond a system reset or
shutdown). This parameter only has an effect when a key is being
created and at no other time.
Returns:
bool: True if successful, otherwise False
CLI Example:
This will set the version value to 2015.5.2 in the SOFTWARE\\Salt key in
the HKEY_LOCAL_MACHINE hive
.. code-block:: bash
salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'version' '2015.5.2'
CLI Example:
This function is strict about the type of vdata. For instance this
example will fail because vtype has a value of REG_SZ and vdata has a
type of int (as opposed to str as expected).
.. code-block:: bash
salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'str_data' 1.2
CLI Example:
In this next example vdata is properly quoted and should succeed.
.. code-block:: bash
salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'str_data' vtype=REG_SZ vdata="'1.2'"
CLI Example:
This is an example of using vtype REG_BINARY.
.. code-block:: bash
salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'bin_data' vtype=REG_BINARY vdata='Salty Data'
CLI Example:
An example of using vtype REG_MULTI_SZ is as follows:
.. code-block:: bash
salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'list_data' vtype=REG_MULTI_SZ vdata='["Salt", "is", "great"]'
'''
return __utils__['reg.set_value'](hive=hive,
key=key,
vname=vname,
vdata=vdata,
vtype=vtype,
use_32bit_registry=use_32bit_registry,
volatile=volatile)
def delete_key_recursive(hive, key, use_32bit_registry=False):
r'''
.. versionadded:: 2015.5.4
Delete a registry key to include all subkeys and value/data pairs.
Args:
hive (str):
The name of the hive. Can be one of the following
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key to remove (looks like a path)
use_32bit_registry (bool):
Deletes the 32bit portion of the registry on 64bit
installations. On 32bit machines this is ignored.
Returns:
dict: A dictionary listing the keys that deleted successfully as well as
those that failed to delete.
CLI Example:
The following example will remove ``delete_me`` and all its subkeys from the
``SOFTWARE`` key in ``HKEY_LOCAL_MACHINE``:
.. code-block:: bash
salt '*' reg.delete_key_recursive HKLM SOFTWARE\\delete_me
'''
return __utils__['reg.delete_key_recursive'](hive=hive,
key=key,
use_32bit_registry=use_32bit_registry)
def delete_value(hive, key, vname=None, use_32bit_registry=False):
r'''
Delete a registry value entry or the default value for a key.
Args:
hive (str):
The name of the hive. Can be one of the following
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name.
vname (str):
The value name. These are the individual name/data pairs under the
key. If not passed, the key (Default) value will be deleted.
use_32bit_registry (bool):
Deletes the 32bit portion of the registry on 64bit installations. On
32bit machines this is ignored.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' reg.delete_value HKEY_CURRENT_USER 'SOFTWARE\\Salt' 'version'
'''
return __utils__['reg.delete_value'](hive=hive,
key=key,
vname=vname,
use_32bit_registry=use_32bit_registry)
def import_file(source, use_32bit_registry=False):
'''
Import registry settings from a Windows ``REG`` file by invoking ``REG.EXE``.
.. versionadded:: 2018.3.0
Args:
source (str):
The full path of the ``REG`` file. This can be either a local file
path or a URL type supported by salt (e.g. ``salt://salt_master_path``)
use_32bit_registry (bool):
If the value of this parameter is ``True`` then the ``REG`` file
will be imported into the Windows 32 bit registry. Otherwise the
Windows 64 bit registry will be used.
Returns:
bool: True if successful, otherwise an error is raised
Raises:
ValueError: If the value of ``source`` is an invalid path or otherwise
causes ``cp.cache_file`` to return ``False``
CommandExecutionError: If ``reg.exe`` exits with a non-0 exit code
CLI Example:
.. code-block:: bash
salt machine1 reg.import_file salt://win/printer_config/110_Canon/postinstall_config.reg
'''
cache_path = __salt__['cp.cache_file'](source)
if not cache_path:
error_msg = "File/URL '{0}' probably invalid.".format(source)
raise ValueError(error_msg)
if use_32bit_registry:
word_sz_txt = "32"
else:
word_sz_txt = "64"
cmd = 'reg import "{0}" /reg:{1}'.format(cache_path, word_sz_txt)
cmd_ret_dict = __salt__['cmd.run_all'](cmd, python_shell=True)
retcode = cmd_ret_dict['retcode']
if retcode != 0:
raise CommandExecutionError(
'reg.exe import failed',
info=cmd_ret_dict
)
return True
|
saltstack/salt
|
salt/modules/reg.py
|
set_value
|
python
|
def set_value(hive,
key,
vname=None,
vdata=None,
vtype='REG_SZ',
use_32bit_registry=False,
volatile=False):
'''
Sets a value in the registry. If ``vname`` is passed, it will be the value
for that value name, otherwise it will be the default value for the
specified key
Args:
hive (str):
The name of the hive. Can be one of the following
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name.
vname (str):
The value name. These are the individual name/data pairs under the
key. If not passed, the key (Default) value will be set.
vdata (str, int, list, bytes):
The value you'd like to set. If a value name (vname) is passed, this
will be the data for that value name. If not, this will be the
(Default) value for the key.
The type of data this parameter expects is determined by the value
type specified in ``vtype``. The correspondence is as follows:
- REG_BINARY: Binary data (str in Py2, bytes in Py3)
- REG_DWORD: int
- REG_EXPAND_SZ: str
- REG_MULTI_SZ: list of str
- REG_QWORD: int
- REG_SZ: str
.. note::
When setting REG_BINARY, string data will be converted to
binary.
.. note::
The type for the (Default) value is always REG_SZ and cannot be
changed.
.. note::
This parameter is optional. If ``vdata`` is not passed, the Key
will be created with no associated item/value pairs.
vtype (str):
The value type. The possible values of the vtype parameter are
indicated above in the description of the vdata parameter.
use_32bit_registry (bool):
Sets the 32bit portion of the registry on 64bit installations. On
32bit machines this is ignored.
volatile (bool):
When this parameter has a value of True, the registry key will be
made volatile (i.e. it will not persist beyond a system reset or
shutdown). This parameter only has an effect when a key is being
created and at no other time.
Returns:
bool: True if successful, otherwise False
CLI Example:
This will set the version value to 2015.5.2 in the SOFTWARE\\Salt key in
the HKEY_LOCAL_MACHINE hive
.. code-block:: bash
salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'version' '2015.5.2'
CLI Example:
This function is strict about the type of vdata. For instance this
example will fail because vtype has a value of REG_SZ and vdata has a
type of int (as opposed to str as expected).
.. code-block:: bash
salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'str_data' 1.2
CLI Example:
In this next example vdata is properly quoted and should succeed.
.. code-block:: bash
salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'str_data' vtype=REG_SZ vdata="'1.2'"
CLI Example:
This is an example of using vtype REG_BINARY.
.. code-block:: bash
salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'bin_data' vtype=REG_BINARY vdata='Salty Data'
CLI Example:
An example of using vtype REG_MULTI_SZ is as follows:
.. code-block:: bash
salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'list_data' vtype=REG_MULTI_SZ vdata='["Salt", "is", "great"]'
'''
return __utils__['reg.set_value'](hive=hive,
key=key,
vname=vname,
vdata=vdata,
vtype=vtype,
use_32bit_registry=use_32bit_registry,
volatile=volatile)
|
Sets a value in the registry. If ``vname`` is passed, it will be the value
for that value name, otherwise it will be the default value for the
specified key
Args:
hive (str):
The name of the hive. Can be one of the following
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name.
vname (str):
The value name. These are the individual name/data pairs under the
key. If not passed, the key (Default) value will be set.
vdata (str, int, list, bytes):
The value you'd like to set. If a value name (vname) is passed, this
will be the data for that value name. If not, this will be the
(Default) value for the key.
The type of data this parameter expects is determined by the value
type specified in ``vtype``. The correspondence is as follows:
- REG_BINARY: Binary data (str in Py2, bytes in Py3)
- REG_DWORD: int
- REG_EXPAND_SZ: str
- REG_MULTI_SZ: list of str
- REG_QWORD: int
- REG_SZ: str
.. note::
When setting REG_BINARY, string data will be converted to
binary.
.. note::
The type for the (Default) value is always REG_SZ and cannot be
changed.
.. note::
This parameter is optional. If ``vdata`` is not passed, the Key
will be created with no associated item/value pairs.
vtype (str):
The value type. The possible values of the vtype parameter are
indicated above in the description of the vdata parameter.
use_32bit_registry (bool):
Sets the 32bit portion of the registry on 64bit installations. On
32bit machines this is ignored.
volatile (bool):
When this parameter has a value of True, the registry key will be
made volatile (i.e. it will not persist beyond a system reset or
shutdown). This parameter only has an effect when a key is being
created and at no other time.
Returns:
bool: True if successful, otherwise False
CLI Example:
This will set the version value to 2015.5.2 in the SOFTWARE\\Salt key in
the HKEY_LOCAL_MACHINE hive
.. code-block:: bash
salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'version' '2015.5.2'
CLI Example:
This function is strict about the type of vdata. For instance this
example will fail because vtype has a value of REG_SZ and vdata has a
type of int (as opposed to str as expected).
.. code-block:: bash
salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'str_data' 1.2
CLI Example:
In this next example vdata is properly quoted and should succeed.
.. code-block:: bash
salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'str_data' vtype=REG_SZ vdata="'1.2'"
CLI Example:
This is an example of using vtype REG_BINARY.
.. code-block:: bash
salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'bin_data' vtype=REG_BINARY vdata='Salty Data'
CLI Example:
An example of using vtype REG_MULTI_SZ is as follows:
.. code-block:: bash
salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'list_data' vtype=REG_MULTI_SZ vdata='["Salt", "is", "great"]'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/reg.py#L285-L408
| null |
# -*- coding: utf-8 -*-
r'''
Manage the Windows registry
Hives
-----
Hives are the main sections of the registry and all begin with the word HKEY.
- HKEY_LOCAL_MACHINE
- HKEY_CURRENT_USER
- HKEY_USER
Keys
----
Keys are the folders in the registry. Keys can have many nested subkeys. Keys
can have a value assigned to them under the (Default)
When passing a key on the CLI it must be quoted correctly depending on the
backslashes being used (``\`` vs ``\\``). The following are valid methods of
passing the the key on the CLI:
Using single backslashes:
``"SOFTWARE\Python"``
``'SOFTWARE\Python'`` (will not work on a Windows Master)
Using double backslashes:
``SOFTWARE\\Python``
-----------------
Values or Entries
-----------------
Values or Entries are the name/data pairs beneath the keys and subkeys. All keys
have a default name/data pair. The name is ``(Default)`` with a displayed value
of ``(value not set)``. The actual value is Null.
Example
-------
The following example is an export from the Windows startup portion of the
registry:
.. code-block:: bash
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run]
"RTHDVCPL"="\"C:\\Program Files\\Realtek\\Audio\\HDA\\RtkNGUI64.exe\" -s"
"NvBackend"="\"C:\\Program Files (x86)\\NVIDIA Corporation\\Update Core\\NvBackend.exe\""
"BTMTrayAgent"="rundll32.exe \"C:\\Program Files (x86)\\Intel\\Bluetooth\\btmshellex.dll\",TrayApp"
In this example these are the values for each:
Hive:
``HKEY_LOCAL_MACHINE``
Key and subkeys:
``SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run``
Value:
- There are 3 value names:
- `RTHDVCPL`
- `NvBackend`
- `BTMTrayAgent`
- Each value name has a corresponding value
:depends: - salt.utils.win_reg
'''
# When production windows installer is using Python 3, Python 2 code can be removed
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
# Import Salt libs
import salt.utils.platform
from salt.exceptions import CommandExecutionError
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'reg'
def __virtual__():
'''
Only works on Windows systems with PyWin32
'''
if not salt.utils.platform.is_windows():
return (False, 'reg execution module failed to load: '
'The module will only run on Windows systems')
if 'reg.read_value' not in __utils__:
return (False, 'reg execution module failed to load: '
'The reg salt util is unavailable')
return __virtualname__
def key_exists(hive, key, use_32bit_registry=False):
r'''
Check that the key is found in the registry. This refers to keys and not
value/data pairs.
Args:
hive (str): The hive to connect to
key (str): The key to check
use_32bit_registry (bool): Look in the 32bit portion of the registry
Returns:
bool: True if exists, otherwise False
CLI Example:
.. code-block:: bash
salt '*' reg.key_exists HKLM SOFTWARE\Microsoft
'''
return __utils__['reg.key_exists'](hive=hive,
key=key,
use_32bit_registry=use_32bit_registry)
def broadcast_change():
'''
Refresh the windows environment.
.. note::
This will only effect new processes and windows. Services will not see
the change until the system restarts.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' reg.broadcast_change
'''
return salt.utils.win_functions.broadcast_setting_change('Environment')
def list_keys(hive, key=None, use_32bit_registry=False):
'''
Enumerates the subkeys in a registry key or hive.
Args:
hive (str):
The name of the hive. Can be one of the following:
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name. If a key is not
passed, the keys under the hive will be returned.
use_32bit_registry (bool):
Accesses the 32bit portion of the registry on 64 bit installations.
On 32bit machines this is ignored.
Returns:
list: A list of keys/subkeys under the hive or key.
CLI Example:
.. code-block:: bash
salt '*' reg.list_keys HKLM 'SOFTWARE'
'''
return __utils__['reg.list_keys'](hive=hive,
key=key,
use_32bit_registry=use_32bit_registry)
def list_values(hive, key=None, use_32bit_registry=False, include_default=True):
r'''
Enumerates the values in a registry key or hive.
Args:
hive (str):
The name of the hive. Can be one of the following:
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name. If a key is not
passed, the values under the hive will be returned.
use_32bit_registry (bool):
Accesses the 32bit portion of the registry on 64 bit installations.
On 32bit machines this is ignored.
include_default (bool):
Toggle whether to include the '(Default)' value.
Returns:
list: A list of values under the hive or key.
CLI Example:
.. code-block:: bash
salt '*' reg.list_values HKLM 'SYSTEM\\CurrentControlSet\\Services\\Tcpip'
'''
return __utils__['reg.list_values'](hive=hive,
key=key,
use_32bit_registry=use_32bit_registry,
include_default=include_default)
def read_value(hive, key, vname=None, use_32bit_registry=False):
r'''
Reads a registry value entry or the default value for a key. To read the
default value, don't pass ``vname``
Args:
hive (str): The name of the hive. Can be one of the following:
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name.
vname (str):
The value name. These are the individual name/data pairs under the
key. If not passed, the key (Default) value will be returned.
use_32bit_registry (bool):
Accesses the 32bit portion of the registry on 64bit installations.
On 32bit machines this is ignored.
Returns:
dict: A dictionary containing the passed settings as well as the
value_data if successful. If unsuccessful, sets success to False.
bool: Returns False if the key is not found
If vname is not passed:
- Returns the first unnamed value (Default) as a string.
- Returns none if first unnamed value is empty.
CLI Example:
The following will get the value of the ``version`` value name in the
``HKEY_LOCAL_MACHINE\\SOFTWARE\\Salt`` key
.. code-block:: bash
salt '*' reg.read_value HKEY_LOCAL_MACHINE 'SOFTWARE\Salt' 'version'
CLI Example:
The following will get the default value of the
``HKEY_LOCAL_MACHINE\\SOFTWARE\\Salt`` key
.. code-block:: bash
salt '*' reg.read_value HKEY_LOCAL_MACHINE 'SOFTWARE\Salt'
'''
return __utils__['reg.read_value'](hive=hive,
key=key,
vname=vname,
use_32bit_registry=use_32bit_registry)
def delete_key_recursive(hive, key, use_32bit_registry=False):
r'''
.. versionadded:: 2015.5.4
Delete a registry key to include all subkeys and value/data pairs.
Args:
hive (str):
The name of the hive. Can be one of the following
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key to remove (looks like a path)
use_32bit_registry (bool):
Deletes the 32bit portion of the registry on 64bit
installations. On 32bit machines this is ignored.
Returns:
dict: A dictionary listing the keys that deleted successfully as well as
those that failed to delete.
CLI Example:
The following example will remove ``delete_me`` and all its subkeys from the
``SOFTWARE`` key in ``HKEY_LOCAL_MACHINE``:
.. code-block:: bash
salt '*' reg.delete_key_recursive HKLM SOFTWARE\\delete_me
'''
return __utils__['reg.delete_key_recursive'](hive=hive,
key=key,
use_32bit_registry=use_32bit_registry)
def delete_value(hive, key, vname=None, use_32bit_registry=False):
r'''
Delete a registry value entry or the default value for a key.
Args:
hive (str):
The name of the hive. Can be one of the following
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name.
vname (str):
The value name. These are the individual name/data pairs under the
key. If not passed, the key (Default) value will be deleted.
use_32bit_registry (bool):
Deletes the 32bit portion of the registry on 64bit installations. On
32bit machines this is ignored.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' reg.delete_value HKEY_CURRENT_USER 'SOFTWARE\\Salt' 'version'
'''
return __utils__['reg.delete_value'](hive=hive,
key=key,
vname=vname,
use_32bit_registry=use_32bit_registry)
def import_file(source, use_32bit_registry=False):
'''
Import registry settings from a Windows ``REG`` file by invoking ``REG.EXE``.
.. versionadded:: 2018.3.0
Args:
source (str):
The full path of the ``REG`` file. This can be either a local file
path or a URL type supported by salt (e.g. ``salt://salt_master_path``)
use_32bit_registry (bool):
If the value of this parameter is ``True`` then the ``REG`` file
will be imported into the Windows 32 bit registry. Otherwise the
Windows 64 bit registry will be used.
Returns:
bool: True if successful, otherwise an error is raised
Raises:
ValueError: If the value of ``source`` is an invalid path or otherwise
causes ``cp.cache_file`` to return ``False``
CommandExecutionError: If ``reg.exe`` exits with a non-0 exit code
CLI Example:
.. code-block:: bash
salt machine1 reg.import_file salt://win/printer_config/110_Canon/postinstall_config.reg
'''
cache_path = __salt__['cp.cache_file'](source)
if not cache_path:
error_msg = "File/URL '{0}' probably invalid.".format(source)
raise ValueError(error_msg)
if use_32bit_registry:
word_sz_txt = "32"
else:
word_sz_txt = "64"
cmd = 'reg import "{0}" /reg:{1}'.format(cache_path, word_sz_txt)
cmd_ret_dict = __salt__['cmd.run_all'](cmd, python_shell=True)
retcode = cmd_ret_dict['retcode']
if retcode != 0:
raise CommandExecutionError(
'reg.exe import failed',
info=cmd_ret_dict
)
return True
|
saltstack/salt
|
salt/modules/reg.py
|
delete_key_recursive
|
python
|
def delete_key_recursive(hive, key, use_32bit_registry=False):
r'''
.. versionadded:: 2015.5.4
Delete a registry key to include all subkeys and value/data pairs.
Args:
hive (str):
The name of the hive. Can be one of the following
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key to remove (looks like a path)
use_32bit_registry (bool):
Deletes the 32bit portion of the registry on 64bit
installations. On 32bit machines this is ignored.
Returns:
dict: A dictionary listing the keys that deleted successfully as well as
those that failed to delete.
CLI Example:
The following example will remove ``delete_me`` and all its subkeys from the
``SOFTWARE`` key in ``HKEY_LOCAL_MACHINE``:
.. code-block:: bash
salt '*' reg.delete_key_recursive HKLM SOFTWARE\\delete_me
'''
return __utils__['reg.delete_key_recursive'](hive=hive,
key=key,
use_32bit_registry=use_32bit_registry)
|
r'''
.. versionadded:: 2015.5.4
Delete a registry key to include all subkeys and value/data pairs.
Args:
hive (str):
The name of the hive. Can be one of the following
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key to remove (looks like a path)
use_32bit_registry (bool):
Deletes the 32bit portion of the registry on 64bit
installations. On 32bit machines this is ignored.
Returns:
dict: A dictionary listing the keys that deleted successfully as well as
those that failed to delete.
CLI Example:
The following example will remove ``delete_me`` and all its subkeys from the
``SOFTWARE`` key in ``HKEY_LOCAL_MACHINE``:
.. code-block:: bash
salt '*' reg.delete_key_recursive HKLM SOFTWARE\\delete_me
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/reg.py#L411-L450
| null |
# -*- coding: utf-8 -*-
r'''
Manage the Windows registry
Hives
-----
Hives are the main sections of the registry and all begin with the word HKEY.
- HKEY_LOCAL_MACHINE
- HKEY_CURRENT_USER
- HKEY_USER
Keys
----
Keys are the folders in the registry. Keys can have many nested subkeys. Keys
can have a value assigned to them under the (Default)
When passing a key on the CLI it must be quoted correctly depending on the
backslashes being used (``\`` vs ``\\``). The following are valid methods of
passing the the key on the CLI:
Using single backslashes:
``"SOFTWARE\Python"``
``'SOFTWARE\Python'`` (will not work on a Windows Master)
Using double backslashes:
``SOFTWARE\\Python``
-----------------
Values or Entries
-----------------
Values or Entries are the name/data pairs beneath the keys and subkeys. All keys
have a default name/data pair. The name is ``(Default)`` with a displayed value
of ``(value not set)``. The actual value is Null.
Example
-------
The following example is an export from the Windows startup portion of the
registry:
.. code-block:: bash
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run]
"RTHDVCPL"="\"C:\\Program Files\\Realtek\\Audio\\HDA\\RtkNGUI64.exe\" -s"
"NvBackend"="\"C:\\Program Files (x86)\\NVIDIA Corporation\\Update Core\\NvBackend.exe\""
"BTMTrayAgent"="rundll32.exe \"C:\\Program Files (x86)\\Intel\\Bluetooth\\btmshellex.dll\",TrayApp"
In this example these are the values for each:
Hive:
``HKEY_LOCAL_MACHINE``
Key and subkeys:
``SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run``
Value:
- There are 3 value names:
- `RTHDVCPL`
- `NvBackend`
- `BTMTrayAgent`
- Each value name has a corresponding value
:depends: - salt.utils.win_reg
'''
# When production windows installer is using Python 3, Python 2 code can be removed
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
# Import Salt libs
import salt.utils.platform
from salt.exceptions import CommandExecutionError
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'reg'
def __virtual__():
'''
Only works on Windows systems with PyWin32
'''
if not salt.utils.platform.is_windows():
return (False, 'reg execution module failed to load: '
'The module will only run on Windows systems')
if 'reg.read_value' not in __utils__:
return (False, 'reg execution module failed to load: '
'The reg salt util is unavailable')
return __virtualname__
def key_exists(hive, key, use_32bit_registry=False):
r'''
Check that the key is found in the registry. This refers to keys and not
value/data pairs.
Args:
hive (str): The hive to connect to
key (str): The key to check
use_32bit_registry (bool): Look in the 32bit portion of the registry
Returns:
bool: True if exists, otherwise False
CLI Example:
.. code-block:: bash
salt '*' reg.key_exists HKLM SOFTWARE\Microsoft
'''
return __utils__['reg.key_exists'](hive=hive,
key=key,
use_32bit_registry=use_32bit_registry)
def broadcast_change():
'''
Refresh the windows environment.
.. note::
This will only effect new processes and windows. Services will not see
the change until the system restarts.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' reg.broadcast_change
'''
return salt.utils.win_functions.broadcast_setting_change('Environment')
def list_keys(hive, key=None, use_32bit_registry=False):
'''
Enumerates the subkeys in a registry key or hive.
Args:
hive (str):
The name of the hive. Can be one of the following:
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name. If a key is not
passed, the keys under the hive will be returned.
use_32bit_registry (bool):
Accesses the 32bit portion of the registry on 64 bit installations.
On 32bit machines this is ignored.
Returns:
list: A list of keys/subkeys under the hive or key.
CLI Example:
.. code-block:: bash
salt '*' reg.list_keys HKLM 'SOFTWARE'
'''
return __utils__['reg.list_keys'](hive=hive,
key=key,
use_32bit_registry=use_32bit_registry)
def list_values(hive, key=None, use_32bit_registry=False, include_default=True):
r'''
Enumerates the values in a registry key or hive.
Args:
hive (str):
The name of the hive. Can be one of the following:
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name. If a key is not
passed, the values under the hive will be returned.
use_32bit_registry (bool):
Accesses the 32bit portion of the registry on 64 bit installations.
On 32bit machines this is ignored.
include_default (bool):
Toggle whether to include the '(Default)' value.
Returns:
list: A list of values under the hive or key.
CLI Example:
.. code-block:: bash
salt '*' reg.list_values HKLM 'SYSTEM\\CurrentControlSet\\Services\\Tcpip'
'''
return __utils__['reg.list_values'](hive=hive,
key=key,
use_32bit_registry=use_32bit_registry,
include_default=include_default)
def read_value(hive, key, vname=None, use_32bit_registry=False):
r'''
Reads a registry value entry or the default value for a key. To read the
default value, don't pass ``vname``
Args:
hive (str): The name of the hive. Can be one of the following:
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name.
vname (str):
The value name. These are the individual name/data pairs under the
key. If not passed, the key (Default) value will be returned.
use_32bit_registry (bool):
Accesses the 32bit portion of the registry on 64bit installations.
On 32bit machines this is ignored.
Returns:
dict: A dictionary containing the passed settings as well as the
value_data if successful. If unsuccessful, sets success to False.
bool: Returns False if the key is not found
If vname is not passed:
- Returns the first unnamed value (Default) as a string.
- Returns none if first unnamed value is empty.
CLI Example:
The following will get the value of the ``version`` value name in the
``HKEY_LOCAL_MACHINE\\SOFTWARE\\Salt`` key
.. code-block:: bash
salt '*' reg.read_value HKEY_LOCAL_MACHINE 'SOFTWARE\Salt' 'version'
CLI Example:
The following will get the default value of the
``HKEY_LOCAL_MACHINE\\SOFTWARE\\Salt`` key
.. code-block:: bash
salt '*' reg.read_value HKEY_LOCAL_MACHINE 'SOFTWARE\Salt'
'''
return __utils__['reg.read_value'](hive=hive,
key=key,
vname=vname,
use_32bit_registry=use_32bit_registry)
def set_value(hive,
key,
vname=None,
vdata=None,
vtype='REG_SZ',
use_32bit_registry=False,
volatile=False):
'''
Sets a value in the registry. If ``vname`` is passed, it will be the value
for that value name, otherwise it will be the default value for the
specified key
Args:
hive (str):
The name of the hive. Can be one of the following
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name.
vname (str):
The value name. These are the individual name/data pairs under the
key. If not passed, the key (Default) value will be set.
vdata (str, int, list, bytes):
The value you'd like to set. If a value name (vname) is passed, this
will be the data for that value name. If not, this will be the
(Default) value for the key.
The type of data this parameter expects is determined by the value
type specified in ``vtype``. The correspondence is as follows:
- REG_BINARY: Binary data (str in Py2, bytes in Py3)
- REG_DWORD: int
- REG_EXPAND_SZ: str
- REG_MULTI_SZ: list of str
- REG_QWORD: int
- REG_SZ: str
.. note::
When setting REG_BINARY, string data will be converted to
binary.
.. note::
The type for the (Default) value is always REG_SZ and cannot be
changed.
.. note::
This parameter is optional. If ``vdata`` is not passed, the Key
will be created with no associated item/value pairs.
vtype (str):
The value type. The possible values of the vtype parameter are
indicated above in the description of the vdata parameter.
use_32bit_registry (bool):
Sets the 32bit portion of the registry on 64bit installations. On
32bit machines this is ignored.
volatile (bool):
When this parameter has a value of True, the registry key will be
made volatile (i.e. it will not persist beyond a system reset or
shutdown). This parameter only has an effect when a key is being
created and at no other time.
Returns:
bool: True if successful, otherwise False
CLI Example:
This will set the version value to 2015.5.2 in the SOFTWARE\\Salt key in
the HKEY_LOCAL_MACHINE hive
.. code-block:: bash
salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'version' '2015.5.2'
CLI Example:
This function is strict about the type of vdata. For instance this
example will fail because vtype has a value of REG_SZ and vdata has a
type of int (as opposed to str as expected).
.. code-block:: bash
salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'str_data' 1.2
CLI Example:
In this next example vdata is properly quoted and should succeed.
.. code-block:: bash
salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'str_data' vtype=REG_SZ vdata="'1.2'"
CLI Example:
This is an example of using vtype REG_BINARY.
.. code-block:: bash
salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'bin_data' vtype=REG_BINARY vdata='Salty Data'
CLI Example:
An example of using vtype REG_MULTI_SZ is as follows:
.. code-block:: bash
salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'list_data' vtype=REG_MULTI_SZ vdata='["Salt", "is", "great"]'
'''
return __utils__['reg.set_value'](hive=hive,
key=key,
vname=vname,
vdata=vdata,
vtype=vtype,
use_32bit_registry=use_32bit_registry,
volatile=volatile)
def delete_value(hive, key, vname=None, use_32bit_registry=False):
r'''
Delete a registry value entry or the default value for a key.
Args:
hive (str):
The name of the hive. Can be one of the following
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name.
vname (str):
The value name. These are the individual name/data pairs under the
key. If not passed, the key (Default) value will be deleted.
use_32bit_registry (bool):
Deletes the 32bit portion of the registry on 64bit installations. On
32bit machines this is ignored.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' reg.delete_value HKEY_CURRENT_USER 'SOFTWARE\\Salt' 'version'
'''
return __utils__['reg.delete_value'](hive=hive,
key=key,
vname=vname,
use_32bit_registry=use_32bit_registry)
def import_file(source, use_32bit_registry=False):
'''
Import registry settings from a Windows ``REG`` file by invoking ``REG.EXE``.
.. versionadded:: 2018.3.0
Args:
source (str):
The full path of the ``REG`` file. This can be either a local file
path or a URL type supported by salt (e.g. ``salt://salt_master_path``)
use_32bit_registry (bool):
If the value of this parameter is ``True`` then the ``REG`` file
will be imported into the Windows 32 bit registry. Otherwise the
Windows 64 bit registry will be used.
Returns:
bool: True if successful, otherwise an error is raised
Raises:
ValueError: If the value of ``source`` is an invalid path or otherwise
causes ``cp.cache_file`` to return ``False``
CommandExecutionError: If ``reg.exe`` exits with a non-0 exit code
CLI Example:
.. code-block:: bash
salt machine1 reg.import_file salt://win/printer_config/110_Canon/postinstall_config.reg
'''
cache_path = __salt__['cp.cache_file'](source)
if not cache_path:
error_msg = "File/URL '{0}' probably invalid.".format(source)
raise ValueError(error_msg)
if use_32bit_registry:
word_sz_txt = "32"
else:
word_sz_txt = "64"
cmd = 'reg import "{0}" /reg:{1}'.format(cache_path, word_sz_txt)
cmd_ret_dict = __salt__['cmd.run_all'](cmd, python_shell=True)
retcode = cmd_ret_dict['retcode']
if retcode != 0:
raise CommandExecutionError(
'reg.exe import failed',
info=cmd_ret_dict
)
return True
|
saltstack/salt
|
salt/modules/reg.py
|
delete_value
|
python
|
def delete_value(hive, key, vname=None, use_32bit_registry=False):
r'''
Delete a registry value entry or the default value for a key.
Args:
hive (str):
The name of the hive. Can be one of the following
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name.
vname (str):
The value name. These are the individual name/data pairs under the
key. If not passed, the key (Default) value will be deleted.
use_32bit_registry (bool):
Deletes the 32bit portion of the registry on 64bit installations. On
32bit machines this is ignored.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' reg.delete_value HKEY_CURRENT_USER 'SOFTWARE\\Salt' 'version'
'''
return __utils__['reg.delete_value'](hive=hive,
key=key,
vname=vname,
use_32bit_registry=use_32bit_registry)
|
r'''
Delete a registry value entry or the default value for a key.
Args:
hive (str):
The name of the hive. Can be one of the following
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name.
vname (str):
The value name. These are the individual name/data pairs under the
key. If not passed, the key (Default) value will be deleted.
use_32bit_registry (bool):
Deletes the 32bit portion of the registry on 64bit installations. On
32bit machines this is ignored.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' reg.delete_value HKEY_CURRENT_USER 'SOFTWARE\\Salt' 'version'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/reg.py#L453-L491
| null |
# -*- coding: utf-8 -*-
r'''
Manage the Windows registry
Hives
-----
Hives are the main sections of the registry and all begin with the word HKEY.
- HKEY_LOCAL_MACHINE
- HKEY_CURRENT_USER
- HKEY_USER
Keys
----
Keys are the folders in the registry. Keys can have many nested subkeys. Keys
can have a value assigned to them under the (Default)
When passing a key on the CLI it must be quoted correctly depending on the
backslashes being used (``\`` vs ``\\``). The following are valid methods of
passing the the key on the CLI:
Using single backslashes:
``"SOFTWARE\Python"``
``'SOFTWARE\Python'`` (will not work on a Windows Master)
Using double backslashes:
``SOFTWARE\\Python``
-----------------
Values or Entries
-----------------
Values or Entries are the name/data pairs beneath the keys and subkeys. All keys
have a default name/data pair. The name is ``(Default)`` with a displayed value
of ``(value not set)``. The actual value is Null.
Example
-------
The following example is an export from the Windows startup portion of the
registry:
.. code-block:: bash
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run]
"RTHDVCPL"="\"C:\\Program Files\\Realtek\\Audio\\HDA\\RtkNGUI64.exe\" -s"
"NvBackend"="\"C:\\Program Files (x86)\\NVIDIA Corporation\\Update Core\\NvBackend.exe\""
"BTMTrayAgent"="rundll32.exe \"C:\\Program Files (x86)\\Intel\\Bluetooth\\btmshellex.dll\",TrayApp"
In this example these are the values for each:
Hive:
``HKEY_LOCAL_MACHINE``
Key and subkeys:
``SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run``
Value:
- There are 3 value names:
- `RTHDVCPL`
- `NvBackend`
- `BTMTrayAgent`
- Each value name has a corresponding value
:depends: - salt.utils.win_reg
'''
# When production windows installer is using Python 3, Python 2 code can be removed
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
# Import Salt libs
import salt.utils.platform
from salt.exceptions import CommandExecutionError
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'reg'
def __virtual__():
'''
Only works on Windows systems with PyWin32
'''
if not salt.utils.platform.is_windows():
return (False, 'reg execution module failed to load: '
'The module will only run on Windows systems')
if 'reg.read_value' not in __utils__:
return (False, 'reg execution module failed to load: '
'The reg salt util is unavailable')
return __virtualname__
def key_exists(hive, key, use_32bit_registry=False):
r'''
Check that the key is found in the registry. This refers to keys and not
value/data pairs.
Args:
hive (str): The hive to connect to
key (str): The key to check
use_32bit_registry (bool): Look in the 32bit portion of the registry
Returns:
bool: True if exists, otherwise False
CLI Example:
.. code-block:: bash
salt '*' reg.key_exists HKLM SOFTWARE\Microsoft
'''
return __utils__['reg.key_exists'](hive=hive,
key=key,
use_32bit_registry=use_32bit_registry)
def broadcast_change():
'''
Refresh the windows environment.
.. note::
This will only effect new processes and windows. Services will not see
the change until the system restarts.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' reg.broadcast_change
'''
return salt.utils.win_functions.broadcast_setting_change('Environment')
def list_keys(hive, key=None, use_32bit_registry=False):
'''
Enumerates the subkeys in a registry key or hive.
Args:
hive (str):
The name of the hive. Can be one of the following:
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name. If a key is not
passed, the keys under the hive will be returned.
use_32bit_registry (bool):
Accesses the 32bit portion of the registry on 64 bit installations.
On 32bit machines this is ignored.
Returns:
list: A list of keys/subkeys under the hive or key.
CLI Example:
.. code-block:: bash
salt '*' reg.list_keys HKLM 'SOFTWARE'
'''
return __utils__['reg.list_keys'](hive=hive,
key=key,
use_32bit_registry=use_32bit_registry)
def list_values(hive, key=None, use_32bit_registry=False, include_default=True):
r'''
Enumerates the values in a registry key or hive.
Args:
hive (str):
The name of the hive. Can be one of the following:
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name. If a key is not
passed, the values under the hive will be returned.
use_32bit_registry (bool):
Accesses the 32bit portion of the registry on 64 bit installations.
On 32bit machines this is ignored.
include_default (bool):
Toggle whether to include the '(Default)' value.
Returns:
list: A list of values under the hive or key.
CLI Example:
.. code-block:: bash
salt '*' reg.list_values HKLM 'SYSTEM\\CurrentControlSet\\Services\\Tcpip'
'''
return __utils__['reg.list_values'](hive=hive,
key=key,
use_32bit_registry=use_32bit_registry,
include_default=include_default)
def read_value(hive, key, vname=None, use_32bit_registry=False):
r'''
Reads a registry value entry or the default value for a key. To read the
default value, don't pass ``vname``
Args:
hive (str): The name of the hive. Can be one of the following:
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name.
vname (str):
The value name. These are the individual name/data pairs under the
key. If not passed, the key (Default) value will be returned.
use_32bit_registry (bool):
Accesses the 32bit portion of the registry on 64bit installations.
On 32bit machines this is ignored.
Returns:
dict: A dictionary containing the passed settings as well as the
value_data if successful. If unsuccessful, sets success to False.
bool: Returns False if the key is not found
If vname is not passed:
- Returns the first unnamed value (Default) as a string.
- Returns none if first unnamed value is empty.
CLI Example:
The following will get the value of the ``version`` value name in the
``HKEY_LOCAL_MACHINE\\SOFTWARE\\Salt`` key
.. code-block:: bash
salt '*' reg.read_value HKEY_LOCAL_MACHINE 'SOFTWARE\Salt' 'version'
CLI Example:
The following will get the default value of the
``HKEY_LOCAL_MACHINE\\SOFTWARE\\Salt`` key
.. code-block:: bash
salt '*' reg.read_value HKEY_LOCAL_MACHINE 'SOFTWARE\Salt'
'''
return __utils__['reg.read_value'](hive=hive,
key=key,
vname=vname,
use_32bit_registry=use_32bit_registry)
def set_value(hive,
key,
vname=None,
vdata=None,
vtype='REG_SZ',
use_32bit_registry=False,
volatile=False):
'''
Sets a value in the registry. If ``vname`` is passed, it will be the value
for that value name, otherwise it will be the default value for the
specified key
Args:
hive (str):
The name of the hive. Can be one of the following
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name.
vname (str):
The value name. These are the individual name/data pairs under the
key. If not passed, the key (Default) value will be set.
vdata (str, int, list, bytes):
The value you'd like to set. If a value name (vname) is passed, this
will be the data for that value name. If not, this will be the
(Default) value for the key.
The type of data this parameter expects is determined by the value
type specified in ``vtype``. The correspondence is as follows:
- REG_BINARY: Binary data (str in Py2, bytes in Py3)
- REG_DWORD: int
- REG_EXPAND_SZ: str
- REG_MULTI_SZ: list of str
- REG_QWORD: int
- REG_SZ: str
.. note::
When setting REG_BINARY, string data will be converted to
binary.
.. note::
The type for the (Default) value is always REG_SZ and cannot be
changed.
.. note::
This parameter is optional. If ``vdata`` is not passed, the Key
will be created with no associated item/value pairs.
vtype (str):
The value type. The possible values of the vtype parameter are
indicated above in the description of the vdata parameter.
use_32bit_registry (bool):
Sets the 32bit portion of the registry on 64bit installations. On
32bit machines this is ignored.
volatile (bool):
When this parameter has a value of True, the registry key will be
made volatile (i.e. it will not persist beyond a system reset or
shutdown). This parameter only has an effect when a key is being
created and at no other time.
Returns:
bool: True if successful, otherwise False
CLI Example:
This will set the version value to 2015.5.2 in the SOFTWARE\\Salt key in
the HKEY_LOCAL_MACHINE hive
.. code-block:: bash
salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'version' '2015.5.2'
CLI Example:
This function is strict about the type of vdata. For instance this
example will fail because vtype has a value of REG_SZ and vdata has a
type of int (as opposed to str as expected).
.. code-block:: bash
salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'str_data' 1.2
CLI Example:
In this next example vdata is properly quoted and should succeed.
.. code-block:: bash
salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'str_data' vtype=REG_SZ vdata="'1.2'"
CLI Example:
This is an example of using vtype REG_BINARY.
.. code-block:: bash
salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'bin_data' vtype=REG_BINARY vdata='Salty Data'
CLI Example:
An example of using vtype REG_MULTI_SZ is as follows:
.. code-block:: bash
salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'list_data' vtype=REG_MULTI_SZ vdata='["Salt", "is", "great"]'
'''
return __utils__['reg.set_value'](hive=hive,
key=key,
vname=vname,
vdata=vdata,
vtype=vtype,
use_32bit_registry=use_32bit_registry,
volatile=volatile)
def delete_key_recursive(hive, key, use_32bit_registry=False):
r'''
.. versionadded:: 2015.5.4
Delete a registry key to include all subkeys and value/data pairs.
Args:
hive (str):
The name of the hive. Can be one of the following
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key to remove (looks like a path)
use_32bit_registry (bool):
Deletes the 32bit portion of the registry on 64bit
installations. On 32bit machines this is ignored.
Returns:
dict: A dictionary listing the keys that deleted successfully as well as
those that failed to delete.
CLI Example:
The following example will remove ``delete_me`` and all its subkeys from the
``SOFTWARE`` key in ``HKEY_LOCAL_MACHINE``:
.. code-block:: bash
salt '*' reg.delete_key_recursive HKLM SOFTWARE\\delete_me
'''
return __utils__['reg.delete_key_recursive'](hive=hive,
key=key,
use_32bit_registry=use_32bit_registry)
def import_file(source, use_32bit_registry=False):
'''
Import registry settings from a Windows ``REG`` file by invoking ``REG.EXE``.
.. versionadded:: 2018.3.0
Args:
source (str):
The full path of the ``REG`` file. This can be either a local file
path or a URL type supported by salt (e.g. ``salt://salt_master_path``)
use_32bit_registry (bool):
If the value of this parameter is ``True`` then the ``REG`` file
will be imported into the Windows 32 bit registry. Otherwise the
Windows 64 bit registry will be used.
Returns:
bool: True if successful, otherwise an error is raised
Raises:
ValueError: If the value of ``source`` is an invalid path or otherwise
causes ``cp.cache_file`` to return ``False``
CommandExecutionError: If ``reg.exe`` exits with a non-0 exit code
CLI Example:
.. code-block:: bash
salt machine1 reg.import_file salt://win/printer_config/110_Canon/postinstall_config.reg
'''
cache_path = __salt__['cp.cache_file'](source)
if not cache_path:
error_msg = "File/URL '{0}' probably invalid.".format(source)
raise ValueError(error_msg)
if use_32bit_registry:
word_sz_txt = "32"
else:
word_sz_txt = "64"
cmd = 'reg import "{0}" /reg:{1}'.format(cache_path, word_sz_txt)
cmd_ret_dict = __salt__['cmd.run_all'](cmd, python_shell=True)
retcode = cmd_ret_dict['retcode']
if retcode != 0:
raise CommandExecutionError(
'reg.exe import failed',
info=cmd_ret_dict
)
return True
|
saltstack/salt
|
salt/modules/reg.py
|
import_file
|
python
|
def import_file(source, use_32bit_registry=False):
'''
Import registry settings from a Windows ``REG`` file by invoking ``REG.EXE``.
.. versionadded:: 2018.3.0
Args:
source (str):
The full path of the ``REG`` file. This can be either a local file
path or a URL type supported by salt (e.g. ``salt://salt_master_path``)
use_32bit_registry (bool):
If the value of this parameter is ``True`` then the ``REG`` file
will be imported into the Windows 32 bit registry. Otherwise the
Windows 64 bit registry will be used.
Returns:
bool: True if successful, otherwise an error is raised
Raises:
ValueError: If the value of ``source`` is an invalid path or otherwise
causes ``cp.cache_file`` to return ``False``
CommandExecutionError: If ``reg.exe`` exits with a non-0 exit code
CLI Example:
.. code-block:: bash
salt machine1 reg.import_file salt://win/printer_config/110_Canon/postinstall_config.reg
'''
cache_path = __salt__['cp.cache_file'](source)
if not cache_path:
error_msg = "File/URL '{0}' probably invalid.".format(source)
raise ValueError(error_msg)
if use_32bit_registry:
word_sz_txt = "32"
else:
word_sz_txt = "64"
cmd = 'reg import "{0}" /reg:{1}'.format(cache_path, word_sz_txt)
cmd_ret_dict = __salt__['cmd.run_all'](cmd, python_shell=True)
retcode = cmd_ret_dict['retcode']
if retcode != 0:
raise CommandExecutionError(
'reg.exe import failed',
info=cmd_ret_dict
)
return True
|
Import registry settings from a Windows ``REG`` file by invoking ``REG.EXE``.
.. versionadded:: 2018.3.0
Args:
source (str):
The full path of the ``REG`` file. This can be either a local file
path or a URL type supported by salt (e.g. ``salt://salt_master_path``)
use_32bit_registry (bool):
If the value of this parameter is ``True`` then the ``REG`` file
will be imported into the Windows 32 bit registry. Otherwise the
Windows 64 bit registry will be used.
Returns:
bool: True if successful, otherwise an error is raised
Raises:
ValueError: If the value of ``source`` is an invalid path or otherwise
causes ``cp.cache_file`` to return ``False``
CommandExecutionError: If ``reg.exe`` exits with a non-0 exit code
CLI Example:
.. code-block:: bash
salt machine1 reg.import_file salt://win/printer_config/110_Canon/postinstall_config.reg
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/reg.py#L494-L542
| null |
# -*- coding: utf-8 -*-
r'''
Manage the Windows registry
Hives
-----
Hives are the main sections of the registry and all begin with the word HKEY.
- HKEY_LOCAL_MACHINE
- HKEY_CURRENT_USER
- HKEY_USER
Keys
----
Keys are the folders in the registry. Keys can have many nested subkeys. Keys
can have a value assigned to them under the (Default)
When passing a key on the CLI it must be quoted correctly depending on the
backslashes being used (``\`` vs ``\\``). The following are valid methods of
passing the the key on the CLI:
Using single backslashes:
``"SOFTWARE\Python"``
``'SOFTWARE\Python'`` (will not work on a Windows Master)
Using double backslashes:
``SOFTWARE\\Python``
-----------------
Values or Entries
-----------------
Values or Entries are the name/data pairs beneath the keys and subkeys. All keys
have a default name/data pair. The name is ``(Default)`` with a displayed value
of ``(value not set)``. The actual value is Null.
Example
-------
The following example is an export from the Windows startup portion of the
registry:
.. code-block:: bash
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run]
"RTHDVCPL"="\"C:\\Program Files\\Realtek\\Audio\\HDA\\RtkNGUI64.exe\" -s"
"NvBackend"="\"C:\\Program Files (x86)\\NVIDIA Corporation\\Update Core\\NvBackend.exe\""
"BTMTrayAgent"="rundll32.exe \"C:\\Program Files (x86)\\Intel\\Bluetooth\\btmshellex.dll\",TrayApp"
In this example these are the values for each:
Hive:
``HKEY_LOCAL_MACHINE``
Key and subkeys:
``SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run``
Value:
- There are 3 value names:
- `RTHDVCPL`
- `NvBackend`
- `BTMTrayAgent`
- Each value name has a corresponding value
:depends: - salt.utils.win_reg
'''
# When production windows installer is using Python 3, Python 2 code can be removed
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import logging
# Import Salt libs
import salt.utils.platform
from salt.exceptions import CommandExecutionError
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'reg'
def __virtual__():
'''
Only works on Windows systems with PyWin32
'''
if not salt.utils.platform.is_windows():
return (False, 'reg execution module failed to load: '
'The module will only run on Windows systems')
if 'reg.read_value' not in __utils__:
return (False, 'reg execution module failed to load: '
'The reg salt util is unavailable')
return __virtualname__
def key_exists(hive, key, use_32bit_registry=False):
r'''
Check that the key is found in the registry. This refers to keys and not
value/data pairs.
Args:
hive (str): The hive to connect to
key (str): The key to check
use_32bit_registry (bool): Look in the 32bit portion of the registry
Returns:
bool: True if exists, otherwise False
CLI Example:
.. code-block:: bash
salt '*' reg.key_exists HKLM SOFTWARE\Microsoft
'''
return __utils__['reg.key_exists'](hive=hive,
key=key,
use_32bit_registry=use_32bit_registry)
def broadcast_change():
'''
Refresh the windows environment.
.. note::
This will only effect new processes and windows. Services will not see
the change until the system restarts.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' reg.broadcast_change
'''
return salt.utils.win_functions.broadcast_setting_change('Environment')
def list_keys(hive, key=None, use_32bit_registry=False):
'''
Enumerates the subkeys in a registry key or hive.
Args:
hive (str):
The name of the hive. Can be one of the following:
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name. If a key is not
passed, the keys under the hive will be returned.
use_32bit_registry (bool):
Accesses the 32bit portion of the registry on 64 bit installations.
On 32bit machines this is ignored.
Returns:
list: A list of keys/subkeys under the hive or key.
CLI Example:
.. code-block:: bash
salt '*' reg.list_keys HKLM 'SOFTWARE'
'''
return __utils__['reg.list_keys'](hive=hive,
key=key,
use_32bit_registry=use_32bit_registry)
def list_values(hive, key=None, use_32bit_registry=False, include_default=True):
r'''
Enumerates the values in a registry key or hive.
Args:
hive (str):
The name of the hive. Can be one of the following:
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name. If a key is not
passed, the values under the hive will be returned.
use_32bit_registry (bool):
Accesses the 32bit portion of the registry on 64 bit installations.
On 32bit machines this is ignored.
include_default (bool):
Toggle whether to include the '(Default)' value.
Returns:
list: A list of values under the hive or key.
CLI Example:
.. code-block:: bash
salt '*' reg.list_values HKLM 'SYSTEM\\CurrentControlSet\\Services\\Tcpip'
'''
return __utils__['reg.list_values'](hive=hive,
key=key,
use_32bit_registry=use_32bit_registry,
include_default=include_default)
def read_value(hive, key, vname=None, use_32bit_registry=False):
r'''
Reads a registry value entry or the default value for a key. To read the
default value, don't pass ``vname``
Args:
hive (str): The name of the hive. Can be one of the following:
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name.
vname (str):
The value name. These are the individual name/data pairs under the
key. If not passed, the key (Default) value will be returned.
use_32bit_registry (bool):
Accesses the 32bit portion of the registry on 64bit installations.
On 32bit machines this is ignored.
Returns:
dict: A dictionary containing the passed settings as well as the
value_data if successful. If unsuccessful, sets success to False.
bool: Returns False if the key is not found
If vname is not passed:
- Returns the first unnamed value (Default) as a string.
- Returns none if first unnamed value is empty.
CLI Example:
The following will get the value of the ``version`` value name in the
``HKEY_LOCAL_MACHINE\\SOFTWARE\\Salt`` key
.. code-block:: bash
salt '*' reg.read_value HKEY_LOCAL_MACHINE 'SOFTWARE\Salt' 'version'
CLI Example:
The following will get the default value of the
``HKEY_LOCAL_MACHINE\\SOFTWARE\\Salt`` key
.. code-block:: bash
salt '*' reg.read_value HKEY_LOCAL_MACHINE 'SOFTWARE\Salt'
'''
return __utils__['reg.read_value'](hive=hive,
key=key,
vname=vname,
use_32bit_registry=use_32bit_registry)
def set_value(hive,
key,
vname=None,
vdata=None,
vtype='REG_SZ',
use_32bit_registry=False,
volatile=False):
'''
Sets a value in the registry. If ``vname`` is passed, it will be the value
for that value name, otherwise it will be the default value for the
specified key
Args:
hive (str):
The name of the hive. Can be one of the following
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name.
vname (str):
The value name. These are the individual name/data pairs under the
key. If not passed, the key (Default) value will be set.
vdata (str, int, list, bytes):
The value you'd like to set. If a value name (vname) is passed, this
will be the data for that value name. If not, this will be the
(Default) value for the key.
The type of data this parameter expects is determined by the value
type specified in ``vtype``. The correspondence is as follows:
- REG_BINARY: Binary data (str in Py2, bytes in Py3)
- REG_DWORD: int
- REG_EXPAND_SZ: str
- REG_MULTI_SZ: list of str
- REG_QWORD: int
- REG_SZ: str
.. note::
When setting REG_BINARY, string data will be converted to
binary.
.. note::
The type for the (Default) value is always REG_SZ and cannot be
changed.
.. note::
This parameter is optional. If ``vdata`` is not passed, the Key
will be created with no associated item/value pairs.
vtype (str):
The value type. The possible values of the vtype parameter are
indicated above in the description of the vdata parameter.
use_32bit_registry (bool):
Sets the 32bit portion of the registry on 64bit installations. On
32bit machines this is ignored.
volatile (bool):
When this parameter has a value of True, the registry key will be
made volatile (i.e. it will not persist beyond a system reset or
shutdown). This parameter only has an effect when a key is being
created and at no other time.
Returns:
bool: True if successful, otherwise False
CLI Example:
This will set the version value to 2015.5.2 in the SOFTWARE\\Salt key in
the HKEY_LOCAL_MACHINE hive
.. code-block:: bash
salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'version' '2015.5.2'
CLI Example:
This function is strict about the type of vdata. For instance this
example will fail because vtype has a value of REG_SZ and vdata has a
type of int (as opposed to str as expected).
.. code-block:: bash
salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'str_data' 1.2
CLI Example:
In this next example vdata is properly quoted and should succeed.
.. code-block:: bash
salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'str_data' vtype=REG_SZ vdata="'1.2'"
CLI Example:
This is an example of using vtype REG_BINARY.
.. code-block:: bash
salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'bin_data' vtype=REG_BINARY vdata='Salty Data'
CLI Example:
An example of using vtype REG_MULTI_SZ is as follows:
.. code-block:: bash
salt '*' reg.set_value HKEY_LOCAL_MACHINE 'SOFTWARE\\Salt' 'list_data' vtype=REG_MULTI_SZ vdata='["Salt", "is", "great"]'
'''
return __utils__['reg.set_value'](hive=hive,
key=key,
vname=vname,
vdata=vdata,
vtype=vtype,
use_32bit_registry=use_32bit_registry,
volatile=volatile)
def delete_key_recursive(hive, key, use_32bit_registry=False):
r'''
.. versionadded:: 2015.5.4
Delete a registry key to include all subkeys and value/data pairs.
Args:
hive (str):
The name of the hive. Can be one of the following
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key to remove (looks like a path)
use_32bit_registry (bool):
Deletes the 32bit portion of the registry on 64bit
installations. On 32bit machines this is ignored.
Returns:
dict: A dictionary listing the keys that deleted successfully as well as
those that failed to delete.
CLI Example:
The following example will remove ``delete_me`` and all its subkeys from the
``SOFTWARE`` key in ``HKEY_LOCAL_MACHINE``:
.. code-block:: bash
salt '*' reg.delete_key_recursive HKLM SOFTWARE\\delete_me
'''
return __utils__['reg.delete_key_recursive'](hive=hive,
key=key,
use_32bit_registry=use_32bit_registry)
def delete_value(hive, key, vname=None, use_32bit_registry=False):
r'''
Delete a registry value entry or the default value for a key.
Args:
hive (str):
The name of the hive. Can be one of the following
- HKEY_LOCAL_MACHINE or HKLM
- HKEY_CURRENT_USER or HKCU
- HKEY_USER or HKU
- HKEY_CLASSES_ROOT or HKCR
- HKEY_CURRENT_CONFIG or HKCC
key (str):
The key (looks like a path) to the value name.
vname (str):
The value name. These are the individual name/data pairs under the
key. If not passed, the key (Default) value will be deleted.
use_32bit_registry (bool):
Deletes the 32bit portion of the registry on 64bit installations. On
32bit machines this is ignored.
Returns:
bool: True if successful, otherwise False
CLI Example:
.. code-block:: bash
salt '*' reg.delete_value HKEY_CURRENT_USER 'SOFTWARE\\Salt' 'version'
'''
return __utils__['reg.delete_value'](hive=hive,
key=key,
vname=vname,
use_32bit_registry=use_32bit_registry)
|
saltstack/salt
|
salt/pillar/ec2_pillar.py
|
ext_pillar
|
python
|
def ext_pillar(minion_id,
pillar, # pylint: disable=W0613
use_grain=False,
minion_ids=None,
tag_match_key=None,
tag_match_value='asis',
tag_list_key=None,
tag_list_sep=';'):
'''
Execute a command and read the output as YAML
'''
valid_tag_match_value = ['uqdn', 'asis']
# meta-data:instance-id
grain_instance_id = __grains__.get('meta-data', {}).get('instance-id', None)
if not grain_instance_id:
# dynamic:instance-identity:document:instanceId
grain_instance_id = \
__grains__.get('dynamic', {}).get('instance-identity', {}).get('document', {}).get('instance-id', None)
if grain_instance_id and re.search(r'^i-([0-9a-z]{17}|[0-9a-z]{8})$', grain_instance_id) is None:
log.error('External pillar %s, instance-id \'%s\' is not valid for '
'\'%s\'', __name__, grain_instance_id, minion_id)
grain_instance_id = None # invalid instance id found, remove it from use.
# Check AWS Tag restrictions .i.e. letters, spaces, and numbers and + - = . _ : / @
if tag_match_key and re.match(r'[\w=.:/@-]+$', tag_match_key) is None:
log.error('External pillar %s, tag_match_key \'%s\' is not valid ',
__name__, tag_match_key if isinstance(tag_match_key, six.text_type) else 'non-string')
return {}
if tag_match_key and tag_match_value not in valid_tag_match_value:
log.error('External pillar %s, tag_value \'%s\' is not valid must be one '
'of %s', __name__, tag_match_value, ' '.join(valid_tag_match_value))
return {}
if not tag_match_key:
base_msg = ('External pillar %s, querying EC2 tags for minion id \'%s\' '
'against instance-id', __name__, minion_id)
else:
base_msg = ('External pillar %s, querying EC2 tags for minion id \'%s\' '
'against instance-id or \'%s\' against \'%s\'', __name__, minion_id, tag_match_key, tag_match_value)
log.debug(base_msg)
find_filter = None
find_id = None
if re.search(r'^i-([0-9a-z]{17}|[0-9a-z]{8})$', minion_id) is not None:
find_filter = None
find_id = minion_id
elif tag_match_key:
if tag_match_value == 'uqdn':
find_filter = {'tag:{0}'.format(tag_match_key): minion_id.split('.', 1)[0]}
else:
find_filter = {'tag:{0}'.format(tag_match_key): minion_id}
if grain_instance_id:
# we have an untrusted grain_instance_id, use it to narrow the search
# even more. Combination will be unique even if uqdn is set.
find_filter.update({'instance-id': grain_instance_id})
# Add this if running state is not dependant on EC2Config
# find_filter.update('instance-state-name': 'running')
# no minion-id is instance-id and no suitable filter, try use_grain if enabled
if not find_filter and not find_id and use_grain:
if not grain_instance_id:
log.debug('Minion-id is not in AWS instance-id formation, and there '
'is no instance-id grain for minion %s', minion_id)
return {}
if minion_ids is not None and minion_id not in minion_ids:
log.debug('Minion-id is not in AWS instance ID format, and minion_ids '
'is set in the ec2_pillar configuration, but minion %s is '
'not in the list of allowed minions %s', minion_id, minion_ids)
return {}
find_id = grain_instance_id
if not (find_filter or find_id):
log.debug('External pillar %s, querying EC2 tags for minion id \'%s\' against '
'instance-id or \'%s\' against \'%s\' noughthing to match against',
__name__, minion_id, tag_match_key, tag_match_value)
return {}
myself = boto.utils.get_instance_metadata(timeout=0.1, num_retries=1)
if not myself:
log.info("%s: salt master not an EC2 instance, skipping", __name__)
return {}
# Get the Master's instance info, primarily the region
(_, region) = _get_instance_info()
# If the Minion's region is available, use it instead
if use_grain:
region = __grains__.get('ec2', {}).get('region', region)
try:
conn = boto.ec2.connect_to_region(region)
except boto.exception.AWSConnectionError as exc:
log.error('%s: invalid AWS credentials, %s', __name__, exc)
return {}
if conn is None:
log.error('%s: Could not connect to region %s', __name__, region)
return {}
try:
if find_id:
instance_data = conn.get_only_instances(instance_ids=[find_id], dry_run=False)
else:
# filters and max_results can not be used togther.
instance_data = conn.get_only_instances(filters=find_filter, dry_run=False)
except boto.exception.EC2ResponseError as exc:
log.error('%s failed with \'%s\'', base_msg, exc)
return {}
if not instance_data:
log.debug('%s no match using \'%s\'', base_msg, find_id if find_id else find_filter)
return {}
# Find a active instance, i.e. ignore terminated and stopped instances
active_inst = []
for inst in range(0, len(instance_data)):
if instance_data[inst].state not in ['terminated', 'stopped']:
active_inst.append(inst)
valid_inst = len(active_inst)
if not valid_inst:
log.debug('%s match found but not active \'%s\'', base_msg, find_id if find_id else find_filter)
return {}
if valid_inst > 1:
log.error('%s multiple matches, ignored, using \'%s\'', base_msg, find_id if find_id else find_filter)
return {}
instance = instance_data[active_inst[0]]
if instance.tags:
ec2_tags = instance.tags
ec2_tags_list = {}
log.debug('External pillar %s, for minion id \'%s\', tags: %s', __name__, minion_id, instance.tags)
if tag_list_key and isinstance(tag_list_key, list):
for item in tag_list_key:
if item in ec2_tags:
ec2_tags_list[item] = ec2_tags[item].split(tag_list_sep)
del ec2_tags[item] # make sure its only in ec2_tags_list
else:
ec2_tags_list[item] = [] # always return a result
return {'ec2_tags': ec2_tags, 'ec2_tags_list': ec2_tags_list}
return {}
|
Execute a command and read the output as YAML
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/ec2_pillar.py#L108-L254
|
[
"def _get_instance_info():\n '''\n Helper function to return the instance ID and region of the master where\n this pillar is run.\n '''\n identity = boto.utils.get_instance_identity()['document']\n return (identity['instanceId'], identity['region'])\n"
] |
# -*- coding: utf-8 -*-
'''
Retrieve EC2 instance data for minions for ec2_tags and ec2_tags_list
The minion id must be the AWS instance-id or value in ``tag_match_key``. For
example set ``tag_match_key`` to ``Name`` to have the minion-id matched against
the tag 'Name'. The tag contents must be unique. The value of
``tag_match_value`` can be 'uqdn' or 'asis'. if 'uqdn', then the domain will be
stripped before comparison.
Additionally, the ``use_grain`` option can be set to ``True``. This allows the
use of an instance-id grain instead of the minion-id. Since this is a potential
security risk, the configuration can be further expanded to include a list of
minions that are trusted to only allow the alternate id of the instances to
specific hosts. There is no glob matching at this time.
.. note::
If you are using ``use_grain: True`` in the configuration for this external
pillar module, the minion must have :conf_minion:`metadata_server_grains`
enabled in the minion config file (see also :py:mod:`here
<salt.grains.metadata>`).
It is important to also note that enabling the ``use_grain`` option allows
the minion to manipulate the pillar data returned, as described above.
The optional ``tag_list_key`` indicates which keys should be added to
``ec2_tags_list`` and be split by ``tag_list_sep`` (by default ``;``). If a tag
key is included in ``tag_list_key`` it is removed from ec2_tags. If a tag does
not exist it is still included as an empty list.
..note::
As with any master configuration change, restart the salt-master daemon for
changes to take effect.
.. code-block:: yaml
ext_pillar:
- ec2_pillar:
tag_match_key: 'Name'
tag_match_value: 'asis'
tag_list_key:
- Role
tag_list_sep: ';'
use_grain: True
minion_ids:
- trusted-minion-1
- trusted-minion-2
- trusted-minion-3
This is a very simple pillar configuration that simply retrieves the instance
data from AWS. Currently the only portion implemented are EC2 tags, which
returns a list of key/value pairs for all of the EC2 tags assigned to the
instance.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import re
import logging
import salt.ext.six as six
from salt.ext.six.moves import range
# Import salt libs
from salt.utils.versions import StrictVersion as _StrictVersion
# Import AWS Boto libs
try:
import boto.ec2
import boto.utils
import boto.exception
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# Set up logging
log = logging.getLogger(__name__)
# DEBUG boto is far too verbose
logging.getLogger('boto').setLevel(logging.WARNING)
def __virtual__():
'''
Check for required version of boto and make this pillar available
depending on outcome.
'''
if not HAS_BOTO:
return False
boto_version = _StrictVersion(boto.__version__)
required_boto_version = _StrictVersion('2.8.0')
if boto_version < required_boto_version:
log.error("%s: installed boto version %s < %s, can't retrieve instance data",
__name__, boto_version, required_boto_version)
return False
return True
def _get_instance_info():
'''
Helper function to return the instance ID and region of the master where
this pillar is run.
'''
identity = boto.utils.get_instance_identity()['document']
return (identity['instanceId'], identity['region'])
|
saltstack/salt
|
salt/pillar/venafi.py
|
ext_pillar
|
python
|
def ext_pillar(minion_id, pillar, conf):
'''
Return an existing set of certificates
'''
cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
ret = {}
dns_names = cache.fetch('venafi/minions', minion_id)
for dns_name in dns_names:
data = cache.fetch('venafi/domains', dns_name)
ret[dns_name] = data
del ret[dns_name]['csr']
return {'venafi': ret}
|
Return an existing set of certificates
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/pillar/venafi.py#L32-L44
|
[
"def fetch(self, bank, key):\n '''\n Fetch data using the specified module\n\n :param bank:\n The name of the location inside the cache which will hold the key\n and its associated data.\n\n :param key:\n The name of the key (or file inside a directory) which will hold\n the data. File extensions should not be provided, as they will be\n added by the driver itself.\n\n :return:\n Return a python object fetched from the cache or an empty dict if\n the given path or key not found.\n\n :raises SaltCacheError:\n Raises an exception if cache driver detected an error accessing data\n in the cache backend (auth, permissions, etc).\n '''\n fun = '{0}.fetch'.format(self.driver)\n return self.modules[fun](bank, key, **self._kwargs)\n"
] |
# -*- coding: utf-8 -*-
'''
Venafi Pillar Certificates
This module will only return pillar data if the ``venafi`` runner module has
already been used to create certificates.
To configure this module, set ``venafi`` to ``True`` in the ``ext_pillar``
section of your ``master`` configuration file:
.. code-block:: yaml
ext_pillar:
- venafi: True
'''
from __future__ import absolute_import, print_function, unicode_literals
import logging
import salt.cache
import salt.syspaths as syspaths
__virtualname__ = 'venafi'
log = logging.getLogger(__name__)
def __virtual__():
'''
No special requirements outside of Salt itself
'''
return __virtualname__
|
saltstack/salt
|
salt/modules/s6.py
|
status
|
python
|
def status(name, sig=None):
'''
Return the status for a service via s6, return pid if running
CLI Example:
.. code-block:: bash
salt '*' s6.status <service name>
'''
cmd = 's6-svstat {0}'.format(_service_path(name))
out = __salt__['cmd.run_stdout'](cmd)
try:
pid = re.search(r'up \(pid (\d+)\)', out).group(1)
except AttributeError:
pid = ''
return pid
|
Return the status for a service via s6, return pid if running
CLI Example:
.. code-block:: bash
salt '*' s6.status <service name>
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/s6.py#L135-L151
|
[
"def _service_path(name):\n '''\n build service path\n '''\n if not SERVICE_DIR:\n raise CommandExecutionError(\"Could not find service directory.\")\n return '{0}/{1}'.format(SERVICE_DIR, name)\n"
] |
# -*- coding: utf-8 -*-
'''
s6 service module
This module is compatible with the :mod:`service <salt.states.service>` states,
so it can be used to maintain services using the ``provider`` argument:
.. code-block:: yaml
myservice:
service:
- running
- provider: s6
Note that the ``enabled`` argument is not available with this provider.
:codeauthor: Marek Skrobacki <skrobul@skrobul.com>
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
# Import salt libs
from salt.exceptions import CommandExecutionError
__func_alias__ = {
'reload_': 'reload'
}
VALID_SERVICE_DIRS = [
'/service',
'/etc/service',
]
SERVICE_DIR = None
for service_dir in VALID_SERVICE_DIRS:
if os.path.exists(service_dir):
SERVICE_DIR = service_dir
break
def _service_path(name):
'''
build service path
'''
if not SERVICE_DIR:
raise CommandExecutionError("Could not find service directory.")
return '{0}/{1}'.format(SERVICE_DIR, name)
def start(name):
'''
Starts service via s6
CLI Example:
.. code-block:: bash
salt '*' s6.start <service name>
'''
cmd = 's6-svc -u {0}'.format(_service_path(name))
return not __salt__['cmd.retcode'](cmd)
def stop(name):
'''
Stops service via s6
CLI Example:
.. code-block:: bash
salt '*' s6.stop <service name>
'''
cmd = 's6-svc -d {0}'.format(_service_path(name))
return not __salt__['cmd.retcode'](cmd)
def term(name):
'''
Send a TERM to service via s6
CLI Example:
.. code-block:: bash
salt '*' s6.term <service name>
'''
cmd = 's6-svc -t {0}'.format(_service_path(name))
return not __salt__['cmd.retcode'](cmd)
def reload_(name):
'''
Send a HUP to service via s6
CLI Example:
.. code-block:: bash
salt '*' s6.reload <service name>
'''
cmd = 's6-svc -h {0}'.format(_service_path(name))
return not __salt__['cmd.retcode'](cmd)
def restart(name):
'''
Restart service via s6. This will stop/start service
CLI Example:
.. code-block:: bash
salt '*' s6.restart <service name>
'''
cmd = 's6-svc -t {0}'.format(_service_path(name))
return not __salt__['cmd.retcode'](cmd)
def full_restart(name):
'''
Calls s6.restart() function
CLI Example:
.. code-block:: bash
salt '*' s6.full_restart <service name>
'''
restart(name)
def available(name):
'''
Returns ``True`` if the specified service is available, otherwise returns
``False``.
CLI Example:
.. code-block:: bash
salt '*' s6.available foo
'''
return name in get_all()
def missing(name):
'''
The inverse of s6.available.
Returns ``True`` if the specified service is not available, otherwise returns
``False``.
CLI Example:
.. code-block:: bash
salt '*' s6.missing foo
'''
return name not in get_all()
def get_all():
'''
Return a list of all available services
CLI Example:
.. code-block:: bash
salt '*' s6.get_all
'''
if not SERVICE_DIR:
raise CommandExecutionError("Could not find service directory.")
service_list = [dirname for dirname
in os.listdir(SERVICE_DIR)
if not dirname.startswith('.')]
return sorted(service_list)
|
saltstack/salt
|
salt/modules/s6.py
|
get_all
|
python
|
def get_all():
'''
Return a list of all available services
CLI Example:
.. code-block:: bash
salt '*' s6.get_all
'''
if not SERVICE_DIR:
raise CommandExecutionError("Could not find service directory.")
service_list = [dirname for dirname
in os.listdir(SERVICE_DIR)
if not dirname.startswith('.')]
return sorted(service_list)
|
Return a list of all available services
CLI Example:
.. code-block:: bash
salt '*' s6.get_all
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/s6.py#L183-L198
| null |
# -*- coding: utf-8 -*-
'''
s6 service module
This module is compatible with the :mod:`service <salt.states.service>` states,
so it can be used to maintain services using the ``provider`` argument:
.. code-block:: yaml
myservice:
service:
- running
- provider: s6
Note that the ``enabled`` argument is not available with this provider.
:codeauthor: Marek Skrobacki <skrobul@skrobul.com>
'''
from __future__ import absolute_import, unicode_literals, print_function
# Import python libs
import os
import re
# Import salt libs
from salt.exceptions import CommandExecutionError
__func_alias__ = {
'reload_': 'reload'
}
VALID_SERVICE_DIRS = [
'/service',
'/etc/service',
]
SERVICE_DIR = None
for service_dir in VALID_SERVICE_DIRS:
if os.path.exists(service_dir):
SERVICE_DIR = service_dir
break
def _service_path(name):
'''
build service path
'''
if not SERVICE_DIR:
raise CommandExecutionError("Could not find service directory.")
return '{0}/{1}'.format(SERVICE_DIR, name)
def start(name):
'''
Starts service via s6
CLI Example:
.. code-block:: bash
salt '*' s6.start <service name>
'''
cmd = 's6-svc -u {0}'.format(_service_path(name))
return not __salt__['cmd.retcode'](cmd)
def stop(name):
'''
Stops service via s6
CLI Example:
.. code-block:: bash
salt '*' s6.stop <service name>
'''
cmd = 's6-svc -d {0}'.format(_service_path(name))
return not __salt__['cmd.retcode'](cmd)
def term(name):
'''
Send a TERM to service via s6
CLI Example:
.. code-block:: bash
salt '*' s6.term <service name>
'''
cmd = 's6-svc -t {0}'.format(_service_path(name))
return not __salt__['cmd.retcode'](cmd)
def reload_(name):
'''
Send a HUP to service via s6
CLI Example:
.. code-block:: bash
salt '*' s6.reload <service name>
'''
cmd = 's6-svc -h {0}'.format(_service_path(name))
return not __salt__['cmd.retcode'](cmd)
def restart(name):
'''
Restart service via s6. This will stop/start service
CLI Example:
.. code-block:: bash
salt '*' s6.restart <service name>
'''
cmd = 's6-svc -t {0}'.format(_service_path(name))
return not __salt__['cmd.retcode'](cmd)
def full_restart(name):
'''
Calls s6.restart() function
CLI Example:
.. code-block:: bash
salt '*' s6.full_restart <service name>
'''
restart(name)
def status(name, sig=None):
'''
Return the status for a service via s6, return pid if running
CLI Example:
.. code-block:: bash
salt '*' s6.status <service name>
'''
cmd = 's6-svstat {0}'.format(_service_path(name))
out = __salt__['cmd.run_stdout'](cmd)
try:
pid = re.search(r'up \(pid (\d+)\)', out).group(1)
except AttributeError:
pid = ''
return pid
def available(name):
'''
Returns ``True`` if the specified service is available, otherwise returns
``False``.
CLI Example:
.. code-block:: bash
salt '*' s6.available foo
'''
return name in get_all()
def missing(name):
'''
The inverse of s6.available.
Returns ``True`` if the specified service is not available, otherwise returns
``False``.
CLI Example:
.. code-block:: bash
salt '*' s6.missing foo
'''
return name not in get_all()
|
saltstack/salt
|
salt/modules/omapi.py
|
add_host
|
python
|
def add_host(mac, name=None, ip=None, ddns=False, group=None,
supersede_host=False):
'''
Add a host object for the given mac.
CLI Example:
.. code-block:: bash
salt dhcp-server omapi.add_host ab:ab:ab:ab:ab:ab name=host1
Add ddns-hostname and a fixed-ip statements:
.. code-block:: bash
salt dhcp-server omapi.add_host ab:ab:ab:ab:ab:ab name=host1 ip=10.1.1.1 ddns=true
'''
statements = ''
o = _conn()
msg = omapi.OmapiMessage.open(b'host')
msg.message.append((b'create', struct.pack(b'!I', 1)))
msg.message.append((b'exclusive', struct.pack(b'!I', 1)))
msg.obj.append((b'hardware-address', omapi.pack_mac(mac)))
msg.obj.append((b'hardware-type', struct.pack(b'!I', 1)))
if ip:
msg.obj.append((b'ip-address', omapi.pack_ip(ip)))
if name:
msg.obj.append((b'name', salt.utils.stringutils.to_bytes(name)))
if group:
msg.obj.append((b'group', salt.utils.stringutils.to_bytes(group)))
if supersede_host:
statements += 'option host-name "{0}"; '.format(name)
if ddns and name:
statements += 'ddns-hostname "{0}"; '.format(name)
if statements:
msg.obj.append((b'statements', salt.utils.stringutils.to_bytes(statements)))
response = o.query_server(msg)
if response.opcode != omapi.OMAPI_OP_UPDATE:
return False
return True
|
Add a host object for the given mac.
CLI Example:
.. code-block:: bash
salt dhcp-server omapi.add_host ab:ab:ab:ab:ab:ab name=host1
Add ddns-hostname and a fixed-ip statements:
.. code-block:: bash
salt dhcp-server omapi.add_host ab:ab:ab:ab:ab:ab name=host1 ip=10.1.1.1 ddns=true
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/omapi.py#L60-L99
|
[
"def _conn():\n server_ip = __pillar__.get('omapi.server_ip',\n __opts__.get('omapi.server_ip', '127.0.0.1'))\n server_port = __pillar__.get('omapi.server_port',\n __opts__.get('omapi.server_port', 7991))\n key = __pillar__.get('omapi.key',\n __opts__.get('omapi.key', None))\n username = __pillar__.get('omapi.user',\n __opts__.get('omapi.user', None))\n if key:\n key = salt.utils.stringutils.to_bytes(key)\n if username:\n username = salt.utils.stringutils.to_bytes(username)\n return omapi.Omapi(server_ip, server_port, username=username, key=key)\n"
] |
# -*- coding: utf-8 -*-
'''
This module interacts with an ISC DHCP Server via OMAPI.
server_ip and server_port params may be set in the minion
config or pillar:
.. code-block:: yaml
omapi.server_ip: 127.0.0.1
omapi.server_port: 7991
:depends: pypureomapi Python module
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import struct
# Import salt libs
import salt.utils.stringutils
log = logging.getLogger(__name__)
try:
import pypureomapi as omapi
omapi_support = True
except ImportError as e:
omapi_support = False
def __virtual__():
'''
Confirm pypureomapi is available.
'''
if omapi_support:
return 'omapi'
return (False, 'The omapi execution module cannot be loaded: '
'the pypureomapi python library is not available.')
def _conn():
server_ip = __pillar__.get('omapi.server_ip',
__opts__.get('omapi.server_ip', '127.0.0.1'))
server_port = __pillar__.get('omapi.server_port',
__opts__.get('omapi.server_port', 7991))
key = __pillar__.get('omapi.key',
__opts__.get('omapi.key', None))
username = __pillar__.get('omapi.user',
__opts__.get('omapi.user', None))
if key:
key = salt.utils.stringutils.to_bytes(key)
if username:
username = salt.utils.stringutils.to_bytes(username)
return omapi.Omapi(server_ip, server_port, username=username, key=key)
def delete_host(mac=None, name=None):
'''
Delete the host with the given mac or name.
CLI Examples:
.. code-block:: bash
salt dhcp-server omapi.delete_host name=host1
salt dhcp-server omapi.delete_host mac=ab:ab:ab:ab:ab:ab
'''
if not (mac or name):
raise TypeError('At least one argument is required')
o = _conn()
msg = omapi.OmapiMessage.open(b'host')
if mac:
msg.obj.append((b'hardware-address', omapi.pack_mac(mac)))
msg.obj.append((b'hardware-type', struct.pack(b'!I', 1)))
if name:
msg.obj.append((b'name', salt.utils.stringutils.to_bytes(name)))
response = o.query_server(msg)
if response.opcode != omapi.OMAPI_OP_UPDATE:
return None
if response.handle == 0:
return False
response = o.query_server(omapi.OmapiMessage.delete(response.handle))
if response.opcode != omapi.OMAPI_OP_STATUS:
return False
return True
|
saltstack/salt
|
salt/modules/omapi.py
|
delete_host
|
python
|
def delete_host(mac=None, name=None):
'''
Delete the host with the given mac or name.
CLI Examples:
.. code-block:: bash
salt dhcp-server omapi.delete_host name=host1
salt dhcp-server omapi.delete_host mac=ab:ab:ab:ab:ab:ab
'''
if not (mac or name):
raise TypeError('At least one argument is required')
o = _conn()
msg = omapi.OmapiMessage.open(b'host')
if mac:
msg.obj.append((b'hardware-address', omapi.pack_mac(mac)))
msg.obj.append((b'hardware-type', struct.pack(b'!I', 1)))
if name:
msg.obj.append((b'name', salt.utils.stringutils.to_bytes(name)))
response = o.query_server(msg)
if response.opcode != omapi.OMAPI_OP_UPDATE:
return None
if response.handle == 0:
return False
response = o.query_server(omapi.OmapiMessage.delete(response.handle))
if response.opcode != omapi.OMAPI_OP_STATUS:
return False
return True
|
Delete the host with the given mac or name.
CLI Examples:
.. code-block:: bash
salt dhcp-server omapi.delete_host name=host1
salt dhcp-server omapi.delete_host mac=ab:ab:ab:ab:ab:ab
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/omapi.py#L102-L130
|
[
"def _conn():\n server_ip = __pillar__.get('omapi.server_ip',\n __opts__.get('omapi.server_ip', '127.0.0.1'))\n server_port = __pillar__.get('omapi.server_port',\n __opts__.get('omapi.server_port', 7991))\n key = __pillar__.get('omapi.key',\n __opts__.get('omapi.key', None))\n username = __pillar__.get('omapi.user',\n __opts__.get('omapi.user', None))\n if key:\n key = salt.utils.stringutils.to_bytes(key)\n if username:\n username = salt.utils.stringutils.to_bytes(username)\n return omapi.Omapi(server_ip, server_port, username=username, key=key)\n"
] |
# -*- coding: utf-8 -*-
'''
This module interacts with an ISC DHCP Server via OMAPI.
server_ip and server_port params may be set in the minion
config or pillar:
.. code-block:: yaml
omapi.server_ip: 127.0.0.1
omapi.server_port: 7991
:depends: pypureomapi Python module
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import struct
# Import salt libs
import salt.utils.stringutils
log = logging.getLogger(__name__)
try:
import pypureomapi as omapi
omapi_support = True
except ImportError as e:
omapi_support = False
def __virtual__():
'''
Confirm pypureomapi is available.
'''
if omapi_support:
return 'omapi'
return (False, 'The omapi execution module cannot be loaded: '
'the pypureomapi python library is not available.')
def _conn():
server_ip = __pillar__.get('omapi.server_ip',
__opts__.get('omapi.server_ip', '127.0.0.1'))
server_port = __pillar__.get('omapi.server_port',
__opts__.get('omapi.server_port', 7991))
key = __pillar__.get('omapi.key',
__opts__.get('omapi.key', None))
username = __pillar__.get('omapi.user',
__opts__.get('omapi.user', None))
if key:
key = salt.utils.stringutils.to_bytes(key)
if username:
username = salt.utils.stringutils.to_bytes(username)
return omapi.Omapi(server_ip, server_port, username=username, key=key)
def add_host(mac, name=None, ip=None, ddns=False, group=None,
supersede_host=False):
'''
Add a host object for the given mac.
CLI Example:
.. code-block:: bash
salt dhcp-server omapi.add_host ab:ab:ab:ab:ab:ab name=host1
Add ddns-hostname and a fixed-ip statements:
.. code-block:: bash
salt dhcp-server omapi.add_host ab:ab:ab:ab:ab:ab name=host1 ip=10.1.1.1 ddns=true
'''
statements = ''
o = _conn()
msg = omapi.OmapiMessage.open(b'host')
msg.message.append((b'create', struct.pack(b'!I', 1)))
msg.message.append((b'exclusive', struct.pack(b'!I', 1)))
msg.obj.append((b'hardware-address', omapi.pack_mac(mac)))
msg.obj.append((b'hardware-type', struct.pack(b'!I', 1)))
if ip:
msg.obj.append((b'ip-address', omapi.pack_ip(ip)))
if name:
msg.obj.append((b'name', salt.utils.stringutils.to_bytes(name)))
if group:
msg.obj.append((b'group', salt.utils.stringutils.to_bytes(group)))
if supersede_host:
statements += 'option host-name "{0}"; '.format(name)
if ddns and name:
statements += 'ddns-hostname "{0}"; '.format(name)
if statements:
msg.obj.append((b'statements', salt.utils.stringutils.to_bytes(statements)))
response = o.query_server(msg)
if response.opcode != omapi.OMAPI_OP_UPDATE:
return False
return True
|
saltstack/salt
|
salt/modules/mine.py
|
_auth
|
python
|
def _auth():
'''
Return the auth object
'''
if 'auth' not in __context__:
try:
__context__['auth'] = salt.crypt.SAuth(__opts__)
except SaltClientError:
log.error('Could not authenticate with master.'
'Mine data will not be transmitted.')
return __context__['auth']
|
Return the auth object
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mine.py#L40-L50
| null |
# -*- coding: utf-8 -*-
'''
The function cache system allows for data to be stored on the master so it can be easily read by other minions
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import time
import traceback
# Import salt libs
import salt.crypt
import salt.payload
import salt.utils.args
import salt.utils.event
import salt.utils.network
import salt.transport.client
from salt.exceptions import SaltClientError
# Import 3rd-party libs
from salt.ext import six
MINE_INTERNAL_KEYWORDS = frozenset([
'__pub_user',
'__pub_arg',
'__pub_fun',
'__pub_jid',
'__pub_tgt',
'__pub_tgt_type',
'__pub_ret'
])
__proxyenabled__ = ['*']
log = logging.getLogger(__name__)
def _mine_function_available(func):
if func not in __salt__:
log.error('Function %s in mine_functions not available', func)
return False
return True
def _mine_send(load, opts):
eventer = salt.utils.event.MinionEvent(opts, listen=False)
event_ret = eventer.fire_event(load, '_minion_mine')
# We need to pause here to allow for the decoupled nature of
# events time to allow the mine to propagate
time.sleep(0.5)
return event_ret
def _mine_get(load, opts):
if opts.get('transport', '') in ('zeromq', 'tcp'):
try:
load['tok'] = _auth().gen_token(b'salt')
except AttributeError:
log.error('Mine could not authenticate with master. '
'Mine could not be retrieved.'
)
return False
channel = salt.transport.client.ReqChannel.factory(opts)
try:
ret = channel.send(load)
finally:
channel.close()
return ret
def update(clear=False, mine_functions=None):
'''
Execute the configured functions and send the data back up to the master.
The functions to be executed are merged from the master config, pillar and
minion config under the option `mine_functions`:
.. code-block:: yaml
mine_functions:
network.ip_addrs:
- eth0
disk.usage: []
This function accepts the following arguments:
clear: False
Boolean flag specifying whether updating will clear the existing
mines, or will update. Default: `False` (update).
mine_functions
Update the mine data on certain functions only.
This feature can be used when updating the mine for functions
that require refresh at different intervals than the rest of
the functions specified under `mine_functions` in the
minion/master config or pillar.
A potential use would be together with the `scheduler`, for example:
.. code-block:: yaml
schedule:
lldp_mine_update:
function: mine.update
kwargs:
mine_functions:
net.lldp: []
hours: 12
In the example above, the mine for `net.lldp` would be refreshed
every 12 hours, while `network.ip_addrs` would continue to be updated
as specified in `mine_interval`.
The function cache will be populated with information from executing these
functions
CLI Example:
.. code-block:: bash
salt '*' mine.update
'''
m_data = {}
if not mine_functions:
m_data = __salt__['config.merge']('mine_functions', {})
# If we don't have any mine functions configured, then we should just bail out
if not m_data:
return
elif mine_functions and isinstance(mine_functions, list):
m_data = dict((fun, {}) for fun in mine_functions)
elif mine_functions and isinstance(mine_functions, dict):
m_data = mine_functions
else:
return
data = {}
for func in m_data:
try:
if m_data[func] and isinstance(m_data[func], dict):
mine_func = m_data[func].pop('mine_function', func)
if not _mine_function_available(mine_func):
continue
data[func] = __salt__[mine_func](**m_data[func])
elif m_data[func] and isinstance(m_data[func], list):
mine_func = func
if isinstance(m_data[func][0], dict) and 'mine_function' in m_data[func][0]:
mine_func = m_data[func][0]['mine_function']
m_data[func].pop(0)
if not _mine_function_available(mine_func):
continue
data[func] = __salt__[mine_func](*m_data[func])
else:
if not _mine_function_available(func):
continue
data[func] = __salt__[func]()
except Exception:
trace = traceback.format_exc()
log.error('Function %s in mine_functions failed to execute', func)
log.debug('Error: %s', trace)
continue
if __opts__['file_client'] == 'local':
if not clear:
old = __salt__['data.get']('mine_cache')
if isinstance(old, dict):
old.update(data)
data = old
return __salt__['data.update']('mine_cache', data)
load = {
'cmd': '_mine',
'data': data,
'id': __opts__['id'],
'clear': clear,
}
return _mine_send(load, __opts__)
def send(func, *args, **kwargs):
'''
Send a specific function to the mine.
CLI Example:
.. code-block:: bash
salt '*' mine.send network.ip_addrs eth0
salt '*' mine.send eth0_ip_addrs mine_function=network.ip_addrs eth0
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
mine_func = kwargs.pop('mine_function', func)
if mine_func not in __salt__:
return False
data = {}
arg_data = salt.utils.args.arg_lookup(__salt__[mine_func])
func_data = copy.deepcopy(kwargs)
for ind, _ in enumerate(arg_data.get('args', [])):
try:
func_data[arg_data['args'][ind]] = args[ind]
except IndexError:
# Safe error, arg may be in kwargs
pass
f_call = salt.utils.args.format_call(
__salt__[mine_func],
func_data,
expected_extra_kws=MINE_INTERNAL_KEYWORDS)
for arg in args:
if arg not in f_call['args']:
f_call['args'].append(arg)
try:
if 'kwargs' in f_call:
data[func] = __salt__[mine_func](*f_call['args'], **f_call['kwargs'])
else:
data[func] = __salt__[mine_func](*f_call['args'])
except Exception as exc:
log.error('Function %s in mine.send failed to execute: %s',
mine_func, exc)
return False
if __opts__['file_client'] == 'local':
old = __salt__['data.get']('mine_cache')
if isinstance(old, dict):
old.update(data)
data = old
return __salt__['data.update']('mine_cache', data)
load = {
'cmd': '_mine',
'data': data,
'id': __opts__['id'],
}
return _mine_send(load, __opts__)
def get(tgt,
fun,
tgt_type='glob',
exclude_minion=False):
'''
Get data from the mine based on the target, function and tgt_type
Targets can be matched based on any standard matching system that can be
matched on the master via these keywords:
- glob
- pcre
- grain
- grain_pcre
- compound
- pillar
- pillar_pcre
Note that all pillar matches, whether using the compound matching system or
the pillar matching system, will be exact matches, with globbing disabled.
exclude_minion
Excludes the current minion from the result set
CLI Example:
.. code-block:: bash
salt '*' mine.get '*' network.interfaces
salt '*' mine.get '*' network.interfaces,network.ipaddrs
salt '*' mine.get '*' '["network.interfaces", "network.ipaddrs"]'
salt '*' mine.get 'os:Fedora' network.interfaces grain
salt '*' mine.get 'G@os:Fedora and S@192.168.5.0/24' network.ipaddrs compound
.. seealso:: Retrieving Mine data from Pillar and Orchestrate
This execution module is intended to be executed on minions.
Master-side operations such as Pillar or Orchestrate that require Mine
data should use the :py:mod:`Mine Runner module <salt.runners.mine>`
instead; it can be invoked from a Pillar SLS file using the
:py:func:`saltutil.runner <salt.modules.saltutil.runner>` module. For
example:
.. code-block:: jinja
{% set minion_ips = salt.saltutil.runner('mine.get',
tgt='*',
fun='network.ip_addrs',
tgt_type='glob') %}
'''
if __opts__['file_client'] == 'local':
ret = {}
is_target = {'glob': __salt__['match.glob'],
'pcre': __salt__['match.pcre'],
'list': __salt__['match.list'],
'grain': __salt__['match.grain'],
'grain_pcre': __salt__['match.grain_pcre'],
'ipcidr': __salt__['match.ipcidr'],
'compound': __salt__['match.compound'],
'pillar': __salt__['match.pillar'],
'pillar_pcre': __salt__['match.pillar_pcre'],
}[tgt_type](tgt)
if is_target:
data = __salt__['data.get']('mine_cache')
if isinstance(data, dict):
if isinstance(fun, six.string_types):
functions = list(set(fun.split(',')))
_ret_dict = len(functions) > 1
elif isinstance(fun, list):
functions = fun
_ret_dict = True
else:
return {}
if not _ret_dict and functions and functions[0] in data:
ret[__opts__['id']] = data.get(functions)
elif _ret_dict:
for fun in functions:
if fun in data:
ret.setdefault(fun, {})[__opts__['id']] = data.get(fun)
return ret
load = {
'cmd': '_mine_get',
'id': __opts__['id'],
'tgt': tgt,
'fun': fun,
'tgt_type': tgt_type,
}
ret = _mine_get(load, __opts__)
if exclude_minion:
if __opts__['id'] in ret:
del ret[__opts__['id']]
return ret
def delete(fun):
'''
Remove specific function contents of minion. Returns True on success.
CLI Example:
.. code-block:: bash
salt '*' mine.delete 'network.interfaces'
'''
if __opts__['file_client'] == 'local':
data = __salt__['data.get']('mine_cache')
if isinstance(data, dict) and fun in data:
del data[fun]
return __salt__['data.update']('mine_cache', data)
load = {
'cmd': '_mine_delete',
'id': __opts__['id'],
'fun': fun,
}
return _mine_send(load, __opts__)
def flush():
'''
Remove all mine contents of minion. Returns True on success.
CLI Example:
.. code-block:: bash
salt '*' mine.flush
'''
if __opts__['file_client'] == 'local':
return __salt__['data.update']('mine_cache', {})
load = {
'cmd': '_mine_flush',
'id': __opts__['id'],
}
return _mine_send(load, __opts__)
def get_docker(interfaces=None, cidrs=None, with_container_id=False):
'''
.. versionchanged:: 2017.7.8,2018.3.3
When :conf_minion:`docker.update_mine` is set to ``False`` for a given
minion, no mine data will be populated for that minion, and thus none
will be returned for it.
.. versionchanged:: 2019.2.0
:conf_minion:`docker.update_mine` now defaults to ``False``
Get all mine data for :py:func:`docker.ps <salt.modules.dockermod.ps_>` and
run an aggregation routine. The ``interfaces`` parameter allows for
specifying the network interfaces from which to select IP addresses. The
``cidrs`` parameter allows for specifying a list of subnets which the IP
address must match.
with_container_id
Boolean, to expose container_id in the list of results
.. versionadded:: 2015.8.2
CLI Example:
.. code-block:: bash
salt '*' mine.get_docker
salt '*' mine.get_docker interfaces='eth0'
salt '*' mine.get_docker interfaces='["eth0", "eth1"]'
salt '*' mine.get_docker cidrs='107.170.147.0/24'
salt '*' mine.get_docker cidrs='["107.170.147.0/24", "172.17.42.0/24"]'
salt '*' mine.get_docker interfaces='["eth0", "eth1"]' cidrs='["107.170.147.0/24", "172.17.42.0/24"]'
'''
# Enforce that interface and cidr are lists
if interfaces:
interface_ = []
interface_.extend(interfaces if isinstance(interfaces, list) else [interfaces])
interfaces = interface_
if cidrs:
cidr_ = []
cidr_.extend(cidrs if isinstance(cidrs, list) else [cidrs])
cidrs = cidr_
# Get docker info
cmd = 'docker.ps'
docker_hosts = get('*', cmd)
proxy_lists = {}
# Process docker info
for containers in six.itervalues(docker_hosts):
host = containers.pop('host')
host_ips = []
# Prepare host_ips list
if not interfaces:
for info in six.itervalues(host['interfaces']):
if 'inet' in info:
for ip_ in info['inet']:
host_ips.append(ip_['address'])
else:
for interface in interfaces:
if interface in host['interfaces']:
if 'inet' in host['interfaces'][interface]:
for item in host['interfaces'][interface]['inet']:
host_ips.append(item['address'])
host_ips = list(set(host_ips))
# Filter out ips from host_ips with cidrs
if cidrs:
good_ips = []
for cidr in cidrs:
for ip_ in host_ips:
if salt.utils.network.in_subnet(cidr, [ip_]):
good_ips.append(ip_)
host_ips = list(set(good_ips))
# Process each container
for container in six.itervalues(containers):
container_id = container['Info']['Id']
if container['Image'] not in proxy_lists:
proxy_lists[container['Image']] = {}
for dock_port in container['Ports']:
# IP exists only if port is exposed
ip_address = dock_port.get('IP')
# If port is 0.0.0.0, then we must get the docker host IP
if ip_address == '0.0.0.0':
for ip_ in host_ips:
containers = proxy_lists[container['Image']].setdefault('ipv4', {}).setdefault(dock_port['PrivatePort'], [])
container_network_footprint = '{0}:{1}'.format(ip_, dock_port['PublicPort'])
if with_container_id:
value = (container_network_footprint, container_id)
else:
value = container_network_footprint
if value not in containers:
containers.append(value)
elif ip_address:
containers = proxy_lists[container['Image']].setdefault('ipv4', {}).setdefault(dock_port['PrivatePort'], [])
container_network_footprint = '{0}:{1}'.format(dock_port['IP'], dock_port['PublicPort'])
if with_container_id:
value = (container_network_footprint, container_id)
else:
value = container_network_footprint
if value not in containers:
containers.append(value)
return proxy_lists
def valid():
'''
List valid entries in mine configuration.
CLI Example:
.. code-block:: bash
salt '*' mine.valid
'''
m_data = __salt__['config.merge']('mine_functions', {})
# If we don't have any mine functions configured, then we should just bail out
if not m_data:
return
data = {}
for func in m_data:
if m_data[func] and isinstance(m_data[func], dict):
mine_func = m_data[func].pop('mine_function', func)
if not _mine_function_available(mine_func):
continue
data[func] = {mine_func: m_data[func]}
elif m_data[func] and isinstance(m_data[func], list):
mine_func = func
if isinstance(m_data[func][0], dict) and 'mine_function' in m_data[func][0]:
mine_func = m_data[func][0]['mine_function']
m_data[func].pop(0)
if not _mine_function_available(mine_func):
continue
data[func] = {mine_func: m_data[func]}
else:
if not _mine_function_available(func):
continue
data[func] = m_data[func]
return data
|
saltstack/salt
|
salt/modules/mine.py
|
update
|
python
|
def update(clear=False, mine_functions=None):
'''
Execute the configured functions and send the data back up to the master.
The functions to be executed are merged from the master config, pillar and
minion config under the option `mine_functions`:
.. code-block:: yaml
mine_functions:
network.ip_addrs:
- eth0
disk.usage: []
This function accepts the following arguments:
clear: False
Boolean flag specifying whether updating will clear the existing
mines, or will update. Default: `False` (update).
mine_functions
Update the mine data on certain functions only.
This feature can be used when updating the mine for functions
that require refresh at different intervals than the rest of
the functions specified under `mine_functions` in the
minion/master config or pillar.
A potential use would be together with the `scheduler`, for example:
.. code-block:: yaml
schedule:
lldp_mine_update:
function: mine.update
kwargs:
mine_functions:
net.lldp: []
hours: 12
In the example above, the mine for `net.lldp` would be refreshed
every 12 hours, while `network.ip_addrs` would continue to be updated
as specified in `mine_interval`.
The function cache will be populated with information from executing these
functions
CLI Example:
.. code-block:: bash
salt '*' mine.update
'''
m_data = {}
if not mine_functions:
m_data = __salt__['config.merge']('mine_functions', {})
# If we don't have any mine functions configured, then we should just bail out
if not m_data:
return
elif mine_functions and isinstance(mine_functions, list):
m_data = dict((fun, {}) for fun in mine_functions)
elif mine_functions and isinstance(mine_functions, dict):
m_data = mine_functions
else:
return
data = {}
for func in m_data:
try:
if m_data[func] and isinstance(m_data[func], dict):
mine_func = m_data[func].pop('mine_function', func)
if not _mine_function_available(mine_func):
continue
data[func] = __salt__[mine_func](**m_data[func])
elif m_data[func] and isinstance(m_data[func], list):
mine_func = func
if isinstance(m_data[func][0], dict) and 'mine_function' in m_data[func][0]:
mine_func = m_data[func][0]['mine_function']
m_data[func].pop(0)
if not _mine_function_available(mine_func):
continue
data[func] = __salt__[mine_func](*m_data[func])
else:
if not _mine_function_available(func):
continue
data[func] = __salt__[func]()
except Exception:
trace = traceback.format_exc()
log.error('Function %s in mine_functions failed to execute', func)
log.debug('Error: %s', trace)
continue
if __opts__['file_client'] == 'local':
if not clear:
old = __salt__['data.get']('mine_cache')
if isinstance(old, dict):
old.update(data)
data = old
return __salt__['data.update']('mine_cache', data)
load = {
'cmd': '_mine',
'data': data,
'id': __opts__['id'],
'clear': clear,
}
return _mine_send(load, __opts__)
|
Execute the configured functions and send the data back up to the master.
The functions to be executed are merged from the master config, pillar and
minion config under the option `mine_functions`:
.. code-block:: yaml
mine_functions:
network.ip_addrs:
- eth0
disk.usage: []
This function accepts the following arguments:
clear: False
Boolean flag specifying whether updating will clear the existing
mines, or will update. Default: `False` (update).
mine_functions
Update the mine data on certain functions only.
This feature can be used when updating the mine for functions
that require refresh at different intervals than the rest of
the functions specified under `mine_functions` in the
minion/master config or pillar.
A potential use would be together with the `scheduler`, for example:
.. code-block:: yaml
schedule:
lldp_mine_update:
function: mine.update
kwargs:
mine_functions:
net.lldp: []
hours: 12
In the example above, the mine for `net.lldp` would be refreshed
every 12 hours, while `network.ip_addrs` would continue to be updated
as specified in `mine_interval`.
The function cache will be populated with information from executing these
functions
CLI Example:
.. code-block:: bash
salt '*' mine.update
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mine.py#L86-L188
|
[
"def _mine_function_available(func):\n if func not in __salt__:\n log.error('Function %s in mine_functions not available', func)\n return False\n return True\n",
"def _mine_send(load, opts):\n eventer = salt.utils.event.MinionEvent(opts, listen=False)\n event_ret = eventer.fire_event(load, '_minion_mine')\n # We need to pause here to allow for the decoupled nature of\n # events time to allow the mine to propagate\n time.sleep(0.5)\n return event_ret\n"
] |
# -*- coding: utf-8 -*-
'''
The function cache system allows for data to be stored on the master so it can be easily read by other minions
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import time
import traceback
# Import salt libs
import salt.crypt
import salt.payload
import salt.utils.args
import salt.utils.event
import salt.utils.network
import salt.transport.client
from salt.exceptions import SaltClientError
# Import 3rd-party libs
from salt.ext import six
MINE_INTERNAL_KEYWORDS = frozenset([
'__pub_user',
'__pub_arg',
'__pub_fun',
'__pub_jid',
'__pub_tgt',
'__pub_tgt_type',
'__pub_ret'
])
__proxyenabled__ = ['*']
log = logging.getLogger(__name__)
def _auth():
'''
Return the auth object
'''
if 'auth' not in __context__:
try:
__context__['auth'] = salt.crypt.SAuth(__opts__)
except SaltClientError:
log.error('Could not authenticate with master.'
'Mine data will not be transmitted.')
return __context__['auth']
def _mine_function_available(func):
if func not in __salt__:
log.error('Function %s in mine_functions not available', func)
return False
return True
def _mine_send(load, opts):
eventer = salt.utils.event.MinionEvent(opts, listen=False)
event_ret = eventer.fire_event(load, '_minion_mine')
# We need to pause here to allow for the decoupled nature of
# events time to allow the mine to propagate
time.sleep(0.5)
return event_ret
def _mine_get(load, opts):
if opts.get('transport', '') in ('zeromq', 'tcp'):
try:
load['tok'] = _auth().gen_token(b'salt')
except AttributeError:
log.error('Mine could not authenticate with master. '
'Mine could not be retrieved.'
)
return False
channel = salt.transport.client.ReqChannel.factory(opts)
try:
ret = channel.send(load)
finally:
channel.close()
return ret
def send(func, *args, **kwargs):
'''
Send a specific function to the mine.
CLI Example:
.. code-block:: bash
salt '*' mine.send network.ip_addrs eth0
salt '*' mine.send eth0_ip_addrs mine_function=network.ip_addrs eth0
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
mine_func = kwargs.pop('mine_function', func)
if mine_func not in __salt__:
return False
data = {}
arg_data = salt.utils.args.arg_lookup(__salt__[mine_func])
func_data = copy.deepcopy(kwargs)
for ind, _ in enumerate(arg_data.get('args', [])):
try:
func_data[arg_data['args'][ind]] = args[ind]
except IndexError:
# Safe error, arg may be in kwargs
pass
f_call = salt.utils.args.format_call(
__salt__[mine_func],
func_data,
expected_extra_kws=MINE_INTERNAL_KEYWORDS)
for arg in args:
if arg not in f_call['args']:
f_call['args'].append(arg)
try:
if 'kwargs' in f_call:
data[func] = __salt__[mine_func](*f_call['args'], **f_call['kwargs'])
else:
data[func] = __salt__[mine_func](*f_call['args'])
except Exception as exc:
log.error('Function %s in mine.send failed to execute: %s',
mine_func, exc)
return False
if __opts__['file_client'] == 'local':
old = __salt__['data.get']('mine_cache')
if isinstance(old, dict):
old.update(data)
data = old
return __salt__['data.update']('mine_cache', data)
load = {
'cmd': '_mine',
'data': data,
'id': __opts__['id'],
}
return _mine_send(load, __opts__)
def get(tgt,
fun,
tgt_type='glob',
exclude_minion=False):
'''
Get data from the mine based on the target, function and tgt_type
Targets can be matched based on any standard matching system that can be
matched on the master via these keywords:
- glob
- pcre
- grain
- grain_pcre
- compound
- pillar
- pillar_pcre
Note that all pillar matches, whether using the compound matching system or
the pillar matching system, will be exact matches, with globbing disabled.
exclude_minion
Excludes the current minion from the result set
CLI Example:
.. code-block:: bash
salt '*' mine.get '*' network.interfaces
salt '*' mine.get '*' network.interfaces,network.ipaddrs
salt '*' mine.get '*' '["network.interfaces", "network.ipaddrs"]'
salt '*' mine.get 'os:Fedora' network.interfaces grain
salt '*' mine.get 'G@os:Fedora and S@192.168.5.0/24' network.ipaddrs compound
.. seealso:: Retrieving Mine data from Pillar and Orchestrate
This execution module is intended to be executed on minions.
Master-side operations such as Pillar or Orchestrate that require Mine
data should use the :py:mod:`Mine Runner module <salt.runners.mine>`
instead; it can be invoked from a Pillar SLS file using the
:py:func:`saltutil.runner <salt.modules.saltutil.runner>` module. For
example:
.. code-block:: jinja
{% set minion_ips = salt.saltutil.runner('mine.get',
tgt='*',
fun='network.ip_addrs',
tgt_type='glob') %}
'''
if __opts__['file_client'] == 'local':
ret = {}
is_target = {'glob': __salt__['match.glob'],
'pcre': __salt__['match.pcre'],
'list': __salt__['match.list'],
'grain': __salt__['match.grain'],
'grain_pcre': __salt__['match.grain_pcre'],
'ipcidr': __salt__['match.ipcidr'],
'compound': __salt__['match.compound'],
'pillar': __salt__['match.pillar'],
'pillar_pcre': __salt__['match.pillar_pcre'],
}[tgt_type](tgt)
if is_target:
data = __salt__['data.get']('mine_cache')
if isinstance(data, dict):
if isinstance(fun, six.string_types):
functions = list(set(fun.split(',')))
_ret_dict = len(functions) > 1
elif isinstance(fun, list):
functions = fun
_ret_dict = True
else:
return {}
if not _ret_dict and functions and functions[0] in data:
ret[__opts__['id']] = data.get(functions)
elif _ret_dict:
for fun in functions:
if fun in data:
ret.setdefault(fun, {})[__opts__['id']] = data.get(fun)
return ret
load = {
'cmd': '_mine_get',
'id': __opts__['id'],
'tgt': tgt,
'fun': fun,
'tgt_type': tgt_type,
}
ret = _mine_get(load, __opts__)
if exclude_minion:
if __opts__['id'] in ret:
del ret[__opts__['id']]
return ret
def delete(fun):
'''
Remove specific function contents of minion. Returns True on success.
CLI Example:
.. code-block:: bash
salt '*' mine.delete 'network.interfaces'
'''
if __opts__['file_client'] == 'local':
data = __salt__['data.get']('mine_cache')
if isinstance(data, dict) and fun in data:
del data[fun]
return __salt__['data.update']('mine_cache', data)
load = {
'cmd': '_mine_delete',
'id': __opts__['id'],
'fun': fun,
}
return _mine_send(load, __opts__)
def flush():
'''
Remove all mine contents of minion. Returns True on success.
CLI Example:
.. code-block:: bash
salt '*' mine.flush
'''
if __opts__['file_client'] == 'local':
return __salt__['data.update']('mine_cache', {})
load = {
'cmd': '_mine_flush',
'id': __opts__['id'],
}
return _mine_send(load, __opts__)
def get_docker(interfaces=None, cidrs=None, with_container_id=False):
'''
.. versionchanged:: 2017.7.8,2018.3.3
When :conf_minion:`docker.update_mine` is set to ``False`` for a given
minion, no mine data will be populated for that minion, and thus none
will be returned for it.
.. versionchanged:: 2019.2.0
:conf_minion:`docker.update_mine` now defaults to ``False``
Get all mine data for :py:func:`docker.ps <salt.modules.dockermod.ps_>` and
run an aggregation routine. The ``interfaces`` parameter allows for
specifying the network interfaces from which to select IP addresses. The
``cidrs`` parameter allows for specifying a list of subnets which the IP
address must match.
with_container_id
Boolean, to expose container_id in the list of results
.. versionadded:: 2015.8.2
CLI Example:
.. code-block:: bash
salt '*' mine.get_docker
salt '*' mine.get_docker interfaces='eth0'
salt '*' mine.get_docker interfaces='["eth0", "eth1"]'
salt '*' mine.get_docker cidrs='107.170.147.0/24'
salt '*' mine.get_docker cidrs='["107.170.147.0/24", "172.17.42.0/24"]'
salt '*' mine.get_docker interfaces='["eth0", "eth1"]' cidrs='["107.170.147.0/24", "172.17.42.0/24"]'
'''
# Enforce that interface and cidr are lists
if interfaces:
interface_ = []
interface_.extend(interfaces if isinstance(interfaces, list) else [interfaces])
interfaces = interface_
if cidrs:
cidr_ = []
cidr_.extend(cidrs if isinstance(cidrs, list) else [cidrs])
cidrs = cidr_
# Get docker info
cmd = 'docker.ps'
docker_hosts = get('*', cmd)
proxy_lists = {}
# Process docker info
for containers in six.itervalues(docker_hosts):
host = containers.pop('host')
host_ips = []
# Prepare host_ips list
if not interfaces:
for info in six.itervalues(host['interfaces']):
if 'inet' in info:
for ip_ in info['inet']:
host_ips.append(ip_['address'])
else:
for interface in interfaces:
if interface in host['interfaces']:
if 'inet' in host['interfaces'][interface]:
for item in host['interfaces'][interface]['inet']:
host_ips.append(item['address'])
host_ips = list(set(host_ips))
# Filter out ips from host_ips with cidrs
if cidrs:
good_ips = []
for cidr in cidrs:
for ip_ in host_ips:
if salt.utils.network.in_subnet(cidr, [ip_]):
good_ips.append(ip_)
host_ips = list(set(good_ips))
# Process each container
for container in six.itervalues(containers):
container_id = container['Info']['Id']
if container['Image'] not in proxy_lists:
proxy_lists[container['Image']] = {}
for dock_port in container['Ports']:
# IP exists only if port is exposed
ip_address = dock_port.get('IP')
# If port is 0.0.0.0, then we must get the docker host IP
if ip_address == '0.0.0.0':
for ip_ in host_ips:
containers = proxy_lists[container['Image']].setdefault('ipv4', {}).setdefault(dock_port['PrivatePort'], [])
container_network_footprint = '{0}:{1}'.format(ip_, dock_port['PublicPort'])
if with_container_id:
value = (container_network_footprint, container_id)
else:
value = container_network_footprint
if value not in containers:
containers.append(value)
elif ip_address:
containers = proxy_lists[container['Image']].setdefault('ipv4', {}).setdefault(dock_port['PrivatePort'], [])
container_network_footprint = '{0}:{1}'.format(dock_port['IP'], dock_port['PublicPort'])
if with_container_id:
value = (container_network_footprint, container_id)
else:
value = container_network_footprint
if value not in containers:
containers.append(value)
return proxy_lists
def valid():
'''
List valid entries in mine configuration.
CLI Example:
.. code-block:: bash
salt '*' mine.valid
'''
m_data = __salt__['config.merge']('mine_functions', {})
# If we don't have any mine functions configured, then we should just bail out
if not m_data:
return
data = {}
for func in m_data:
if m_data[func] and isinstance(m_data[func], dict):
mine_func = m_data[func].pop('mine_function', func)
if not _mine_function_available(mine_func):
continue
data[func] = {mine_func: m_data[func]}
elif m_data[func] and isinstance(m_data[func], list):
mine_func = func
if isinstance(m_data[func][0], dict) and 'mine_function' in m_data[func][0]:
mine_func = m_data[func][0]['mine_function']
m_data[func].pop(0)
if not _mine_function_available(mine_func):
continue
data[func] = {mine_func: m_data[func]}
else:
if not _mine_function_available(func):
continue
data[func] = m_data[func]
return data
|
saltstack/salt
|
salt/modules/mine.py
|
send
|
python
|
def send(func, *args, **kwargs):
'''
Send a specific function to the mine.
CLI Example:
.. code-block:: bash
salt '*' mine.send network.ip_addrs eth0
salt '*' mine.send eth0_ip_addrs mine_function=network.ip_addrs eth0
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
mine_func = kwargs.pop('mine_function', func)
if mine_func not in __salt__:
return False
data = {}
arg_data = salt.utils.args.arg_lookup(__salt__[mine_func])
func_data = copy.deepcopy(kwargs)
for ind, _ in enumerate(arg_data.get('args', [])):
try:
func_data[arg_data['args'][ind]] = args[ind]
except IndexError:
# Safe error, arg may be in kwargs
pass
f_call = salt.utils.args.format_call(
__salt__[mine_func],
func_data,
expected_extra_kws=MINE_INTERNAL_KEYWORDS)
for arg in args:
if arg not in f_call['args']:
f_call['args'].append(arg)
try:
if 'kwargs' in f_call:
data[func] = __salt__[mine_func](*f_call['args'], **f_call['kwargs'])
else:
data[func] = __salt__[mine_func](*f_call['args'])
except Exception as exc:
log.error('Function %s in mine.send failed to execute: %s',
mine_func, exc)
return False
if __opts__['file_client'] == 'local':
old = __salt__['data.get']('mine_cache')
if isinstance(old, dict):
old.update(data)
data = old
return __salt__['data.update']('mine_cache', data)
load = {
'cmd': '_mine',
'data': data,
'id': __opts__['id'],
}
return _mine_send(load, __opts__)
|
Send a specific function to the mine.
CLI Example:
.. code-block:: bash
salt '*' mine.send network.ip_addrs eth0
salt '*' mine.send eth0_ip_addrs mine_function=network.ip_addrs eth0
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mine.py#L191-L242
|
[
"def format_call(fun,\n data,\n initial_ret=None,\n expected_extra_kws=(),\n is_class_method=None):\n '''\n Build the required arguments and keyword arguments required for the passed\n function.\n\n :param fun: The function to get the argspec from\n :param data: A dictionary containing the required data to build the\n arguments and keyword arguments.\n :param initial_ret: The initial return data pre-populated as dictionary or\n None\n :param expected_extra_kws: Any expected extra keyword argument names which\n should not trigger a :ref:`SaltInvocationError`\n :param is_class_method: Pass True if you are sure that the function being passed\n is a class method. The reason for this is that on Python 3\n ``inspect.ismethod`` only returns ``True`` for bound methods,\n while on Python 2, it returns ``True`` for bound and unbound\n methods. So, on Python 3, in case of a class method, you'd\n need the class to which the function belongs to be instantiated\n and this is not always wanted.\n :returns: A dictionary with the function required arguments and keyword\n arguments.\n '''\n ret = initial_ret is not None and initial_ret or {}\n\n ret['args'] = []\n ret['kwargs'] = OrderedDict()\n\n aspec = get_function_argspec(fun, is_class_method=is_class_method)\n\n arg_data = arg_lookup(fun, aspec)\n args = arg_data['args']\n kwargs = arg_data['kwargs']\n\n # Since we WILL be changing the data dictionary, let's change a copy of it\n data = data.copy()\n\n missing_args = []\n\n for key in kwargs:\n try:\n kwargs[key] = data.pop(key)\n except KeyError:\n # Let's leave the default value in place\n pass\n\n while args:\n arg = args.pop(0)\n try:\n ret['args'].append(data.pop(arg))\n except KeyError:\n missing_args.append(arg)\n\n if missing_args:\n used_args_count = len(ret['args']) + len(args)\n args_count = used_args_count + len(missing_args)\n raise SaltInvocationError(\n '{0} takes at least {1} argument{2} ({3} given)'.format(\n fun.__name__,\n args_count,\n args_count > 1 and 's' or '',\n used_args_count\n )\n )\n\n ret['kwargs'].update(kwargs)\n\n if aspec.keywords:\n # The function accepts **kwargs, any non expected extra keyword\n # arguments will made available.\n for key, value in six.iteritems(data):\n if key in expected_extra_kws:\n continue\n ret['kwargs'][key] = value\n\n # No need to check for extra keyword arguments since they are all\n # **kwargs now. Return\n return ret\n\n # Did not return yet? Lets gather any remaining and unexpected keyword\n # arguments\n extra = {}\n for key, value in six.iteritems(data):\n if key in expected_extra_kws:\n continue\n extra[key] = copy.deepcopy(value)\n\n if extra:\n # Found unexpected keyword arguments, raise an error to the user\n if len(extra) == 1:\n msg = '\\'{0[0]}\\' is an invalid keyword argument for \\'{1}\\''.format(\n list(extra.keys()),\n ret.get(\n # In case this is being called for a state module\n 'full',\n # Not a state module, build the name\n '{0}.{1}'.format(fun.__module__, fun.__name__)\n )\n )\n else:\n msg = '{0} and \\'{1}\\' are invalid keyword arguments for \\'{2}\\''.format(\n ', '.join(['\\'{0}\\''.format(e) for e in extra][:-1]),\n list(extra.keys())[-1],\n ret.get(\n # In case this is being called for a state module\n 'full',\n # Not a state module, build the name\n '{0}.{1}'.format(fun.__module__, fun.__name__)\n )\n )\n\n raise SaltInvocationError(msg)\n return ret\n",
"def clean_kwargs(**kwargs):\n '''\n Return a dict without any of the __pub* keys (or any other keys starting\n with a dunder) from the kwargs dict passed into the execution module\n functions. These keys are useful for tracking what was used to invoke\n the function call, but they may not be desirable to have if passing the\n kwargs forward wholesale.\n\n Usage example:\n\n .. code-block:: python\n\n kwargs = __utils__['args.clean_kwargs'](**kwargs)\n '''\n ret = {}\n for key, val in six.iteritems(kwargs):\n if not key.startswith('__'):\n ret[key] = val\n return ret\n",
"def arg_lookup(fun, aspec=None):\n '''\n Return a dict containing the arguments and default arguments to the\n function.\n '''\n ret = {'kwargs': {}}\n if aspec is None:\n aspec = get_function_argspec(fun)\n if aspec.defaults:\n ret['kwargs'] = dict(zip(aspec.args[::-1], aspec.defaults[::-1]))\n ret['args'] = [arg for arg in aspec.args if arg not in ret['kwargs']]\n return ret\n",
"def _mine_send(load, opts):\n eventer = salt.utils.event.MinionEvent(opts, listen=False)\n event_ret = eventer.fire_event(load, '_minion_mine')\n # We need to pause here to allow for the decoupled nature of\n # events time to allow the mine to propagate\n time.sleep(0.5)\n return event_ret\n"
] |
# -*- coding: utf-8 -*-
'''
The function cache system allows for data to be stored on the master so it can be easily read by other minions
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import time
import traceback
# Import salt libs
import salt.crypt
import salt.payload
import salt.utils.args
import salt.utils.event
import salt.utils.network
import salt.transport.client
from salt.exceptions import SaltClientError
# Import 3rd-party libs
from salt.ext import six
MINE_INTERNAL_KEYWORDS = frozenset([
'__pub_user',
'__pub_arg',
'__pub_fun',
'__pub_jid',
'__pub_tgt',
'__pub_tgt_type',
'__pub_ret'
])
__proxyenabled__ = ['*']
log = logging.getLogger(__name__)
def _auth():
'''
Return the auth object
'''
if 'auth' not in __context__:
try:
__context__['auth'] = salt.crypt.SAuth(__opts__)
except SaltClientError:
log.error('Could not authenticate with master.'
'Mine data will not be transmitted.')
return __context__['auth']
def _mine_function_available(func):
if func not in __salt__:
log.error('Function %s in mine_functions not available', func)
return False
return True
def _mine_send(load, opts):
eventer = salt.utils.event.MinionEvent(opts, listen=False)
event_ret = eventer.fire_event(load, '_minion_mine')
# We need to pause here to allow for the decoupled nature of
# events time to allow the mine to propagate
time.sleep(0.5)
return event_ret
def _mine_get(load, opts):
if opts.get('transport', '') in ('zeromq', 'tcp'):
try:
load['tok'] = _auth().gen_token(b'salt')
except AttributeError:
log.error('Mine could not authenticate with master. '
'Mine could not be retrieved.'
)
return False
channel = salt.transport.client.ReqChannel.factory(opts)
try:
ret = channel.send(load)
finally:
channel.close()
return ret
def update(clear=False, mine_functions=None):
'''
Execute the configured functions and send the data back up to the master.
The functions to be executed are merged from the master config, pillar and
minion config under the option `mine_functions`:
.. code-block:: yaml
mine_functions:
network.ip_addrs:
- eth0
disk.usage: []
This function accepts the following arguments:
clear: False
Boolean flag specifying whether updating will clear the existing
mines, or will update. Default: `False` (update).
mine_functions
Update the mine data on certain functions only.
This feature can be used when updating the mine for functions
that require refresh at different intervals than the rest of
the functions specified under `mine_functions` in the
minion/master config or pillar.
A potential use would be together with the `scheduler`, for example:
.. code-block:: yaml
schedule:
lldp_mine_update:
function: mine.update
kwargs:
mine_functions:
net.lldp: []
hours: 12
In the example above, the mine for `net.lldp` would be refreshed
every 12 hours, while `network.ip_addrs` would continue to be updated
as specified in `mine_interval`.
The function cache will be populated with information from executing these
functions
CLI Example:
.. code-block:: bash
salt '*' mine.update
'''
m_data = {}
if not mine_functions:
m_data = __salt__['config.merge']('mine_functions', {})
# If we don't have any mine functions configured, then we should just bail out
if not m_data:
return
elif mine_functions and isinstance(mine_functions, list):
m_data = dict((fun, {}) for fun in mine_functions)
elif mine_functions and isinstance(mine_functions, dict):
m_data = mine_functions
else:
return
data = {}
for func in m_data:
try:
if m_data[func] and isinstance(m_data[func], dict):
mine_func = m_data[func].pop('mine_function', func)
if not _mine_function_available(mine_func):
continue
data[func] = __salt__[mine_func](**m_data[func])
elif m_data[func] and isinstance(m_data[func], list):
mine_func = func
if isinstance(m_data[func][0], dict) and 'mine_function' in m_data[func][0]:
mine_func = m_data[func][0]['mine_function']
m_data[func].pop(0)
if not _mine_function_available(mine_func):
continue
data[func] = __salt__[mine_func](*m_data[func])
else:
if not _mine_function_available(func):
continue
data[func] = __salt__[func]()
except Exception:
trace = traceback.format_exc()
log.error('Function %s in mine_functions failed to execute', func)
log.debug('Error: %s', trace)
continue
if __opts__['file_client'] == 'local':
if not clear:
old = __salt__['data.get']('mine_cache')
if isinstance(old, dict):
old.update(data)
data = old
return __salt__['data.update']('mine_cache', data)
load = {
'cmd': '_mine',
'data': data,
'id': __opts__['id'],
'clear': clear,
}
return _mine_send(load, __opts__)
def get(tgt,
fun,
tgt_type='glob',
exclude_minion=False):
'''
Get data from the mine based on the target, function and tgt_type
Targets can be matched based on any standard matching system that can be
matched on the master via these keywords:
- glob
- pcre
- grain
- grain_pcre
- compound
- pillar
- pillar_pcre
Note that all pillar matches, whether using the compound matching system or
the pillar matching system, will be exact matches, with globbing disabled.
exclude_minion
Excludes the current minion from the result set
CLI Example:
.. code-block:: bash
salt '*' mine.get '*' network.interfaces
salt '*' mine.get '*' network.interfaces,network.ipaddrs
salt '*' mine.get '*' '["network.interfaces", "network.ipaddrs"]'
salt '*' mine.get 'os:Fedora' network.interfaces grain
salt '*' mine.get 'G@os:Fedora and S@192.168.5.0/24' network.ipaddrs compound
.. seealso:: Retrieving Mine data from Pillar and Orchestrate
This execution module is intended to be executed on minions.
Master-side operations such as Pillar or Orchestrate that require Mine
data should use the :py:mod:`Mine Runner module <salt.runners.mine>`
instead; it can be invoked from a Pillar SLS file using the
:py:func:`saltutil.runner <salt.modules.saltutil.runner>` module. For
example:
.. code-block:: jinja
{% set minion_ips = salt.saltutil.runner('mine.get',
tgt='*',
fun='network.ip_addrs',
tgt_type='glob') %}
'''
if __opts__['file_client'] == 'local':
ret = {}
is_target = {'glob': __salt__['match.glob'],
'pcre': __salt__['match.pcre'],
'list': __salt__['match.list'],
'grain': __salt__['match.grain'],
'grain_pcre': __salt__['match.grain_pcre'],
'ipcidr': __salt__['match.ipcidr'],
'compound': __salt__['match.compound'],
'pillar': __salt__['match.pillar'],
'pillar_pcre': __salt__['match.pillar_pcre'],
}[tgt_type](tgt)
if is_target:
data = __salt__['data.get']('mine_cache')
if isinstance(data, dict):
if isinstance(fun, six.string_types):
functions = list(set(fun.split(',')))
_ret_dict = len(functions) > 1
elif isinstance(fun, list):
functions = fun
_ret_dict = True
else:
return {}
if not _ret_dict and functions and functions[0] in data:
ret[__opts__['id']] = data.get(functions)
elif _ret_dict:
for fun in functions:
if fun in data:
ret.setdefault(fun, {})[__opts__['id']] = data.get(fun)
return ret
load = {
'cmd': '_mine_get',
'id': __opts__['id'],
'tgt': tgt,
'fun': fun,
'tgt_type': tgt_type,
}
ret = _mine_get(load, __opts__)
if exclude_minion:
if __opts__['id'] in ret:
del ret[__opts__['id']]
return ret
def delete(fun):
'''
Remove specific function contents of minion. Returns True on success.
CLI Example:
.. code-block:: bash
salt '*' mine.delete 'network.interfaces'
'''
if __opts__['file_client'] == 'local':
data = __salt__['data.get']('mine_cache')
if isinstance(data, dict) and fun in data:
del data[fun]
return __salt__['data.update']('mine_cache', data)
load = {
'cmd': '_mine_delete',
'id': __opts__['id'],
'fun': fun,
}
return _mine_send(load, __opts__)
def flush():
'''
Remove all mine contents of minion. Returns True on success.
CLI Example:
.. code-block:: bash
salt '*' mine.flush
'''
if __opts__['file_client'] == 'local':
return __salt__['data.update']('mine_cache', {})
load = {
'cmd': '_mine_flush',
'id': __opts__['id'],
}
return _mine_send(load, __opts__)
def get_docker(interfaces=None, cidrs=None, with_container_id=False):
'''
.. versionchanged:: 2017.7.8,2018.3.3
When :conf_minion:`docker.update_mine` is set to ``False`` for a given
minion, no mine data will be populated for that minion, and thus none
will be returned for it.
.. versionchanged:: 2019.2.0
:conf_minion:`docker.update_mine` now defaults to ``False``
Get all mine data for :py:func:`docker.ps <salt.modules.dockermod.ps_>` and
run an aggregation routine. The ``interfaces`` parameter allows for
specifying the network interfaces from which to select IP addresses. The
``cidrs`` parameter allows for specifying a list of subnets which the IP
address must match.
with_container_id
Boolean, to expose container_id in the list of results
.. versionadded:: 2015.8.2
CLI Example:
.. code-block:: bash
salt '*' mine.get_docker
salt '*' mine.get_docker interfaces='eth0'
salt '*' mine.get_docker interfaces='["eth0", "eth1"]'
salt '*' mine.get_docker cidrs='107.170.147.0/24'
salt '*' mine.get_docker cidrs='["107.170.147.0/24", "172.17.42.0/24"]'
salt '*' mine.get_docker interfaces='["eth0", "eth1"]' cidrs='["107.170.147.0/24", "172.17.42.0/24"]'
'''
# Enforce that interface and cidr are lists
if interfaces:
interface_ = []
interface_.extend(interfaces if isinstance(interfaces, list) else [interfaces])
interfaces = interface_
if cidrs:
cidr_ = []
cidr_.extend(cidrs if isinstance(cidrs, list) else [cidrs])
cidrs = cidr_
# Get docker info
cmd = 'docker.ps'
docker_hosts = get('*', cmd)
proxy_lists = {}
# Process docker info
for containers in six.itervalues(docker_hosts):
host = containers.pop('host')
host_ips = []
# Prepare host_ips list
if not interfaces:
for info in six.itervalues(host['interfaces']):
if 'inet' in info:
for ip_ in info['inet']:
host_ips.append(ip_['address'])
else:
for interface in interfaces:
if interface in host['interfaces']:
if 'inet' in host['interfaces'][interface]:
for item in host['interfaces'][interface]['inet']:
host_ips.append(item['address'])
host_ips = list(set(host_ips))
# Filter out ips from host_ips with cidrs
if cidrs:
good_ips = []
for cidr in cidrs:
for ip_ in host_ips:
if salt.utils.network.in_subnet(cidr, [ip_]):
good_ips.append(ip_)
host_ips = list(set(good_ips))
# Process each container
for container in six.itervalues(containers):
container_id = container['Info']['Id']
if container['Image'] not in proxy_lists:
proxy_lists[container['Image']] = {}
for dock_port in container['Ports']:
# IP exists only if port is exposed
ip_address = dock_port.get('IP')
# If port is 0.0.0.0, then we must get the docker host IP
if ip_address == '0.0.0.0':
for ip_ in host_ips:
containers = proxy_lists[container['Image']].setdefault('ipv4', {}).setdefault(dock_port['PrivatePort'], [])
container_network_footprint = '{0}:{1}'.format(ip_, dock_port['PublicPort'])
if with_container_id:
value = (container_network_footprint, container_id)
else:
value = container_network_footprint
if value not in containers:
containers.append(value)
elif ip_address:
containers = proxy_lists[container['Image']].setdefault('ipv4', {}).setdefault(dock_port['PrivatePort'], [])
container_network_footprint = '{0}:{1}'.format(dock_port['IP'], dock_port['PublicPort'])
if with_container_id:
value = (container_network_footprint, container_id)
else:
value = container_network_footprint
if value not in containers:
containers.append(value)
return proxy_lists
def valid():
'''
List valid entries in mine configuration.
CLI Example:
.. code-block:: bash
salt '*' mine.valid
'''
m_data = __salt__['config.merge']('mine_functions', {})
# If we don't have any mine functions configured, then we should just bail out
if not m_data:
return
data = {}
for func in m_data:
if m_data[func] and isinstance(m_data[func], dict):
mine_func = m_data[func].pop('mine_function', func)
if not _mine_function_available(mine_func):
continue
data[func] = {mine_func: m_data[func]}
elif m_data[func] and isinstance(m_data[func], list):
mine_func = func
if isinstance(m_data[func][0], dict) and 'mine_function' in m_data[func][0]:
mine_func = m_data[func][0]['mine_function']
m_data[func].pop(0)
if not _mine_function_available(mine_func):
continue
data[func] = {mine_func: m_data[func]}
else:
if not _mine_function_available(func):
continue
data[func] = m_data[func]
return data
|
saltstack/salt
|
salt/modules/mine.py
|
get
|
python
|
def get(tgt,
fun,
tgt_type='glob',
exclude_minion=False):
'''
Get data from the mine based on the target, function and tgt_type
Targets can be matched based on any standard matching system that can be
matched on the master via these keywords:
- glob
- pcre
- grain
- grain_pcre
- compound
- pillar
- pillar_pcre
Note that all pillar matches, whether using the compound matching system or
the pillar matching system, will be exact matches, with globbing disabled.
exclude_minion
Excludes the current minion from the result set
CLI Example:
.. code-block:: bash
salt '*' mine.get '*' network.interfaces
salt '*' mine.get '*' network.interfaces,network.ipaddrs
salt '*' mine.get '*' '["network.interfaces", "network.ipaddrs"]'
salt '*' mine.get 'os:Fedora' network.interfaces grain
salt '*' mine.get 'G@os:Fedora and S@192.168.5.0/24' network.ipaddrs compound
.. seealso:: Retrieving Mine data from Pillar and Orchestrate
This execution module is intended to be executed on minions.
Master-side operations such as Pillar or Orchestrate that require Mine
data should use the :py:mod:`Mine Runner module <salt.runners.mine>`
instead; it can be invoked from a Pillar SLS file using the
:py:func:`saltutil.runner <salt.modules.saltutil.runner>` module. For
example:
.. code-block:: jinja
{% set minion_ips = salt.saltutil.runner('mine.get',
tgt='*',
fun='network.ip_addrs',
tgt_type='glob') %}
'''
if __opts__['file_client'] == 'local':
ret = {}
is_target = {'glob': __salt__['match.glob'],
'pcre': __salt__['match.pcre'],
'list': __salt__['match.list'],
'grain': __salt__['match.grain'],
'grain_pcre': __salt__['match.grain_pcre'],
'ipcidr': __salt__['match.ipcidr'],
'compound': __salt__['match.compound'],
'pillar': __salt__['match.pillar'],
'pillar_pcre': __salt__['match.pillar_pcre'],
}[tgt_type](tgt)
if is_target:
data = __salt__['data.get']('mine_cache')
if isinstance(data, dict):
if isinstance(fun, six.string_types):
functions = list(set(fun.split(',')))
_ret_dict = len(functions) > 1
elif isinstance(fun, list):
functions = fun
_ret_dict = True
else:
return {}
if not _ret_dict and functions and functions[0] in data:
ret[__opts__['id']] = data.get(functions)
elif _ret_dict:
for fun in functions:
if fun in data:
ret.setdefault(fun, {})[__opts__['id']] = data.get(fun)
return ret
load = {
'cmd': '_mine_get',
'id': __opts__['id'],
'tgt': tgt,
'fun': fun,
'tgt_type': tgt_type,
}
ret = _mine_get(load, __opts__)
if exclude_minion:
if __opts__['id'] in ret:
del ret[__opts__['id']]
return ret
|
Get data from the mine based on the target, function and tgt_type
Targets can be matched based on any standard matching system that can be
matched on the master via these keywords:
- glob
- pcre
- grain
- grain_pcre
- compound
- pillar
- pillar_pcre
Note that all pillar matches, whether using the compound matching system or
the pillar matching system, will be exact matches, with globbing disabled.
exclude_minion
Excludes the current minion from the result set
CLI Example:
.. code-block:: bash
salt '*' mine.get '*' network.interfaces
salt '*' mine.get '*' network.interfaces,network.ipaddrs
salt '*' mine.get '*' '["network.interfaces", "network.ipaddrs"]'
salt '*' mine.get 'os:Fedora' network.interfaces grain
salt '*' mine.get 'G@os:Fedora and S@192.168.5.0/24' network.ipaddrs compound
.. seealso:: Retrieving Mine data from Pillar and Orchestrate
This execution module is intended to be executed on minions.
Master-side operations such as Pillar or Orchestrate that require Mine
data should use the :py:mod:`Mine Runner module <salt.runners.mine>`
instead; it can be invoked from a Pillar SLS file using the
:py:func:`saltutil.runner <salt.modules.saltutil.runner>` module. For
example:
.. code-block:: jinja
{% set minion_ips = salt.saltutil.runner('mine.get',
tgt='*',
fun='network.ip_addrs',
tgt_type='glob') %}
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mine.py#L245-L339
|
[
"def _mine_get(load, opts):\n if opts.get('transport', '') in ('zeromq', 'tcp'):\n try:\n load['tok'] = _auth().gen_token(b'salt')\n except AttributeError:\n log.error('Mine could not authenticate with master. '\n 'Mine could not be retrieved.'\n )\n return False\n channel = salt.transport.client.ReqChannel.factory(opts)\n try:\n ret = channel.send(load)\n finally:\n channel.close()\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
The function cache system allows for data to be stored on the master so it can be easily read by other minions
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import time
import traceback
# Import salt libs
import salt.crypt
import salt.payload
import salt.utils.args
import salt.utils.event
import salt.utils.network
import salt.transport.client
from salt.exceptions import SaltClientError
# Import 3rd-party libs
from salt.ext import six
MINE_INTERNAL_KEYWORDS = frozenset([
'__pub_user',
'__pub_arg',
'__pub_fun',
'__pub_jid',
'__pub_tgt',
'__pub_tgt_type',
'__pub_ret'
])
__proxyenabled__ = ['*']
log = logging.getLogger(__name__)
def _auth():
'''
Return the auth object
'''
if 'auth' not in __context__:
try:
__context__['auth'] = salt.crypt.SAuth(__opts__)
except SaltClientError:
log.error('Could not authenticate with master.'
'Mine data will not be transmitted.')
return __context__['auth']
def _mine_function_available(func):
if func not in __salt__:
log.error('Function %s in mine_functions not available', func)
return False
return True
def _mine_send(load, opts):
eventer = salt.utils.event.MinionEvent(opts, listen=False)
event_ret = eventer.fire_event(load, '_minion_mine')
# We need to pause here to allow for the decoupled nature of
# events time to allow the mine to propagate
time.sleep(0.5)
return event_ret
def _mine_get(load, opts):
if opts.get('transport', '') in ('zeromq', 'tcp'):
try:
load['tok'] = _auth().gen_token(b'salt')
except AttributeError:
log.error('Mine could not authenticate with master. '
'Mine could not be retrieved.'
)
return False
channel = salt.transport.client.ReqChannel.factory(opts)
try:
ret = channel.send(load)
finally:
channel.close()
return ret
def update(clear=False, mine_functions=None):
'''
Execute the configured functions and send the data back up to the master.
The functions to be executed are merged from the master config, pillar and
minion config under the option `mine_functions`:
.. code-block:: yaml
mine_functions:
network.ip_addrs:
- eth0
disk.usage: []
This function accepts the following arguments:
clear: False
Boolean flag specifying whether updating will clear the existing
mines, or will update. Default: `False` (update).
mine_functions
Update the mine data on certain functions only.
This feature can be used when updating the mine for functions
that require refresh at different intervals than the rest of
the functions specified under `mine_functions` in the
minion/master config or pillar.
A potential use would be together with the `scheduler`, for example:
.. code-block:: yaml
schedule:
lldp_mine_update:
function: mine.update
kwargs:
mine_functions:
net.lldp: []
hours: 12
In the example above, the mine for `net.lldp` would be refreshed
every 12 hours, while `network.ip_addrs` would continue to be updated
as specified in `mine_interval`.
The function cache will be populated with information from executing these
functions
CLI Example:
.. code-block:: bash
salt '*' mine.update
'''
m_data = {}
if not mine_functions:
m_data = __salt__['config.merge']('mine_functions', {})
# If we don't have any mine functions configured, then we should just bail out
if not m_data:
return
elif mine_functions and isinstance(mine_functions, list):
m_data = dict((fun, {}) for fun in mine_functions)
elif mine_functions and isinstance(mine_functions, dict):
m_data = mine_functions
else:
return
data = {}
for func in m_data:
try:
if m_data[func] and isinstance(m_data[func], dict):
mine_func = m_data[func].pop('mine_function', func)
if not _mine_function_available(mine_func):
continue
data[func] = __salt__[mine_func](**m_data[func])
elif m_data[func] and isinstance(m_data[func], list):
mine_func = func
if isinstance(m_data[func][0], dict) and 'mine_function' in m_data[func][0]:
mine_func = m_data[func][0]['mine_function']
m_data[func].pop(0)
if not _mine_function_available(mine_func):
continue
data[func] = __salt__[mine_func](*m_data[func])
else:
if not _mine_function_available(func):
continue
data[func] = __salt__[func]()
except Exception:
trace = traceback.format_exc()
log.error('Function %s in mine_functions failed to execute', func)
log.debug('Error: %s', trace)
continue
if __opts__['file_client'] == 'local':
if not clear:
old = __salt__['data.get']('mine_cache')
if isinstance(old, dict):
old.update(data)
data = old
return __salt__['data.update']('mine_cache', data)
load = {
'cmd': '_mine',
'data': data,
'id': __opts__['id'],
'clear': clear,
}
return _mine_send(load, __opts__)
def send(func, *args, **kwargs):
'''
Send a specific function to the mine.
CLI Example:
.. code-block:: bash
salt '*' mine.send network.ip_addrs eth0
salt '*' mine.send eth0_ip_addrs mine_function=network.ip_addrs eth0
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
mine_func = kwargs.pop('mine_function', func)
if mine_func not in __salt__:
return False
data = {}
arg_data = salt.utils.args.arg_lookup(__salt__[mine_func])
func_data = copy.deepcopy(kwargs)
for ind, _ in enumerate(arg_data.get('args', [])):
try:
func_data[arg_data['args'][ind]] = args[ind]
except IndexError:
# Safe error, arg may be in kwargs
pass
f_call = salt.utils.args.format_call(
__salt__[mine_func],
func_data,
expected_extra_kws=MINE_INTERNAL_KEYWORDS)
for arg in args:
if arg not in f_call['args']:
f_call['args'].append(arg)
try:
if 'kwargs' in f_call:
data[func] = __salt__[mine_func](*f_call['args'], **f_call['kwargs'])
else:
data[func] = __salt__[mine_func](*f_call['args'])
except Exception as exc:
log.error('Function %s in mine.send failed to execute: %s',
mine_func, exc)
return False
if __opts__['file_client'] == 'local':
old = __salt__['data.get']('mine_cache')
if isinstance(old, dict):
old.update(data)
data = old
return __salt__['data.update']('mine_cache', data)
load = {
'cmd': '_mine',
'data': data,
'id': __opts__['id'],
}
return _mine_send(load, __opts__)
def delete(fun):
'''
Remove specific function contents of minion. Returns True on success.
CLI Example:
.. code-block:: bash
salt '*' mine.delete 'network.interfaces'
'''
if __opts__['file_client'] == 'local':
data = __salt__['data.get']('mine_cache')
if isinstance(data, dict) and fun in data:
del data[fun]
return __salt__['data.update']('mine_cache', data)
load = {
'cmd': '_mine_delete',
'id': __opts__['id'],
'fun': fun,
}
return _mine_send(load, __opts__)
def flush():
'''
Remove all mine contents of minion. Returns True on success.
CLI Example:
.. code-block:: bash
salt '*' mine.flush
'''
if __opts__['file_client'] == 'local':
return __salt__['data.update']('mine_cache', {})
load = {
'cmd': '_mine_flush',
'id': __opts__['id'],
}
return _mine_send(load, __opts__)
def get_docker(interfaces=None, cidrs=None, with_container_id=False):
'''
.. versionchanged:: 2017.7.8,2018.3.3
When :conf_minion:`docker.update_mine` is set to ``False`` for a given
minion, no mine data will be populated for that minion, and thus none
will be returned for it.
.. versionchanged:: 2019.2.0
:conf_minion:`docker.update_mine` now defaults to ``False``
Get all mine data for :py:func:`docker.ps <salt.modules.dockermod.ps_>` and
run an aggregation routine. The ``interfaces`` parameter allows for
specifying the network interfaces from which to select IP addresses. The
``cidrs`` parameter allows for specifying a list of subnets which the IP
address must match.
with_container_id
Boolean, to expose container_id in the list of results
.. versionadded:: 2015.8.2
CLI Example:
.. code-block:: bash
salt '*' mine.get_docker
salt '*' mine.get_docker interfaces='eth0'
salt '*' mine.get_docker interfaces='["eth0", "eth1"]'
salt '*' mine.get_docker cidrs='107.170.147.0/24'
salt '*' mine.get_docker cidrs='["107.170.147.0/24", "172.17.42.0/24"]'
salt '*' mine.get_docker interfaces='["eth0", "eth1"]' cidrs='["107.170.147.0/24", "172.17.42.0/24"]'
'''
# Enforce that interface and cidr are lists
if interfaces:
interface_ = []
interface_.extend(interfaces if isinstance(interfaces, list) else [interfaces])
interfaces = interface_
if cidrs:
cidr_ = []
cidr_.extend(cidrs if isinstance(cidrs, list) else [cidrs])
cidrs = cidr_
# Get docker info
cmd = 'docker.ps'
docker_hosts = get('*', cmd)
proxy_lists = {}
# Process docker info
for containers in six.itervalues(docker_hosts):
host = containers.pop('host')
host_ips = []
# Prepare host_ips list
if not interfaces:
for info in six.itervalues(host['interfaces']):
if 'inet' in info:
for ip_ in info['inet']:
host_ips.append(ip_['address'])
else:
for interface in interfaces:
if interface in host['interfaces']:
if 'inet' in host['interfaces'][interface]:
for item in host['interfaces'][interface]['inet']:
host_ips.append(item['address'])
host_ips = list(set(host_ips))
# Filter out ips from host_ips with cidrs
if cidrs:
good_ips = []
for cidr in cidrs:
for ip_ in host_ips:
if salt.utils.network.in_subnet(cidr, [ip_]):
good_ips.append(ip_)
host_ips = list(set(good_ips))
# Process each container
for container in six.itervalues(containers):
container_id = container['Info']['Id']
if container['Image'] not in proxy_lists:
proxy_lists[container['Image']] = {}
for dock_port in container['Ports']:
# IP exists only if port is exposed
ip_address = dock_port.get('IP')
# If port is 0.0.0.0, then we must get the docker host IP
if ip_address == '0.0.0.0':
for ip_ in host_ips:
containers = proxy_lists[container['Image']].setdefault('ipv4', {}).setdefault(dock_port['PrivatePort'], [])
container_network_footprint = '{0}:{1}'.format(ip_, dock_port['PublicPort'])
if with_container_id:
value = (container_network_footprint, container_id)
else:
value = container_network_footprint
if value not in containers:
containers.append(value)
elif ip_address:
containers = proxy_lists[container['Image']].setdefault('ipv4', {}).setdefault(dock_port['PrivatePort'], [])
container_network_footprint = '{0}:{1}'.format(dock_port['IP'], dock_port['PublicPort'])
if with_container_id:
value = (container_network_footprint, container_id)
else:
value = container_network_footprint
if value not in containers:
containers.append(value)
return proxy_lists
def valid():
'''
List valid entries in mine configuration.
CLI Example:
.. code-block:: bash
salt '*' mine.valid
'''
m_data = __salt__['config.merge']('mine_functions', {})
# If we don't have any mine functions configured, then we should just bail out
if not m_data:
return
data = {}
for func in m_data:
if m_data[func] and isinstance(m_data[func], dict):
mine_func = m_data[func].pop('mine_function', func)
if not _mine_function_available(mine_func):
continue
data[func] = {mine_func: m_data[func]}
elif m_data[func] and isinstance(m_data[func], list):
mine_func = func
if isinstance(m_data[func][0], dict) and 'mine_function' in m_data[func][0]:
mine_func = m_data[func][0]['mine_function']
m_data[func].pop(0)
if not _mine_function_available(mine_func):
continue
data[func] = {mine_func: m_data[func]}
else:
if not _mine_function_available(func):
continue
data[func] = m_data[func]
return data
|
saltstack/salt
|
salt/modules/mine.py
|
delete
|
python
|
def delete(fun):
'''
Remove specific function contents of minion. Returns True on success.
CLI Example:
.. code-block:: bash
salt '*' mine.delete 'network.interfaces'
'''
if __opts__['file_client'] == 'local':
data = __salt__['data.get']('mine_cache')
if isinstance(data, dict) and fun in data:
del data[fun]
return __salt__['data.update']('mine_cache', data)
load = {
'cmd': '_mine_delete',
'id': __opts__['id'],
'fun': fun,
}
return _mine_send(load, __opts__)
|
Remove specific function contents of minion. Returns True on success.
CLI Example:
.. code-block:: bash
salt '*' mine.delete 'network.interfaces'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mine.py#L342-L362
|
[
"def _mine_send(load, opts):\n eventer = salt.utils.event.MinionEvent(opts, listen=False)\n event_ret = eventer.fire_event(load, '_minion_mine')\n # We need to pause here to allow for the decoupled nature of\n # events time to allow the mine to propagate\n time.sleep(0.5)\n return event_ret\n"
] |
# -*- coding: utf-8 -*-
'''
The function cache system allows for data to be stored on the master so it can be easily read by other minions
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import time
import traceback
# Import salt libs
import salt.crypt
import salt.payload
import salt.utils.args
import salt.utils.event
import salt.utils.network
import salt.transport.client
from salt.exceptions import SaltClientError
# Import 3rd-party libs
from salt.ext import six
MINE_INTERNAL_KEYWORDS = frozenset([
'__pub_user',
'__pub_arg',
'__pub_fun',
'__pub_jid',
'__pub_tgt',
'__pub_tgt_type',
'__pub_ret'
])
__proxyenabled__ = ['*']
log = logging.getLogger(__name__)
def _auth():
'''
Return the auth object
'''
if 'auth' not in __context__:
try:
__context__['auth'] = salt.crypt.SAuth(__opts__)
except SaltClientError:
log.error('Could not authenticate with master.'
'Mine data will not be transmitted.')
return __context__['auth']
def _mine_function_available(func):
if func not in __salt__:
log.error('Function %s in mine_functions not available', func)
return False
return True
def _mine_send(load, opts):
eventer = salt.utils.event.MinionEvent(opts, listen=False)
event_ret = eventer.fire_event(load, '_minion_mine')
# We need to pause here to allow for the decoupled nature of
# events time to allow the mine to propagate
time.sleep(0.5)
return event_ret
def _mine_get(load, opts):
if opts.get('transport', '') in ('zeromq', 'tcp'):
try:
load['tok'] = _auth().gen_token(b'salt')
except AttributeError:
log.error('Mine could not authenticate with master. '
'Mine could not be retrieved.'
)
return False
channel = salt.transport.client.ReqChannel.factory(opts)
try:
ret = channel.send(load)
finally:
channel.close()
return ret
def update(clear=False, mine_functions=None):
'''
Execute the configured functions and send the data back up to the master.
The functions to be executed are merged from the master config, pillar and
minion config under the option `mine_functions`:
.. code-block:: yaml
mine_functions:
network.ip_addrs:
- eth0
disk.usage: []
This function accepts the following arguments:
clear: False
Boolean flag specifying whether updating will clear the existing
mines, or will update. Default: `False` (update).
mine_functions
Update the mine data on certain functions only.
This feature can be used when updating the mine for functions
that require refresh at different intervals than the rest of
the functions specified under `mine_functions` in the
minion/master config or pillar.
A potential use would be together with the `scheduler`, for example:
.. code-block:: yaml
schedule:
lldp_mine_update:
function: mine.update
kwargs:
mine_functions:
net.lldp: []
hours: 12
In the example above, the mine for `net.lldp` would be refreshed
every 12 hours, while `network.ip_addrs` would continue to be updated
as specified in `mine_interval`.
The function cache will be populated with information from executing these
functions
CLI Example:
.. code-block:: bash
salt '*' mine.update
'''
m_data = {}
if not mine_functions:
m_data = __salt__['config.merge']('mine_functions', {})
# If we don't have any mine functions configured, then we should just bail out
if not m_data:
return
elif mine_functions and isinstance(mine_functions, list):
m_data = dict((fun, {}) for fun in mine_functions)
elif mine_functions and isinstance(mine_functions, dict):
m_data = mine_functions
else:
return
data = {}
for func in m_data:
try:
if m_data[func] and isinstance(m_data[func], dict):
mine_func = m_data[func].pop('mine_function', func)
if not _mine_function_available(mine_func):
continue
data[func] = __salt__[mine_func](**m_data[func])
elif m_data[func] and isinstance(m_data[func], list):
mine_func = func
if isinstance(m_data[func][0], dict) and 'mine_function' in m_data[func][0]:
mine_func = m_data[func][0]['mine_function']
m_data[func].pop(0)
if not _mine_function_available(mine_func):
continue
data[func] = __salt__[mine_func](*m_data[func])
else:
if not _mine_function_available(func):
continue
data[func] = __salt__[func]()
except Exception:
trace = traceback.format_exc()
log.error('Function %s in mine_functions failed to execute', func)
log.debug('Error: %s', trace)
continue
if __opts__['file_client'] == 'local':
if not clear:
old = __salt__['data.get']('mine_cache')
if isinstance(old, dict):
old.update(data)
data = old
return __salt__['data.update']('mine_cache', data)
load = {
'cmd': '_mine',
'data': data,
'id': __opts__['id'],
'clear': clear,
}
return _mine_send(load, __opts__)
def send(func, *args, **kwargs):
'''
Send a specific function to the mine.
CLI Example:
.. code-block:: bash
salt '*' mine.send network.ip_addrs eth0
salt '*' mine.send eth0_ip_addrs mine_function=network.ip_addrs eth0
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
mine_func = kwargs.pop('mine_function', func)
if mine_func not in __salt__:
return False
data = {}
arg_data = salt.utils.args.arg_lookup(__salt__[mine_func])
func_data = copy.deepcopy(kwargs)
for ind, _ in enumerate(arg_data.get('args', [])):
try:
func_data[arg_data['args'][ind]] = args[ind]
except IndexError:
# Safe error, arg may be in kwargs
pass
f_call = salt.utils.args.format_call(
__salt__[mine_func],
func_data,
expected_extra_kws=MINE_INTERNAL_KEYWORDS)
for arg in args:
if arg not in f_call['args']:
f_call['args'].append(arg)
try:
if 'kwargs' in f_call:
data[func] = __salt__[mine_func](*f_call['args'], **f_call['kwargs'])
else:
data[func] = __salt__[mine_func](*f_call['args'])
except Exception as exc:
log.error('Function %s in mine.send failed to execute: %s',
mine_func, exc)
return False
if __opts__['file_client'] == 'local':
old = __salt__['data.get']('mine_cache')
if isinstance(old, dict):
old.update(data)
data = old
return __salt__['data.update']('mine_cache', data)
load = {
'cmd': '_mine',
'data': data,
'id': __opts__['id'],
}
return _mine_send(load, __opts__)
def get(tgt,
fun,
tgt_type='glob',
exclude_minion=False):
'''
Get data from the mine based on the target, function and tgt_type
Targets can be matched based on any standard matching system that can be
matched on the master via these keywords:
- glob
- pcre
- grain
- grain_pcre
- compound
- pillar
- pillar_pcre
Note that all pillar matches, whether using the compound matching system or
the pillar matching system, will be exact matches, with globbing disabled.
exclude_minion
Excludes the current minion from the result set
CLI Example:
.. code-block:: bash
salt '*' mine.get '*' network.interfaces
salt '*' mine.get '*' network.interfaces,network.ipaddrs
salt '*' mine.get '*' '["network.interfaces", "network.ipaddrs"]'
salt '*' mine.get 'os:Fedora' network.interfaces grain
salt '*' mine.get 'G@os:Fedora and S@192.168.5.0/24' network.ipaddrs compound
.. seealso:: Retrieving Mine data from Pillar and Orchestrate
This execution module is intended to be executed on minions.
Master-side operations such as Pillar or Orchestrate that require Mine
data should use the :py:mod:`Mine Runner module <salt.runners.mine>`
instead; it can be invoked from a Pillar SLS file using the
:py:func:`saltutil.runner <salt.modules.saltutil.runner>` module. For
example:
.. code-block:: jinja
{% set minion_ips = salt.saltutil.runner('mine.get',
tgt='*',
fun='network.ip_addrs',
tgt_type='glob') %}
'''
if __opts__['file_client'] == 'local':
ret = {}
is_target = {'glob': __salt__['match.glob'],
'pcre': __salt__['match.pcre'],
'list': __salt__['match.list'],
'grain': __salt__['match.grain'],
'grain_pcre': __salt__['match.grain_pcre'],
'ipcidr': __salt__['match.ipcidr'],
'compound': __salt__['match.compound'],
'pillar': __salt__['match.pillar'],
'pillar_pcre': __salt__['match.pillar_pcre'],
}[tgt_type](tgt)
if is_target:
data = __salt__['data.get']('mine_cache')
if isinstance(data, dict):
if isinstance(fun, six.string_types):
functions = list(set(fun.split(',')))
_ret_dict = len(functions) > 1
elif isinstance(fun, list):
functions = fun
_ret_dict = True
else:
return {}
if not _ret_dict and functions and functions[0] in data:
ret[__opts__['id']] = data.get(functions)
elif _ret_dict:
for fun in functions:
if fun in data:
ret.setdefault(fun, {})[__opts__['id']] = data.get(fun)
return ret
load = {
'cmd': '_mine_get',
'id': __opts__['id'],
'tgt': tgt,
'fun': fun,
'tgt_type': tgt_type,
}
ret = _mine_get(load, __opts__)
if exclude_minion:
if __opts__['id'] in ret:
del ret[__opts__['id']]
return ret
def flush():
'''
Remove all mine contents of minion. Returns True on success.
CLI Example:
.. code-block:: bash
salt '*' mine.flush
'''
if __opts__['file_client'] == 'local':
return __salt__['data.update']('mine_cache', {})
load = {
'cmd': '_mine_flush',
'id': __opts__['id'],
}
return _mine_send(load, __opts__)
def get_docker(interfaces=None, cidrs=None, with_container_id=False):
'''
.. versionchanged:: 2017.7.8,2018.3.3
When :conf_minion:`docker.update_mine` is set to ``False`` for a given
minion, no mine data will be populated for that minion, and thus none
will be returned for it.
.. versionchanged:: 2019.2.0
:conf_minion:`docker.update_mine` now defaults to ``False``
Get all mine data for :py:func:`docker.ps <salt.modules.dockermod.ps_>` and
run an aggregation routine. The ``interfaces`` parameter allows for
specifying the network interfaces from which to select IP addresses. The
``cidrs`` parameter allows for specifying a list of subnets which the IP
address must match.
with_container_id
Boolean, to expose container_id in the list of results
.. versionadded:: 2015.8.2
CLI Example:
.. code-block:: bash
salt '*' mine.get_docker
salt '*' mine.get_docker interfaces='eth0'
salt '*' mine.get_docker interfaces='["eth0", "eth1"]'
salt '*' mine.get_docker cidrs='107.170.147.0/24'
salt '*' mine.get_docker cidrs='["107.170.147.0/24", "172.17.42.0/24"]'
salt '*' mine.get_docker interfaces='["eth0", "eth1"]' cidrs='["107.170.147.0/24", "172.17.42.0/24"]'
'''
# Enforce that interface and cidr are lists
if interfaces:
interface_ = []
interface_.extend(interfaces if isinstance(interfaces, list) else [interfaces])
interfaces = interface_
if cidrs:
cidr_ = []
cidr_.extend(cidrs if isinstance(cidrs, list) else [cidrs])
cidrs = cidr_
# Get docker info
cmd = 'docker.ps'
docker_hosts = get('*', cmd)
proxy_lists = {}
# Process docker info
for containers in six.itervalues(docker_hosts):
host = containers.pop('host')
host_ips = []
# Prepare host_ips list
if not interfaces:
for info in six.itervalues(host['interfaces']):
if 'inet' in info:
for ip_ in info['inet']:
host_ips.append(ip_['address'])
else:
for interface in interfaces:
if interface in host['interfaces']:
if 'inet' in host['interfaces'][interface]:
for item in host['interfaces'][interface]['inet']:
host_ips.append(item['address'])
host_ips = list(set(host_ips))
# Filter out ips from host_ips with cidrs
if cidrs:
good_ips = []
for cidr in cidrs:
for ip_ in host_ips:
if salt.utils.network.in_subnet(cidr, [ip_]):
good_ips.append(ip_)
host_ips = list(set(good_ips))
# Process each container
for container in six.itervalues(containers):
container_id = container['Info']['Id']
if container['Image'] not in proxy_lists:
proxy_lists[container['Image']] = {}
for dock_port in container['Ports']:
# IP exists only if port is exposed
ip_address = dock_port.get('IP')
# If port is 0.0.0.0, then we must get the docker host IP
if ip_address == '0.0.0.0':
for ip_ in host_ips:
containers = proxy_lists[container['Image']].setdefault('ipv4', {}).setdefault(dock_port['PrivatePort'], [])
container_network_footprint = '{0}:{1}'.format(ip_, dock_port['PublicPort'])
if with_container_id:
value = (container_network_footprint, container_id)
else:
value = container_network_footprint
if value not in containers:
containers.append(value)
elif ip_address:
containers = proxy_lists[container['Image']].setdefault('ipv4', {}).setdefault(dock_port['PrivatePort'], [])
container_network_footprint = '{0}:{1}'.format(dock_port['IP'], dock_port['PublicPort'])
if with_container_id:
value = (container_network_footprint, container_id)
else:
value = container_network_footprint
if value not in containers:
containers.append(value)
return proxy_lists
def valid():
'''
List valid entries in mine configuration.
CLI Example:
.. code-block:: bash
salt '*' mine.valid
'''
m_data = __salt__['config.merge']('mine_functions', {})
# If we don't have any mine functions configured, then we should just bail out
if not m_data:
return
data = {}
for func in m_data:
if m_data[func] and isinstance(m_data[func], dict):
mine_func = m_data[func].pop('mine_function', func)
if not _mine_function_available(mine_func):
continue
data[func] = {mine_func: m_data[func]}
elif m_data[func] and isinstance(m_data[func], list):
mine_func = func
if isinstance(m_data[func][0], dict) and 'mine_function' in m_data[func][0]:
mine_func = m_data[func][0]['mine_function']
m_data[func].pop(0)
if not _mine_function_available(mine_func):
continue
data[func] = {mine_func: m_data[func]}
else:
if not _mine_function_available(func):
continue
data[func] = m_data[func]
return data
|
saltstack/salt
|
salt/modules/mine.py
|
get_docker
|
python
|
def get_docker(interfaces=None, cidrs=None, with_container_id=False):
'''
.. versionchanged:: 2017.7.8,2018.3.3
When :conf_minion:`docker.update_mine` is set to ``False`` for a given
minion, no mine data will be populated for that minion, and thus none
will be returned for it.
.. versionchanged:: 2019.2.0
:conf_minion:`docker.update_mine` now defaults to ``False``
Get all mine data for :py:func:`docker.ps <salt.modules.dockermod.ps_>` and
run an aggregation routine. The ``interfaces`` parameter allows for
specifying the network interfaces from which to select IP addresses. The
``cidrs`` parameter allows for specifying a list of subnets which the IP
address must match.
with_container_id
Boolean, to expose container_id in the list of results
.. versionadded:: 2015.8.2
CLI Example:
.. code-block:: bash
salt '*' mine.get_docker
salt '*' mine.get_docker interfaces='eth0'
salt '*' mine.get_docker interfaces='["eth0", "eth1"]'
salt '*' mine.get_docker cidrs='107.170.147.0/24'
salt '*' mine.get_docker cidrs='["107.170.147.0/24", "172.17.42.0/24"]'
salt '*' mine.get_docker interfaces='["eth0", "eth1"]' cidrs='["107.170.147.0/24", "172.17.42.0/24"]'
'''
# Enforce that interface and cidr are lists
if interfaces:
interface_ = []
interface_.extend(interfaces if isinstance(interfaces, list) else [interfaces])
interfaces = interface_
if cidrs:
cidr_ = []
cidr_.extend(cidrs if isinstance(cidrs, list) else [cidrs])
cidrs = cidr_
# Get docker info
cmd = 'docker.ps'
docker_hosts = get('*', cmd)
proxy_lists = {}
# Process docker info
for containers in six.itervalues(docker_hosts):
host = containers.pop('host')
host_ips = []
# Prepare host_ips list
if not interfaces:
for info in six.itervalues(host['interfaces']):
if 'inet' in info:
for ip_ in info['inet']:
host_ips.append(ip_['address'])
else:
for interface in interfaces:
if interface in host['interfaces']:
if 'inet' in host['interfaces'][interface]:
for item in host['interfaces'][interface]['inet']:
host_ips.append(item['address'])
host_ips = list(set(host_ips))
# Filter out ips from host_ips with cidrs
if cidrs:
good_ips = []
for cidr in cidrs:
for ip_ in host_ips:
if salt.utils.network.in_subnet(cidr, [ip_]):
good_ips.append(ip_)
host_ips = list(set(good_ips))
# Process each container
for container in six.itervalues(containers):
container_id = container['Info']['Id']
if container['Image'] not in proxy_lists:
proxy_lists[container['Image']] = {}
for dock_port in container['Ports']:
# IP exists only if port is exposed
ip_address = dock_port.get('IP')
# If port is 0.0.0.0, then we must get the docker host IP
if ip_address == '0.0.0.0':
for ip_ in host_ips:
containers = proxy_lists[container['Image']].setdefault('ipv4', {}).setdefault(dock_port['PrivatePort'], [])
container_network_footprint = '{0}:{1}'.format(ip_, dock_port['PublicPort'])
if with_container_id:
value = (container_network_footprint, container_id)
else:
value = container_network_footprint
if value not in containers:
containers.append(value)
elif ip_address:
containers = proxy_lists[container['Image']].setdefault('ipv4', {}).setdefault(dock_port['PrivatePort'], [])
container_network_footprint = '{0}:{1}'.format(dock_port['IP'], dock_port['PublicPort'])
if with_container_id:
value = (container_network_footprint, container_id)
else:
value = container_network_footprint
if value not in containers:
containers.append(value)
return proxy_lists
|
.. versionchanged:: 2017.7.8,2018.3.3
When :conf_minion:`docker.update_mine` is set to ``False`` for a given
minion, no mine data will be populated for that minion, and thus none
will be returned for it.
.. versionchanged:: 2019.2.0
:conf_minion:`docker.update_mine` now defaults to ``False``
Get all mine data for :py:func:`docker.ps <salt.modules.dockermod.ps_>` and
run an aggregation routine. The ``interfaces`` parameter allows for
specifying the network interfaces from which to select IP addresses. The
``cidrs`` parameter allows for specifying a list of subnets which the IP
address must match.
with_container_id
Boolean, to expose container_id in the list of results
.. versionadded:: 2015.8.2
CLI Example:
.. code-block:: bash
salt '*' mine.get_docker
salt '*' mine.get_docker interfaces='eth0'
salt '*' mine.get_docker interfaces='["eth0", "eth1"]'
salt '*' mine.get_docker cidrs='107.170.147.0/24'
salt '*' mine.get_docker cidrs='["107.170.147.0/24", "172.17.42.0/24"]'
salt '*' mine.get_docker interfaces='["eth0", "eth1"]' cidrs='["107.170.147.0/24", "172.17.42.0/24"]'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mine.py#L384-L489
|
[
"def get(tgt,\n fun,\n tgt_type='glob',\n exclude_minion=False):\n '''\n Get data from the mine based on the target, function and tgt_type\n\n Targets can be matched based on any standard matching system that can be\n matched on the master via these keywords:\n\n - glob\n - pcre\n - grain\n - grain_pcre\n - compound\n - pillar\n - pillar_pcre\n\n Note that all pillar matches, whether using the compound matching system or\n the pillar matching system, will be exact matches, with globbing disabled.\n\n exclude_minion\n Excludes the current minion from the result set\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' mine.get '*' network.interfaces\n salt '*' mine.get '*' network.interfaces,network.ipaddrs\n salt '*' mine.get '*' '[\"network.interfaces\", \"network.ipaddrs\"]'\n salt '*' mine.get 'os:Fedora' network.interfaces grain\n salt '*' mine.get 'G@os:Fedora and S@192.168.5.0/24' network.ipaddrs compound\n\n .. seealso:: Retrieving Mine data from Pillar and Orchestrate\n\n This execution module is intended to be executed on minions.\n Master-side operations such as Pillar or Orchestrate that require Mine\n data should use the :py:mod:`Mine Runner module <salt.runners.mine>`\n instead; it can be invoked from a Pillar SLS file using the\n :py:func:`saltutil.runner <salt.modules.saltutil.runner>` module. For\n example:\n\n .. code-block:: jinja\n\n {% set minion_ips = salt.saltutil.runner('mine.get',\n tgt='*',\n fun='network.ip_addrs',\n tgt_type='glob') %}\n '''\n if __opts__['file_client'] == 'local':\n ret = {}\n is_target = {'glob': __salt__['match.glob'],\n 'pcre': __salt__['match.pcre'],\n 'list': __salt__['match.list'],\n 'grain': __salt__['match.grain'],\n 'grain_pcre': __salt__['match.grain_pcre'],\n 'ipcidr': __salt__['match.ipcidr'],\n 'compound': __salt__['match.compound'],\n 'pillar': __salt__['match.pillar'],\n 'pillar_pcre': __salt__['match.pillar_pcre'],\n }[tgt_type](tgt)\n if is_target:\n data = __salt__['data.get']('mine_cache')\n\n if isinstance(data, dict):\n if isinstance(fun, six.string_types):\n functions = list(set(fun.split(',')))\n _ret_dict = len(functions) > 1\n elif isinstance(fun, list):\n functions = fun\n _ret_dict = True\n else:\n return {}\n\n if not _ret_dict and functions and functions[0] in data:\n ret[__opts__['id']] = data.get(functions)\n elif _ret_dict:\n for fun in functions:\n if fun in data:\n ret.setdefault(fun, {})[__opts__['id']] = data.get(fun)\n\n return ret\n load = {\n 'cmd': '_mine_get',\n 'id': __opts__['id'],\n 'tgt': tgt,\n 'fun': fun,\n 'tgt_type': tgt_type,\n }\n ret = _mine_get(load, __opts__)\n if exclude_minion:\n if __opts__['id'] in ret:\n del ret[__opts__['id']]\n return ret\n",
"def itervalues(d, **kw):\n return d.itervalues(**kw)\n",
"def in_subnet(cidr, addr=None):\n '''\n Returns True if host or (any of) addrs is within specified subnet, otherwise False\n '''\n try:\n cidr = ipaddress.ip_network(cidr)\n except ValueError:\n log.error('Invalid CIDR \\'%s\\'', cidr)\n return False\n\n if addr is None:\n addr = ip_addrs()\n addr.extend(ip_addrs6())\n elif not isinstance(addr, (list, tuple)):\n addr = (addr,)\n\n return any(ipaddress.ip_address(item) in cidr for item in addr)\n"
] |
# -*- coding: utf-8 -*-
'''
The function cache system allows for data to be stored on the master so it can be easily read by other minions
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import time
import traceback
# Import salt libs
import salt.crypt
import salt.payload
import salt.utils.args
import salt.utils.event
import salt.utils.network
import salt.transport.client
from salt.exceptions import SaltClientError
# Import 3rd-party libs
from salt.ext import six
MINE_INTERNAL_KEYWORDS = frozenset([
'__pub_user',
'__pub_arg',
'__pub_fun',
'__pub_jid',
'__pub_tgt',
'__pub_tgt_type',
'__pub_ret'
])
__proxyenabled__ = ['*']
log = logging.getLogger(__name__)
def _auth():
'''
Return the auth object
'''
if 'auth' not in __context__:
try:
__context__['auth'] = salt.crypt.SAuth(__opts__)
except SaltClientError:
log.error('Could not authenticate with master.'
'Mine data will not be transmitted.')
return __context__['auth']
def _mine_function_available(func):
if func not in __salt__:
log.error('Function %s in mine_functions not available', func)
return False
return True
def _mine_send(load, opts):
eventer = salt.utils.event.MinionEvent(opts, listen=False)
event_ret = eventer.fire_event(load, '_minion_mine')
# We need to pause here to allow for the decoupled nature of
# events time to allow the mine to propagate
time.sleep(0.5)
return event_ret
def _mine_get(load, opts):
if opts.get('transport', '') in ('zeromq', 'tcp'):
try:
load['tok'] = _auth().gen_token(b'salt')
except AttributeError:
log.error('Mine could not authenticate with master. '
'Mine could not be retrieved.'
)
return False
channel = salt.transport.client.ReqChannel.factory(opts)
try:
ret = channel.send(load)
finally:
channel.close()
return ret
def update(clear=False, mine_functions=None):
'''
Execute the configured functions and send the data back up to the master.
The functions to be executed are merged from the master config, pillar and
minion config under the option `mine_functions`:
.. code-block:: yaml
mine_functions:
network.ip_addrs:
- eth0
disk.usage: []
This function accepts the following arguments:
clear: False
Boolean flag specifying whether updating will clear the existing
mines, or will update. Default: `False` (update).
mine_functions
Update the mine data on certain functions only.
This feature can be used when updating the mine for functions
that require refresh at different intervals than the rest of
the functions specified under `mine_functions` in the
minion/master config or pillar.
A potential use would be together with the `scheduler`, for example:
.. code-block:: yaml
schedule:
lldp_mine_update:
function: mine.update
kwargs:
mine_functions:
net.lldp: []
hours: 12
In the example above, the mine for `net.lldp` would be refreshed
every 12 hours, while `network.ip_addrs` would continue to be updated
as specified in `mine_interval`.
The function cache will be populated with information from executing these
functions
CLI Example:
.. code-block:: bash
salt '*' mine.update
'''
m_data = {}
if not mine_functions:
m_data = __salt__['config.merge']('mine_functions', {})
# If we don't have any mine functions configured, then we should just bail out
if not m_data:
return
elif mine_functions and isinstance(mine_functions, list):
m_data = dict((fun, {}) for fun in mine_functions)
elif mine_functions and isinstance(mine_functions, dict):
m_data = mine_functions
else:
return
data = {}
for func in m_data:
try:
if m_data[func] and isinstance(m_data[func], dict):
mine_func = m_data[func].pop('mine_function', func)
if not _mine_function_available(mine_func):
continue
data[func] = __salt__[mine_func](**m_data[func])
elif m_data[func] and isinstance(m_data[func], list):
mine_func = func
if isinstance(m_data[func][0], dict) and 'mine_function' in m_data[func][0]:
mine_func = m_data[func][0]['mine_function']
m_data[func].pop(0)
if not _mine_function_available(mine_func):
continue
data[func] = __salt__[mine_func](*m_data[func])
else:
if not _mine_function_available(func):
continue
data[func] = __salt__[func]()
except Exception:
trace = traceback.format_exc()
log.error('Function %s in mine_functions failed to execute', func)
log.debug('Error: %s', trace)
continue
if __opts__['file_client'] == 'local':
if not clear:
old = __salt__['data.get']('mine_cache')
if isinstance(old, dict):
old.update(data)
data = old
return __salt__['data.update']('mine_cache', data)
load = {
'cmd': '_mine',
'data': data,
'id': __opts__['id'],
'clear': clear,
}
return _mine_send(load, __opts__)
def send(func, *args, **kwargs):
'''
Send a specific function to the mine.
CLI Example:
.. code-block:: bash
salt '*' mine.send network.ip_addrs eth0
salt '*' mine.send eth0_ip_addrs mine_function=network.ip_addrs eth0
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
mine_func = kwargs.pop('mine_function', func)
if mine_func not in __salt__:
return False
data = {}
arg_data = salt.utils.args.arg_lookup(__salt__[mine_func])
func_data = copy.deepcopy(kwargs)
for ind, _ in enumerate(arg_data.get('args', [])):
try:
func_data[arg_data['args'][ind]] = args[ind]
except IndexError:
# Safe error, arg may be in kwargs
pass
f_call = salt.utils.args.format_call(
__salt__[mine_func],
func_data,
expected_extra_kws=MINE_INTERNAL_KEYWORDS)
for arg in args:
if arg not in f_call['args']:
f_call['args'].append(arg)
try:
if 'kwargs' in f_call:
data[func] = __salt__[mine_func](*f_call['args'], **f_call['kwargs'])
else:
data[func] = __salt__[mine_func](*f_call['args'])
except Exception as exc:
log.error('Function %s in mine.send failed to execute: %s',
mine_func, exc)
return False
if __opts__['file_client'] == 'local':
old = __salt__['data.get']('mine_cache')
if isinstance(old, dict):
old.update(data)
data = old
return __salt__['data.update']('mine_cache', data)
load = {
'cmd': '_mine',
'data': data,
'id': __opts__['id'],
}
return _mine_send(load, __opts__)
def get(tgt,
fun,
tgt_type='glob',
exclude_minion=False):
'''
Get data from the mine based on the target, function and tgt_type
Targets can be matched based on any standard matching system that can be
matched on the master via these keywords:
- glob
- pcre
- grain
- grain_pcre
- compound
- pillar
- pillar_pcre
Note that all pillar matches, whether using the compound matching system or
the pillar matching system, will be exact matches, with globbing disabled.
exclude_minion
Excludes the current minion from the result set
CLI Example:
.. code-block:: bash
salt '*' mine.get '*' network.interfaces
salt '*' mine.get '*' network.interfaces,network.ipaddrs
salt '*' mine.get '*' '["network.interfaces", "network.ipaddrs"]'
salt '*' mine.get 'os:Fedora' network.interfaces grain
salt '*' mine.get 'G@os:Fedora and S@192.168.5.0/24' network.ipaddrs compound
.. seealso:: Retrieving Mine data from Pillar and Orchestrate
This execution module is intended to be executed on minions.
Master-side operations such as Pillar or Orchestrate that require Mine
data should use the :py:mod:`Mine Runner module <salt.runners.mine>`
instead; it can be invoked from a Pillar SLS file using the
:py:func:`saltutil.runner <salt.modules.saltutil.runner>` module. For
example:
.. code-block:: jinja
{% set minion_ips = salt.saltutil.runner('mine.get',
tgt='*',
fun='network.ip_addrs',
tgt_type='glob') %}
'''
if __opts__['file_client'] == 'local':
ret = {}
is_target = {'glob': __salt__['match.glob'],
'pcre': __salt__['match.pcre'],
'list': __salt__['match.list'],
'grain': __salt__['match.grain'],
'grain_pcre': __salt__['match.grain_pcre'],
'ipcidr': __salt__['match.ipcidr'],
'compound': __salt__['match.compound'],
'pillar': __salt__['match.pillar'],
'pillar_pcre': __salt__['match.pillar_pcre'],
}[tgt_type](tgt)
if is_target:
data = __salt__['data.get']('mine_cache')
if isinstance(data, dict):
if isinstance(fun, six.string_types):
functions = list(set(fun.split(',')))
_ret_dict = len(functions) > 1
elif isinstance(fun, list):
functions = fun
_ret_dict = True
else:
return {}
if not _ret_dict and functions and functions[0] in data:
ret[__opts__['id']] = data.get(functions)
elif _ret_dict:
for fun in functions:
if fun in data:
ret.setdefault(fun, {})[__opts__['id']] = data.get(fun)
return ret
load = {
'cmd': '_mine_get',
'id': __opts__['id'],
'tgt': tgt,
'fun': fun,
'tgt_type': tgt_type,
}
ret = _mine_get(load, __opts__)
if exclude_minion:
if __opts__['id'] in ret:
del ret[__opts__['id']]
return ret
def delete(fun):
'''
Remove specific function contents of minion. Returns True on success.
CLI Example:
.. code-block:: bash
salt '*' mine.delete 'network.interfaces'
'''
if __opts__['file_client'] == 'local':
data = __salt__['data.get']('mine_cache')
if isinstance(data, dict) and fun in data:
del data[fun]
return __salt__['data.update']('mine_cache', data)
load = {
'cmd': '_mine_delete',
'id': __opts__['id'],
'fun': fun,
}
return _mine_send(load, __opts__)
def flush():
'''
Remove all mine contents of minion. Returns True on success.
CLI Example:
.. code-block:: bash
salt '*' mine.flush
'''
if __opts__['file_client'] == 'local':
return __salt__['data.update']('mine_cache', {})
load = {
'cmd': '_mine_flush',
'id': __opts__['id'],
}
return _mine_send(load, __opts__)
def valid():
'''
List valid entries in mine configuration.
CLI Example:
.. code-block:: bash
salt '*' mine.valid
'''
m_data = __salt__['config.merge']('mine_functions', {})
# If we don't have any mine functions configured, then we should just bail out
if not m_data:
return
data = {}
for func in m_data:
if m_data[func] and isinstance(m_data[func], dict):
mine_func = m_data[func].pop('mine_function', func)
if not _mine_function_available(mine_func):
continue
data[func] = {mine_func: m_data[func]}
elif m_data[func] and isinstance(m_data[func], list):
mine_func = func
if isinstance(m_data[func][0], dict) and 'mine_function' in m_data[func][0]:
mine_func = m_data[func][0]['mine_function']
m_data[func].pop(0)
if not _mine_function_available(mine_func):
continue
data[func] = {mine_func: m_data[func]}
else:
if not _mine_function_available(func):
continue
data[func] = m_data[func]
return data
|
saltstack/salt
|
salt/modules/mine.py
|
valid
|
python
|
def valid():
'''
List valid entries in mine configuration.
CLI Example:
.. code-block:: bash
salt '*' mine.valid
'''
m_data = __salt__['config.merge']('mine_functions', {})
# If we don't have any mine functions configured, then we should just bail out
if not m_data:
return
data = {}
for func in m_data:
if m_data[func] and isinstance(m_data[func], dict):
mine_func = m_data[func].pop('mine_function', func)
if not _mine_function_available(mine_func):
continue
data[func] = {mine_func: m_data[func]}
elif m_data[func] and isinstance(m_data[func], list):
mine_func = func
if isinstance(m_data[func][0], dict) and 'mine_function' in m_data[func][0]:
mine_func = m_data[func][0]['mine_function']
m_data[func].pop(0)
if not _mine_function_available(mine_func):
continue
data[func] = {mine_func: m_data[func]}
else:
if not _mine_function_available(func):
continue
data[func] = m_data[func]
return data
|
List valid entries in mine configuration.
CLI Example:
.. code-block:: bash
salt '*' mine.valid
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mine.py#L492-L528
|
[
"def _mine_function_available(func):\n if func not in __salt__:\n log.error('Function %s in mine_functions not available', func)\n return False\n return True\n"
] |
# -*- coding: utf-8 -*-
'''
The function cache system allows for data to be stored on the master so it can be easily read by other minions
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import logging
import time
import traceback
# Import salt libs
import salt.crypt
import salt.payload
import salt.utils.args
import salt.utils.event
import salt.utils.network
import salt.transport.client
from salt.exceptions import SaltClientError
# Import 3rd-party libs
from salt.ext import six
MINE_INTERNAL_KEYWORDS = frozenset([
'__pub_user',
'__pub_arg',
'__pub_fun',
'__pub_jid',
'__pub_tgt',
'__pub_tgt_type',
'__pub_ret'
])
__proxyenabled__ = ['*']
log = logging.getLogger(__name__)
def _auth():
'''
Return the auth object
'''
if 'auth' not in __context__:
try:
__context__['auth'] = salt.crypt.SAuth(__opts__)
except SaltClientError:
log.error('Could not authenticate with master.'
'Mine data will not be transmitted.')
return __context__['auth']
def _mine_function_available(func):
if func not in __salt__:
log.error('Function %s in mine_functions not available', func)
return False
return True
def _mine_send(load, opts):
eventer = salt.utils.event.MinionEvent(opts, listen=False)
event_ret = eventer.fire_event(load, '_minion_mine')
# We need to pause here to allow for the decoupled nature of
# events time to allow the mine to propagate
time.sleep(0.5)
return event_ret
def _mine_get(load, opts):
if opts.get('transport', '') in ('zeromq', 'tcp'):
try:
load['tok'] = _auth().gen_token(b'salt')
except AttributeError:
log.error('Mine could not authenticate with master. '
'Mine could not be retrieved.'
)
return False
channel = salt.transport.client.ReqChannel.factory(opts)
try:
ret = channel.send(load)
finally:
channel.close()
return ret
def update(clear=False, mine_functions=None):
'''
Execute the configured functions and send the data back up to the master.
The functions to be executed are merged from the master config, pillar and
minion config under the option `mine_functions`:
.. code-block:: yaml
mine_functions:
network.ip_addrs:
- eth0
disk.usage: []
This function accepts the following arguments:
clear: False
Boolean flag specifying whether updating will clear the existing
mines, or will update. Default: `False` (update).
mine_functions
Update the mine data on certain functions only.
This feature can be used when updating the mine for functions
that require refresh at different intervals than the rest of
the functions specified under `mine_functions` in the
minion/master config or pillar.
A potential use would be together with the `scheduler`, for example:
.. code-block:: yaml
schedule:
lldp_mine_update:
function: mine.update
kwargs:
mine_functions:
net.lldp: []
hours: 12
In the example above, the mine for `net.lldp` would be refreshed
every 12 hours, while `network.ip_addrs` would continue to be updated
as specified in `mine_interval`.
The function cache will be populated with information from executing these
functions
CLI Example:
.. code-block:: bash
salt '*' mine.update
'''
m_data = {}
if not mine_functions:
m_data = __salt__['config.merge']('mine_functions', {})
# If we don't have any mine functions configured, then we should just bail out
if not m_data:
return
elif mine_functions and isinstance(mine_functions, list):
m_data = dict((fun, {}) for fun in mine_functions)
elif mine_functions and isinstance(mine_functions, dict):
m_data = mine_functions
else:
return
data = {}
for func in m_data:
try:
if m_data[func] and isinstance(m_data[func], dict):
mine_func = m_data[func].pop('mine_function', func)
if not _mine_function_available(mine_func):
continue
data[func] = __salt__[mine_func](**m_data[func])
elif m_data[func] and isinstance(m_data[func], list):
mine_func = func
if isinstance(m_data[func][0], dict) and 'mine_function' in m_data[func][0]:
mine_func = m_data[func][0]['mine_function']
m_data[func].pop(0)
if not _mine_function_available(mine_func):
continue
data[func] = __salt__[mine_func](*m_data[func])
else:
if not _mine_function_available(func):
continue
data[func] = __salt__[func]()
except Exception:
trace = traceback.format_exc()
log.error('Function %s in mine_functions failed to execute', func)
log.debug('Error: %s', trace)
continue
if __opts__['file_client'] == 'local':
if not clear:
old = __salt__['data.get']('mine_cache')
if isinstance(old, dict):
old.update(data)
data = old
return __salt__['data.update']('mine_cache', data)
load = {
'cmd': '_mine',
'data': data,
'id': __opts__['id'],
'clear': clear,
}
return _mine_send(load, __opts__)
def send(func, *args, **kwargs):
'''
Send a specific function to the mine.
CLI Example:
.. code-block:: bash
salt '*' mine.send network.ip_addrs eth0
salt '*' mine.send eth0_ip_addrs mine_function=network.ip_addrs eth0
'''
kwargs = salt.utils.args.clean_kwargs(**kwargs)
mine_func = kwargs.pop('mine_function', func)
if mine_func not in __salt__:
return False
data = {}
arg_data = salt.utils.args.arg_lookup(__salt__[mine_func])
func_data = copy.deepcopy(kwargs)
for ind, _ in enumerate(arg_data.get('args', [])):
try:
func_data[arg_data['args'][ind]] = args[ind]
except IndexError:
# Safe error, arg may be in kwargs
pass
f_call = salt.utils.args.format_call(
__salt__[mine_func],
func_data,
expected_extra_kws=MINE_INTERNAL_KEYWORDS)
for arg in args:
if arg not in f_call['args']:
f_call['args'].append(arg)
try:
if 'kwargs' in f_call:
data[func] = __salt__[mine_func](*f_call['args'], **f_call['kwargs'])
else:
data[func] = __salt__[mine_func](*f_call['args'])
except Exception as exc:
log.error('Function %s in mine.send failed to execute: %s',
mine_func, exc)
return False
if __opts__['file_client'] == 'local':
old = __salt__['data.get']('mine_cache')
if isinstance(old, dict):
old.update(data)
data = old
return __salt__['data.update']('mine_cache', data)
load = {
'cmd': '_mine',
'data': data,
'id': __opts__['id'],
}
return _mine_send(load, __opts__)
def get(tgt,
fun,
tgt_type='glob',
exclude_minion=False):
'''
Get data from the mine based on the target, function and tgt_type
Targets can be matched based on any standard matching system that can be
matched on the master via these keywords:
- glob
- pcre
- grain
- grain_pcre
- compound
- pillar
- pillar_pcre
Note that all pillar matches, whether using the compound matching system or
the pillar matching system, will be exact matches, with globbing disabled.
exclude_minion
Excludes the current minion from the result set
CLI Example:
.. code-block:: bash
salt '*' mine.get '*' network.interfaces
salt '*' mine.get '*' network.interfaces,network.ipaddrs
salt '*' mine.get '*' '["network.interfaces", "network.ipaddrs"]'
salt '*' mine.get 'os:Fedora' network.interfaces grain
salt '*' mine.get 'G@os:Fedora and S@192.168.5.0/24' network.ipaddrs compound
.. seealso:: Retrieving Mine data from Pillar and Orchestrate
This execution module is intended to be executed on minions.
Master-side operations such as Pillar or Orchestrate that require Mine
data should use the :py:mod:`Mine Runner module <salt.runners.mine>`
instead; it can be invoked from a Pillar SLS file using the
:py:func:`saltutil.runner <salt.modules.saltutil.runner>` module. For
example:
.. code-block:: jinja
{% set minion_ips = salt.saltutil.runner('mine.get',
tgt='*',
fun='network.ip_addrs',
tgt_type='glob') %}
'''
if __opts__['file_client'] == 'local':
ret = {}
is_target = {'glob': __salt__['match.glob'],
'pcre': __salt__['match.pcre'],
'list': __salt__['match.list'],
'grain': __salt__['match.grain'],
'grain_pcre': __salt__['match.grain_pcre'],
'ipcidr': __salt__['match.ipcidr'],
'compound': __salt__['match.compound'],
'pillar': __salt__['match.pillar'],
'pillar_pcre': __salt__['match.pillar_pcre'],
}[tgt_type](tgt)
if is_target:
data = __salt__['data.get']('mine_cache')
if isinstance(data, dict):
if isinstance(fun, six.string_types):
functions = list(set(fun.split(',')))
_ret_dict = len(functions) > 1
elif isinstance(fun, list):
functions = fun
_ret_dict = True
else:
return {}
if not _ret_dict and functions and functions[0] in data:
ret[__opts__['id']] = data.get(functions)
elif _ret_dict:
for fun in functions:
if fun in data:
ret.setdefault(fun, {})[__opts__['id']] = data.get(fun)
return ret
load = {
'cmd': '_mine_get',
'id': __opts__['id'],
'tgt': tgt,
'fun': fun,
'tgt_type': tgt_type,
}
ret = _mine_get(load, __opts__)
if exclude_minion:
if __opts__['id'] in ret:
del ret[__opts__['id']]
return ret
def delete(fun):
'''
Remove specific function contents of minion. Returns True on success.
CLI Example:
.. code-block:: bash
salt '*' mine.delete 'network.interfaces'
'''
if __opts__['file_client'] == 'local':
data = __salt__['data.get']('mine_cache')
if isinstance(data, dict) and fun in data:
del data[fun]
return __salt__['data.update']('mine_cache', data)
load = {
'cmd': '_mine_delete',
'id': __opts__['id'],
'fun': fun,
}
return _mine_send(load, __opts__)
def flush():
'''
Remove all mine contents of minion. Returns True on success.
CLI Example:
.. code-block:: bash
salt '*' mine.flush
'''
if __opts__['file_client'] == 'local':
return __salt__['data.update']('mine_cache', {})
load = {
'cmd': '_mine_flush',
'id': __opts__['id'],
}
return _mine_send(load, __opts__)
def get_docker(interfaces=None, cidrs=None, with_container_id=False):
'''
.. versionchanged:: 2017.7.8,2018.3.3
When :conf_minion:`docker.update_mine` is set to ``False`` for a given
minion, no mine data will be populated for that minion, and thus none
will be returned for it.
.. versionchanged:: 2019.2.0
:conf_minion:`docker.update_mine` now defaults to ``False``
Get all mine data for :py:func:`docker.ps <salt.modules.dockermod.ps_>` and
run an aggregation routine. The ``interfaces`` parameter allows for
specifying the network interfaces from which to select IP addresses. The
``cidrs`` parameter allows for specifying a list of subnets which the IP
address must match.
with_container_id
Boolean, to expose container_id in the list of results
.. versionadded:: 2015.8.2
CLI Example:
.. code-block:: bash
salt '*' mine.get_docker
salt '*' mine.get_docker interfaces='eth0'
salt '*' mine.get_docker interfaces='["eth0", "eth1"]'
salt '*' mine.get_docker cidrs='107.170.147.0/24'
salt '*' mine.get_docker cidrs='["107.170.147.0/24", "172.17.42.0/24"]'
salt '*' mine.get_docker interfaces='["eth0", "eth1"]' cidrs='["107.170.147.0/24", "172.17.42.0/24"]'
'''
# Enforce that interface and cidr are lists
if interfaces:
interface_ = []
interface_.extend(interfaces if isinstance(interfaces, list) else [interfaces])
interfaces = interface_
if cidrs:
cidr_ = []
cidr_.extend(cidrs if isinstance(cidrs, list) else [cidrs])
cidrs = cidr_
# Get docker info
cmd = 'docker.ps'
docker_hosts = get('*', cmd)
proxy_lists = {}
# Process docker info
for containers in six.itervalues(docker_hosts):
host = containers.pop('host')
host_ips = []
# Prepare host_ips list
if not interfaces:
for info in six.itervalues(host['interfaces']):
if 'inet' in info:
for ip_ in info['inet']:
host_ips.append(ip_['address'])
else:
for interface in interfaces:
if interface in host['interfaces']:
if 'inet' in host['interfaces'][interface]:
for item in host['interfaces'][interface]['inet']:
host_ips.append(item['address'])
host_ips = list(set(host_ips))
# Filter out ips from host_ips with cidrs
if cidrs:
good_ips = []
for cidr in cidrs:
for ip_ in host_ips:
if salt.utils.network.in_subnet(cidr, [ip_]):
good_ips.append(ip_)
host_ips = list(set(good_ips))
# Process each container
for container in six.itervalues(containers):
container_id = container['Info']['Id']
if container['Image'] not in proxy_lists:
proxy_lists[container['Image']] = {}
for dock_port in container['Ports']:
# IP exists only if port is exposed
ip_address = dock_port.get('IP')
# If port is 0.0.0.0, then we must get the docker host IP
if ip_address == '0.0.0.0':
for ip_ in host_ips:
containers = proxy_lists[container['Image']].setdefault('ipv4', {}).setdefault(dock_port['PrivatePort'], [])
container_network_footprint = '{0}:{1}'.format(ip_, dock_port['PublicPort'])
if with_container_id:
value = (container_network_footprint, container_id)
else:
value = container_network_footprint
if value not in containers:
containers.append(value)
elif ip_address:
containers = proxy_lists[container['Image']].setdefault('ipv4', {}).setdefault(dock_port['PrivatePort'], [])
container_network_footprint = '{0}:{1}'.format(dock_port['IP'], dock_port['PublicPort'])
if with_container_id:
value = (container_network_footprint, container_id)
else:
value = container_network_footprint
if value not in containers:
containers.append(value)
return proxy_lists
|
saltstack/salt
|
salt/returners/pgjsonb.py
|
returner
|
python
|
def returner(ret):
'''
Return data to a Pg server
'''
try:
with _get_serv(ret, commit=True) as cur:
sql = '''INSERT INTO salt_returns
(fun, jid, return, id, success, full_ret, alter_time)
VALUES (%s, %s, %s, %s, %s, %s, to_timestamp(%s))'''
cur.execute(sql, (ret['fun'], ret['jid'],
psycopg2.extras.Json(ret['return']),
ret['id'],
ret.get('success', False),
psycopg2.extras.Json(ret),
time.time()))
except salt.exceptions.SaltMasterError:
log.critical('Could not store return with pgjsonb returner. PostgreSQL server unavailable.')
|
Return data to a Pg server
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/pgjsonb.py#L288-L305
| null |
# -*- coding: utf-8 -*-
'''
Return data to a PostgreSQL server with json data stored in Pg's jsonb data type
:maintainer: Dave Boucha <dave@saltstack.com>, Seth House <shouse@saltstack.com>, C. R. Oldham <cr@saltstack.com>
:maturity: Stable
:depends: python-psycopg2
:platform: all
.. note::
There are three PostgreSQL returners. Any can function as an external
:ref:`master job cache <external-job-cache>`. but each has different
features. SaltStack recommends
:mod:`returners.pgjsonb <salt.returners.pgjsonb>` if you are working with
a version of PostgreSQL that has the appropriate native binary JSON types.
Otherwise, review
:mod:`returners.postgres <salt.returners.postgres>` and
:mod:`returners.postgres_local_cache <salt.returners.postgres_local_cache>`
to see which module best suits your particular needs.
To enable this returner, the minion will need the python client for PostgreSQL
installed and the following values configured in the minion or master
config. These are the defaults:
.. code-block:: yaml
returner.pgjsonb.host: 'salt'
returner.pgjsonb.user: 'salt'
returner.pgjsonb.pass: 'salt'
returner.pgjsonb.db: 'salt'
returner.pgjsonb.port: 5432
SSL is optional. The defaults are set to None. If you do not want to use SSL,
either exclude these options or set them to None.
.. code-block:: yaml
returner.pgjsonb.sslmode: None
returner.pgjsonb.sslcert: None
returner.pgjsonb.sslkey: None
returner.pgjsonb.sslrootcert: None
returner.pgjsonb.sslcrl: None
.. versionadded:: 2017.5.0
Alternative configuration values can be used by prefacing the configuration
with `alternative.`. Any values not found in the alternative configuration will
be pulled from the default location. As stated above, SSL configuration is
optional. The following ssl options are simply for illustration purposes:
.. code-block:: yaml
alternative.pgjsonb.host: 'salt'
alternative.pgjsonb.user: 'salt'
alternative.pgjsonb.pass: 'salt'
alternative.pgjsonb.db: 'salt'
alternative.pgjsonb.port: 5432
alternative.pgjsonb.ssl_ca: '/etc/pki/mysql/certs/localhost.pem'
alternative.pgjsonb.ssl_cert: '/etc/pki/mysql/certs/localhost.crt'
alternative.pgjsonb.ssl_key: '/etc/pki/mysql/certs/localhost.key'
Should you wish the returner data to be cleaned out every so often, set
``keep_jobs`` to the number of hours for the jobs to live in the tables.
Setting it to ``0`` or leaving it unset will cause the data to stay in the tables.
Should you wish to archive jobs in a different table for later processing,
set ``archive_jobs`` to True. Salt will create 3 archive tables;
- ``jids_archive``
- ``salt_returns_archive``
- ``salt_events_archive``
and move the contents of ``jids``, ``salt_returns``, and ``salt_events`` that are
more than ``keep_jobs`` hours old to these tables.
.. versionadded:: 2019.2.0
Use the following Pg database schema:
.. code-block:: sql
CREATE DATABASE salt
WITH ENCODING 'utf-8';
--
-- Table structure for table `jids`
--
DROP TABLE IF EXISTS jids;
CREATE TABLE jids (
jid varchar(255) NOT NULL primary key,
load jsonb NOT NULL
);
CREATE INDEX idx_jids_jsonb on jids
USING gin (load)
WITH (fastupdate=on);
--
-- Table structure for table `salt_returns`
--
DROP TABLE IF EXISTS salt_returns;
CREATE TABLE salt_returns (
fun varchar(50) NOT NULL,
jid varchar(255) NOT NULL,
return jsonb NOT NULL,
id varchar(255) NOT NULL,
success varchar(10) NOT NULL,
full_ret jsonb NOT NULL,
alter_time TIMESTAMP WITH TIME ZONE DEFAULT NOW());
CREATE INDEX idx_salt_returns_id ON salt_returns (id);
CREATE INDEX idx_salt_returns_jid ON salt_returns (jid);
CREATE INDEX idx_salt_returns_fun ON salt_returns (fun);
CREATE INDEX idx_salt_returns_return ON salt_returns
USING gin (return) with (fastupdate=on);
CREATE INDEX idx_salt_returns_full_ret ON salt_returns
USING gin (full_ret) with (fastupdate=on);
--
-- Table structure for table `salt_events`
--
DROP TABLE IF EXISTS salt_events;
DROP SEQUENCE IF EXISTS seq_salt_events_id;
CREATE SEQUENCE seq_salt_events_id;
CREATE TABLE salt_events (
id BIGINT NOT NULL UNIQUE DEFAULT nextval('seq_salt_events_id'),
tag varchar(255) NOT NULL,
data jsonb NOT NULL,
alter_time TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
master_id varchar(255) NOT NULL);
CREATE INDEX idx_salt_events_tag on
salt_events (tag);
CREATE INDEX idx_salt_events_data ON salt_events
USING gin (data) with (fastupdate=on);
Required python modules: Psycopg2
To use this returner, append '--return pgjsonb' to the salt command.
.. code-block:: bash
salt '*' test.ping --return pgjsonb
To use the alternative configuration, append '--return_config alternative' to the salt command.
.. versionadded:: 2015.5.0
.. code-block:: bash
salt '*' test.ping --return pgjsonb --return_config alternative
To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command.
.. versionadded:: 2016.3.0
.. code-block:: bash
salt '*' test.ping --return pgjsonb --return_kwargs '{"db": "another-salt"}'
'''
from __future__ import absolute_import, print_function, unicode_literals
# Let's not allow PyLint complain about string substitution
# pylint: disable=W1321,E1321
# Import python libs
from contextlib import contextmanager
import sys
import time
import logging
# Import salt libs
import salt.returners
import salt.utils.jid
import salt.exceptions
from salt.ext import six
# Import third party libs
try:
import psycopg2
import psycopg2.extras
HAS_PG = True
except ImportError:
HAS_PG = False
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pgjsonb'
PG_SAVE_LOAD_SQL = '''INSERT INTO jids (jid, load) VALUES (%(jid)s, %(load)s)'''
def __virtual__():
if not HAS_PG:
return False, 'Could not import pgjsonb returner; python-psycopg2 is not installed.'
return True
def _get_options(ret=None):
'''
Returns options used for the MySQL connection.
'''
defaults = {
'host': 'localhost',
'user': 'salt',
'pass': 'salt',
'db': 'salt',
'port': 5432
}
attrs = {
'host': 'host',
'user': 'user',
'pass': 'pass',
'db': 'db',
'port': 'port',
'sslmode': 'sslmode',
'sslcert': 'sslcert',
'sslkey': 'sslkey',
'sslrootcert': 'sslrootcert',
'sslcrl': 'sslcrl',
}
_options = salt.returners.get_returner_options('returner.{0}'.format(__virtualname__),
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__,
defaults=defaults)
# Ensure port is an int
if 'port' in _options:
_options['port'] = int(_options['port'])
return _options
@contextmanager
def _get_serv(ret=None, commit=False):
'''
Return a Pg cursor
'''
_options = _get_options(ret)
try:
# An empty ssl_options dictionary passed to MySQLdb.connect will
# effectively connect w/o SSL.
ssl_options = {
k: v for k, v in six.iteritems(_options)
if k in ['sslmode', 'sslcert', 'sslkey', 'sslrootcert', 'sslcrl']
}
conn = psycopg2.connect(
host=_options.get('host'),
port=_options.get('port'),
dbname=_options.get('db'),
user=_options.get('user'),
password=_options.get('pass'),
**ssl_options
)
except psycopg2.OperationalError as exc:
raise salt.exceptions.SaltMasterError('pgjsonb returner could not connect to database: {exc}'.format(exc=exc))
if conn.server_version is not None and conn.server_version >= 90500:
global PG_SAVE_LOAD_SQL
PG_SAVE_LOAD_SQL = '''INSERT INTO jids
(jid, load)
VALUES (%(jid)s, %(load)s)
ON CONFLICT (jid) DO UPDATE
SET load=%(load)s'''
cursor = conn.cursor()
try:
yield cursor
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
else:
if commit:
cursor.execute("COMMIT")
else:
cursor.execute("ROLLBACK")
finally:
conn.close()
def event_return(events):
'''
Return event to Pg server
Requires that configuration be enabled via 'event_return'
option in master config.
'''
with _get_serv(events, commit=True) as cur:
for event in events:
tag = event.get('tag', '')
data = event.get('data', '')
sql = '''INSERT INTO salt_events (tag, data, master_id, alter_time)
VALUES (%s, %s, %s, to_timestamp(%s))'''
cur.execute(sql, (tag, psycopg2.extras.Json(data),
__opts__['id'], time.time()))
def save_load(jid, load, minions=None):
'''
Save the load to the specified jid id
'''
with _get_serv(commit=True) as cur:
try:
cur.execute(PG_SAVE_LOAD_SQL,
{'jid': jid, 'load': psycopg2.extras.Json(load)})
except psycopg2.IntegrityError:
# https://github.com/saltstack/salt/issues/22171
# Without this try/except we get tons of duplicate entry errors
# which result in job returns not being stored properly
pass
def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument
'''
Included for API consistency
'''
pass
def get_load(jid):
'''
Return the load data that marks a specified jid
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT load FROM jids WHERE jid = %s;'''
cur.execute(sql, (jid,))
data = cur.fetchone()
if data:
return data[0]
return {}
def get_jid(jid):
'''
Return the information returned when the specified job id was executed
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT id, full_ret FROM salt_returns
WHERE jid = %s'''
cur.execute(sql, (jid,))
data = cur.fetchall()
ret = {}
if data:
for minion, full_ret in data:
ret[minion] = full_ret
return ret
def get_fun(fun):
'''
Return a dict of the last function called for all minions
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT s.id,s.jid, s.full_ret
FROM salt_returns s
JOIN ( SELECT MAX(`jid`) as jid
from salt_returns GROUP BY fun, id) max
ON s.jid = max.jid
WHERE s.fun = %s
'''
cur.execute(sql, (fun,))
data = cur.fetchall()
ret = {}
if data:
for minion, _, full_ret in data:
ret[minion] = full_ret
return ret
def get_jids():
'''
Return a list of all job ids
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT jid, load
FROM jids'''
cur.execute(sql)
data = cur.fetchall()
ret = {}
for jid, load in data:
ret[jid] = salt.utils.jid.format_jid_instance(jid, load)
return ret
def get_minions():
'''
Return a list of minions
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT DISTINCT id
FROM salt_returns'''
cur.execute(sql)
data = cur.fetchall()
ret = []
for minion in data:
ret.append(minion[0])
return ret
def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument
'''
Do any work necessary to prepare a JID, including sending a custom id
'''
return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
def _purge_jobs(timestamp):
'''
Purge records from the returner tables.
:param job_age_in_seconds: Purge jobs older than this
:return:
'''
with _get_serv() as cursor:
try:
sql = 'delete from jids where jid in (select distinct jid from salt_returns where alter_time < %s)'
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
try:
sql = 'delete from salt_returns where alter_time < %s'
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
try:
sql = 'delete from salt_events where alter_time < %s'
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
return True
def _archive_jobs(timestamp):
'''
Copy rows to a set of backup tables, then purge rows.
:param timestamp: Archive rows older than this timestamp
:return:
'''
source_tables = ['jids',
'salt_returns',
'salt_events']
with _get_serv() as cursor:
target_tables = {}
for table_name in source_tables:
try:
tmp_table_name = table_name + '_archive'
sql = 'create table IF NOT exists {0} (LIKE {1})'.format(tmp_table_name, table_name)
cursor.execute(sql)
cursor.execute('COMMIT')
target_tables[table_name] = tmp_table_name
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
try:
sql = 'insert into {0} select * from {1} where jid in (select distinct jid from salt_returns where alter_time < %s)'.format(target_tables['jids'], 'jids')
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
except Exception as e:
log.error(e)
raise
try:
sql = 'insert into {0} select * from {1} where alter_time < %s'.format(target_tables['salt_returns'], 'salt_returns')
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
try:
sql = 'insert into {0} select * from {1} where alter_time < %s'.format(target_tables['salt_events'], 'salt_events')
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
return _purge_jobs(timestamp)
def clean_old_jobs():
'''
Called in the master's event loop every loop_interval. Archives and/or
deletes the events and job details from the database.
:return:
'''
if __opts__.get('keep_jobs', False) and int(__opts__.get('keep_jobs', 0)) > 0:
try:
with _get_serv() as cur:
sql = "select (NOW() - interval '{0}' hour) as stamp;".format(__opts__['keep_jobs'])
cur.execute(sql)
rows = cur.fetchall()
stamp = rows[0][0]
if __opts__.get('archive_jobs', False):
_archive_jobs(stamp)
else:
_purge_jobs(stamp)
except Exception as e:
log.error(e)
|
saltstack/salt
|
salt/returners/pgjsonb.py
|
event_return
|
python
|
def event_return(events):
'''
Return event to Pg server
Requires that configuration be enabled via 'event_return'
option in master config.
'''
with _get_serv(events, commit=True) as cur:
for event in events:
tag = event.get('tag', '')
data = event.get('data', '')
sql = '''INSERT INTO salt_events (tag, data, master_id, alter_time)
VALUES (%s, %s, %s, to_timestamp(%s))'''
cur.execute(sql, (tag, psycopg2.extras.Json(data),
__opts__['id'], time.time()))
|
Return event to Pg server
Requires that configuration be enabled via 'event_return'
option in master config.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/pgjsonb.py#L308-L322
| null |
# -*- coding: utf-8 -*-
'''
Return data to a PostgreSQL server with json data stored in Pg's jsonb data type
:maintainer: Dave Boucha <dave@saltstack.com>, Seth House <shouse@saltstack.com>, C. R. Oldham <cr@saltstack.com>
:maturity: Stable
:depends: python-psycopg2
:platform: all
.. note::
There are three PostgreSQL returners. Any can function as an external
:ref:`master job cache <external-job-cache>`. but each has different
features. SaltStack recommends
:mod:`returners.pgjsonb <salt.returners.pgjsonb>` if you are working with
a version of PostgreSQL that has the appropriate native binary JSON types.
Otherwise, review
:mod:`returners.postgres <salt.returners.postgres>` and
:mod:`returners.postgres_local_cache <salt.returners.postgres_local_cache>`
to see which module best suits your particular needs.
To enable this returner, the minion will need the python client for PostgreSQL
installed and the following values configured in the minion or master
config. These are the defaults:
.. code-block:: yaml
returner.pgjsonb.host: 'salt'
returner.pgjsonb.user: 'salt'
returner.pgjsonb.pass: 'salt'
returner.pgjsonb.db: 'salt'
returner.pgjsonb.port: 5432
SSL is optional. The defaults are set to None. If you do not want to use SSL,
either exclude these options or set them to None.
.. code-block:: yaml
returner.pgjsonb.sslmode: None
returner.pgjsonb.sslcert: None
returner.pgjsonb.sslkey: None
returner.pgjsonb.sslrootcert: None
returner.pgjsonb.sslcrl: None
.. versionadded:: 2017.5.0
Alternative configuration values can be used by prefacing the configuration
with `alternative.`. Any values not found in the alternative configuration will
be pulled from the default location. As stated above, SSL configuration is
optional. The following ssl options are simply for illustration purposes:
.. code-block:: yaml
alternative.pgjsonb.host: 'salt'
alternative.pgjsonb.user: 'salt'
alternative.pgjsonb.pass: 'salt'
alternative.pgjsonb.db: 'salt'
alternative.pgjsonb.port: 5432
alternative.pgjsonb.ssl_ca: '/etc/pki/mysql/certs/localhost.pem'
alternative.pgjsonb.ssl_cert: '/etc/pki/mysql/certs/localhost.crt'
alternative.pgjsonb.ssl_key: '/etc/pki/mysql/certs/localhost.key'
Should you wish the returner data to be cleaned out every so often, set
``keep_jobs`` to the number of hours for the jobs to live in the tables.
Setting it to ``0`` or leaving it unset will cause the data to stay in the tables.
Should you wish to archive jobs in a different table for later processing,
set ``archive_jobs`` to True. Salt will create 3 archive tables;
- ``jids_archive``
- ``salt_returns_archive``
- ``salt_events_archive``
and move the contents of ``jids``, ``salt_returns``, and ``salt_events`` that are
more than ``keep_jobs`` hours old to these tables.
.. versionadded:: 2019.2.0
Use the following Pg database schema:
.. code-block:: sql
CREATE DATABASE salt
WITH ENCODING 'utf-8';
--
-- Table structure for table `jids`
--
DROP TABLE IF EXISTS jids;
CREATE TABLE jids (
jid varchar(255) NOT NULL primary key,
load jsonb NOT NULL
);
CREATE INDEX idx_jids_jsonb on jids
USING gin (load)
WITH (fastupdate=on);
--
-- Table structure for table `salt_returns`
--
DROP TABLE IF EXISTS salt_returns;
CREATE TABLE salt_returns (
fun varchar(50) NOT NULL,
jid varchar(255) NOT NULL,
return jsonb NOT NULL,
id varchar(255) NOT NULL,
success varchar(10) NOT NULL,
full_ret jsonb NOT NULL,
alter_time TIMESTAMP WITH TIME ZONE DEFAULT NOW());
CREATE INDEX idx_salt_returns_id ON salt_returns (id);
CREATE INDEX idx_salt_returns_jid ON salt_returns (jid);
CREATE INDEX idx_salt_returns_fun ON salt_returns (fun);
CREATE INDEX idx_salt_returns_return ON salt_returns
USING gin (return) with (fastupdate=on);
CREATE INDEX idx_salt_returns_full_ret ON salt_returns
USING gin (full_ret) with (fastupdate=on);
--
-- Table structure for table `salt_events`
--
DROP TABLE IF EXISTS salt_events;
DROP SEQUENCE IF EXISTS seq_salt_events_id;
CREATE SEQUENCE seq_salt_events_id;
CREATE TABLE salt_events (
id BIGINT NOT NULL UNIQUE DEFAULT nextval('seq_salt_events_id'),
tag varchar(255) NOT NULL,
data jsonb NOT NULL,
alter_time TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
master_id varchar(255) NOT NULL);
CREATE INDEX idx_salt_events_tag on
salt_events (tag);
CREATE INDEX idx_salt_events_data ON salt_events
USING gin (data) with (fastupdate=on);
Required python modules: Psycopg2
To use this returner, append '--return pgjsonb' to the salt command.
.. code-block:: bash
salt '*' test.ping --return pgjsonb
To use the alternative configuration, append '--return_config alternative' to the salt command.
.. versionadded:: 2015.5.0
.. code-block:: bash
salt '*' test.ping --return pgjsonb --return_config alternative
To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command.
.. versionadded:: 2016.3.0
.. code-block:: bash
salt '*' test.ping --return pgjsonb --return_kwargs '{"db": "another-salt"}'
'''
from __future__ import absolute_import, print_function, unicode_literals
# Let's not allow PyLint complain about string substitution
# pylint: disable=W1321,E1321
# Import python libs
from contextlib import contextmanager
import sys
import time
import logging
# Import salt libs
import salt.returners
import salt.utils.jid
import salt.exceptions
from salt.ext import six
# Import third party libs
try:
import psycopg2
import psycopg2.extras
HAS_PG = True
except ImportError:
HAS_PG = False
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pgjsonb'
PG_SAVE_LOAD_SQL = '''INSERT INTO jids (jid, load) VALUES (%(jid)s, %(load)s)'''
def __virtual__():
if not HAS_PG:
return False, 'Could not import pgjsonb returner; python-psycopg2 is not installed.'
return True
def _get_options(ret=None):
'''
Returns options used for the MySQL connection.
'''
defaults = {
'host': 'localhost',
'user': 'salt',
'pass': 'salt',
'db': 'salt',
'port': 5432
}
attrs = {
'host': 'host',
'user': 'user',
'pass': 'pass',
'db': 'db',
'port': 'port',
'sslmode': 'sslmode',
'sslcert': 'sslcert',
'sslkey': 'sslkey',
'sslrootcert': 'sslrootcert',
'sslcrl': 'sslcrl',
}
_options = salt.returners.get_returner_options('returner.{0}'.format(__virtualname__),
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__,
defaults=defaults)
# Ensure port is an int
if 'port' in _options:
_options['port'] = int(_options['port'])
return _options
@contextmanager
def _get_serv(ret=None, commit=False):
'''
Return a Pg cursor
'''
_options = _get_options(ret)
try:
# An empty ssl_options dictionary passed to MySQLdb.connect will
# effectively connect w/o SSL.
ssl_options = {
k: v for k, v in six.iteritems(_options)
if k in ['sslmode', 'sslcert', 'sslkey', 'sslrootcert', 'sslcrl']
}
conn = psycopg2.connect(
host=_options.get('host'),
port=_options.get('port'),
dbname=_options.get('db'),
user=_options.get('user'),
password=_options.get('pass'),
**ssl_options
)
except psycopg2.OperationalError as exc:
raise salt.exceptions.SaltMasterError('pgjsonb returner could not connect to database: {exc}'.format(exc=exc))
if conn.server_version is not None and conn.server_version >= 90500:
global PG_SAVE_LOAD_SQL
PG_SAVE_LOAD_SQL = '''INSERT INTO jids
(jid, load)
VALUES (%(jid)s, %(load)s)
ON CONFLICT (jid) DO UPDATE
SET load=%(load)s'''
cursor = conn.cursor()
try:
yield cursor
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
else:
if commit:
cursor.execute("COMMIT")
else:
cursor.execute("ROLLBACK")
finally:
conn.close()
def returner(ret):
'''
Return data to a Pg server
'''
try:
with _get_serv(ret, commit=True) as cur:
sql = '''INSERT INTO salt_returns
(fun, jid, return, id, success, full_ret, alter_time)
VALUES (%s, %s, %s, %s, %s, %s, to_timestamp(%s))'''
cur.execute(sql, (ret['fun'], ret['jid'],
psycopg2.extras.Json(ret['return']),
ret['id'],
ret.get('success', False),
psycopg2.extras.Json(ret),
time.time()))
except salt.exceptions.SaltMasterError:
log.critical('Could not store return with pgjsonb returner. PostgreSQL server unavailable.')
def save_load(jid, load, minions=None):
'''
Save the load to the specified jid id
'''
with _get_serv(commit=True) as cur:
try:
cur.execute(PG_SAVE_LOAD_SQL,
{'jid': jid, 'load': psycopg2.extras.Json(load)})
except psycopg2.IntegrityError:
# https://github.com/saltstack/salt/issues/22171
# Without this try/except we get tons of duplicate entry errors
# which result in job returns not being stored properly
pass
def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument
'''
Included for API consistency
'''
pass
def get_load(jid):
'''
Return the load data that marks a specified jid
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT load FROM jids WHERE jid = %s;'''
cur.execute(sql, (jid,))
data = cur.fetchone()
if data:
return data[0]
return {}
def get_jid(jid):
'''
Return the information returned when the specified job id was executed
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT id, full_ret FROM salt_returns
WHERE jid = %s'''
cur.execute(sql, (jid,))
data = cur.fetchall()
ret = {}
if data:
for minion, full_ret in data:
ret[minion] = full_ret
return ret
def get_fun(fun):
'''
Return a dict of the last function called for all minions
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT s.id,s.jid, s.full_ret
FROM salt_returns s
JOIN ( SELECT MAX(`jid`) as jid
from salt_returns GROUP BY fun, id) max
ON s.jid = max.jid
WHERE s.fun = %s
'''
cur.execute(sql, (fun,))
data = cur.fetchall()
ret = {}
if data:
for minion, _, full_ret in data:
ret[minion] = full_ret
return ret
def get_jids():
'''
Return a list of all job ids
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT jid, load
FROM jids'''
cur.execute(sql)
data = cur.fetchall()
ret = {}
for jid, load in data:
ret[jid] = salt.utils.jid.format_jid_instance(jid, load)
return ret
def get_minions():
'''
Return a list of minions
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT DISTINCT id
FROM salt_returns'''
cur.execute(sql)
data = cur.fetchall()
ret = []
for minion in data:
ret.append(minion[0])
return ret
def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument
'''
Do any work necessary to prepare a JID, including sending a custom id
'''
return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
def _purge_jobs(timestamp):
'''
Purge records from the returner tables.
:param job_age_in_seconds: Purge jobs older than this
:return:
'''
with _get_serv() as cursor:
try:
sql = 'delete from jids where jid in (select distinct jid from salt_returns where alter_time < %s)'
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
try:
sql = 'delete from salt_returns where alter_time < %s'
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
try:
sql = 'delete from salt_events where alter_time < %s'
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
return True
def _archive_jobs(timestamp):
'''
Copy rows to a set of backup tables, then purge rows.
:param timestamp: Archive rows older than this timestamp
:return:
'''
source_tables = ['jids',
'salt_returns',
'salt_events']
with _get_serv() as cursor:
target_tables = {}
for table_name in source_tables:
try:
tmp_table_name = table_name + '_archive'
sql = 'create table IF NOT exists {0} (LIKE {1})'.format(tmp_table_name, table_name)
cursor.execute(sql)
cursor.execute('COMMIT')
target_tables[table_name] = tmp_table_name
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
try:
sql = 'insert into {0} select * from {1} where jid in (select distinct jid from salt_returns where alter_time < %s)'.format(target_tables['jids'], 'jids')
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
except Exception as e:
log.error(e)
raise
try:
sql = 'insert into {0} select * from {1} where alter_time < %s'.format(target_tables['salt_returns'], 'salt_returns')
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
try:
sql = 'insert into {0} select * from {1} where alter_time < %s'.format(target_tables['salt_events'], 'salt_events')
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
return _purge_jobs(timestamp)
def clean_old_jobs():
'''
Called in the master's event loop every loop_interval. Archives and/or
deletes the events and job details from the database.
:return:
'''
if __opts__.get('keep_jobs', False) and int(__opts__.get('keep_jobs', 0)) > 0:
try:
with _get_serv() as cur:
sql = "select (NOW() - interval '{0}' hour) as stamp;".format(__opts__['keep_jobs'])
cur.execute(sql)
rows = cur.fetchall()
stamp = rows[0][0]
if __opts__.get('archive_jobs', False):
_archive_jobs(stamp)
else:
_purge_jobs(stamp)
except Exception as e:
log.error(e)
|
saltstack/salt
|
salt/returners/pgjsonb.py
|
save_load
|
python
|
def save_load(jid, load, minions=None):
'''
Save the load to the specified jid id
'''
with _get_serv(commit=True) as cur:
try:
cur.execute(PG_SAVE_LOAD_SQL,
{'jid': jid, 'load': psycopg2.extras.Json(load)})
except psycopg2.IntegrityError:
# https://github.com/saltstack/salt/issues/22171
# Without this try/except we get tons of duplicate entry errors
# which result in job returns not being stored properly
pass
|
Save the load to the specified jid id
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/pgjsonb.py#L325-L337
| null |
# -*- coding: utf-8 -*-
'''
Return data to a PostgreSQL server with json data stored in Pg's jsonb data type
:maintainer: Dave Boucha <dave@saltstack.com>, Seth House <shouse@saltstack.com>, C. R. Oldham <cr@saltstack.com>
:maturity: Stable
:depends: python-psycopg2
:platform: all
.. note::
There are three PostgreSQL returners. Any can function as an external
:ref:`master job cache <external-job-cache>`. but each has different
features. SaltStack recommends
:mod:`returners.pgjsonb <salt.returners.pgjsonb>` if you are working with
a version of PostgreSQL that has the appropriate native binary JSON types.
Otherwise, review
:mod:`returners.postgres <salt.returners.postgres>` and
:mod:`returners.postgres_local_cache <salt.returners.postgres_local_cache>`
to see which module best suits your particular needs.
To enable this returner, the minion will need the python client for PostgreSQL
installed and the following values configured in the minion or master
config. These are the defaults:
.. code-block:: yaml
returner.pgjsonb.host: 'salt'
returner.pgjsonb.user: 'salt'
returner.pgjsonb.pass: 'salt'
returner.pgjsonb.db: 'salt'
returner.pgjsonb.port: 5432
SSL is optional. The defaults are set to None. If you do not want to use SSL,
either exclude these options or set them to None.
.. code-block:: yaml
returner.pgjsonb.sslmode: None
returner.pgjsonb.sslcert: None
returner.pgjsonb.sslkey: None
returner.pgjsonb.sslrootcert: None
returner.pgjsonb.sslcrl: None
.. versionadded:: 2017.5.0
Alternative configuration values can be used by prefacing the configuration
with `alternative.`. Any values not found in the alternative configuration will
be pulled from the default location. As stated above, SSL configuration is
optional. The following ssl options are simply for illustration purposes:
.. code-block:: yaml
alternative.pgjsonb.host: 'salt'
alternative.pgjsonb.user: 'salt'
alternative.pgjsonb.pass: 'salt'
alternative.pgjsonb.db: 'salt'
alternative.pgjsonb.port: 5432
alternative.pgjsonb.ssl_ca: '/etc/pki/mysql/certs/localhost.pem'
alternative.pgjsonb.ssl_cert: '/etc/pki/mysql/certs/localhost.crt'
alternative.pgjsonb.ssl_key: '/etc/pki/mysql/certs/localhost.key'
Should you wish the returner data to be cleaned out every so often, set
``keep_jobs`` to the number of hours for the jobs to live in the tables.
Setting it to ``0`` or leaving it unset will cause the data to stay in the tables.
Should you wish to archive jobs in a different table for later processing,
set ``archive_jobs`` to True. Salt will create 3 archive tables;
- ``jids_archive``
- ``salt_returns_archive``
- ``salt_events_archive``
and move the contents of ``jids``, ``salt_returns``, and ``salt_events`` that are
more than ``keep_jobs`` hours old to these tables.
.. versionadded:: 2019.2.0
Use the following Pg database schema:
.. code-block:: sql
CREATE DATABASE salt
WITH ENCODING 'utf-8';
--
-- Table structure for table `jids`
--
DROP TABLE IF EXISTS jids;
CREATE TABLE jids (
jid varchar(255) NOT NULL primary key,
load jsonb NOT NULL
);
CREATE INDEX idx_jids_jsonb on jids
USING gin (load)
WITH (fastupdate=on);
--
-- Table structure for table `salt_returns`
--
DROP TABLE IF EXISTS salt_returns;
CREATE TABLE salt_returns (
fun varchar(50) NOT NULL,
jid varchar(255) NOT NULL,
return jsonb NOT NULL,
id varchar(255) NOT NULL,
success varchar(10) NOT NULL,
full_ret jsonb NOT NULL,
alter_time TIMESTAMP WITH TIME ZONE DEFAULT NOW());
CREATE INDEX idx_salt_returns_id ON salt_returns (id);
CREATE INDEX idx_salt_returns_jid ON salt_returns (jid);
CREATE INDEX idx_salt_returns_fun ON salt_returns (fun);
CREATE INDEX idx_salt_returns_return ON salt_returns
USING gin (return) with (fastupdate=on);
CREATE INDEX idx_salt_returns_full_ret ON salt_returns
USING gin (full_ret) with (fastupdate=on);
--
-- Table structure for table `salt_events`
--
DROP TABLE IF EXISTS salt_events;
DROP SEQUENCE IF EXISTS seq_salt_events_id;
CREATE SEQUENCE seq_salt_events_id;
CREATE TABLE salt_events (
id BIGINT NOT NULL UNIQUE DEFAULT nextval('seq_salt_events_id'),
tag varchar(255) NOT NULL,
data jsonb NOT NULL,
alter_time TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
master_id varchar(255) NOT NULL);
CREATE INDEX idx_salt_events_tag on
salt_events (tag);
CREATE INDEX idx_salt_events_data ON salt_events
USING gin (data) with (fastupdate=on);
Required python modules: Psycopg2
To use this returner, append '--return pgjsonb' to the salt command.
.. code-block:: bash
salt '*' test.ping --return pgjsonb
To use the alternative configuration, append '--return_config alternative' to the salt command.
.. versionadded:: 2015.5.0
.. code-block:: bash
salt '*' test.ping --return pgjsonb --return_config alternative
To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command.
.. versionadded:: 2016.3.0
.. code-block:: bash
salt '*' test.ping --return pgjsonb --return_kwargs '{"db": "another-salt"}'
'''
from __future__ import absolute_import, print_function, unicode_literals
# Let's not allow PyLint complain about string substitution
# pylint: disable=W1321,E1321
# Import python libs
from contextlib import contextmanager
import sys
import time
import logging
# Import salt libs
import salt.returners
import salt.utils.jid
import salt.exceptions
from salt.ext import six
# Import third party libs
try:
import psycopg2
import psycopg2.extras
HAS_PG = True
except ImportError:
HAS_PG = False
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pgjsonb'
PG_SAVE_LOAD_SQL = '''INSERT INTO jids (jid, load) VALUES (%(jid)s, %(load)s)'''
def __virtual__():
if not HAS_PG:
return False, 'Could not import pgjsonb returner; python-psycopg2 is not installed.'
return True
def _get_options(ret=None):
'''
Returns options used for the MySQL connection.
'''
defaults = {
'host': 'localhost',
'user': 'salt',
'pass': 'salt',
'db': 'salt',
'port': 5432
}
attrs = {
'host': 'host',
'user': 'user',
'pass': 'pass',
'db': 'db',
'port': 'port',
'sslmode': 'sslmode',
'sslcert': 'sslcert',
'sslkey': 'sslkey',
'sslrootcert': 'sslrootcert',
'sslcrl': 'sslcrl',
}
_options = salt.returners.get_returner_options('returner.{0}'.format(__virtualname__),
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__,
defaults=defaults)
# Ensure port is an int
if 'port' in _options:
_options['port'] = int(_options['port'])
return _options
@contextmanager
def _get_serv(ret=None, commit=False):
'''
Return a Pg cursor
'''
_options = _get_options(ret)
try:
# An empty ssl_options dictionary passed to MySQLdb.connect will
# effectively connect w/o SSL.
ssl_options = {
k: v for k, v in six.iteritems(_options)
if k in ['sslmode', 'sslcert', 'sslkey', 'sslrootcert', 'sslcrl']
}
conn = psycopg2.connect(
host=_options.get('host'),
port=_options.get('port'),
dbname=_options.get('db'),
user=_options.get('user'),
password=_options.get('pass'),
**ssl_options
)
except psycopg2.OperationalError as exc:
raise salt.exceptions.SaltMasterError('pgjsonb returner could not connect to database: {exc}'.format(exc=exc))
if conn.server_version is not None and conn.server_version >= 90500:
global PG_SAVE_LOAD_SQL
PG_SAVE_LOAD_SQL = '''INSERT INTO jids
(jid, load)
VALUES (%(jid)s, %(load)s)
ON CONFLICT (jid) DO UPDATE
SET load=%(load)s'''
cursor = conn.cursor()
try:
yield cursor
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
else:
if commit:
cursor.execute("COMMIT")
else:
cursor.execute("ROLLBACK")
finally:
conn.close()
def returner(ret):
'''
Return data to a Pg server
'''
try:
with _get_serv(ret, commit=True) as cur:
sql = '''INSERT INTO salt_returns
(fun, jid, return, id, success, full_ret, alter_time)
VALUES (%s, %s, %s, %s, %s, %s, to_timestamp(%s))'''
cur.execute(sql, (ret['fun'], ret['jid'],
psycopg2.extras.Json(ret['return']),
ret['id'],
ret.get('success', False),
psycopg2.extras.Json(ret),
time.time()))
except salt.exceptions.SaltMasterError:
log.critical('Could not store return with pgjsonb returner. PostgreSQL server unavailable.')
def event_return(events):
'''
Return event to Pg server
Requires that configuration be enabled via 'event_return'
option in master config.
'''
with _get_serv(events, commit=True) as cur:
for event in events:
tag = event.get('tag', '')
data = event.get('data', '')
sql = '''INSERT INTO salt_events (tag, data, master_id, alter_time)
VALUES (%s, %s, %s, to_timestamp(%s))'''
cur.execute(sql, (tag, psycopg2.extras.Json(data),
__opts__['id'], time.time()))
def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument
'''
Included for API consistency
'''
pass
def get_load(jid):
'''
Return the load data that marks a specified jid
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT load FROM jids WHERE jid = %s;'''
cur.execute(sql, (jid,))
data = cur.fetchone()
if data:
return data[0]
return {}
def get_jid(jid):
'''
Return the information returned when the specified job id was executed
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT id, full_ret FROM salt_returns
WHERE jid = %s'''
cur.execute(sql, (jid,))
data = cur.fetchall()
ret = {}
if data:
for minion, full_ret in data:
ret[minion] = full_ret
return ret
def get_fun(fun):
'''
Return a dict of the last function called for all minions
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT s.id,s.jid, s.full_ret
FROM salt_returns s
JOIN ( SELECT MAX(`jid`) as jid
from salt_returns GROUP BY fun, id) max
ON s.jid = max.jid
WHERE s.fun = %s
'''
cur.execute(sql, (fun,))
data = cur.fetchall()
ret = {}
if data:
for minion, _, full_ret in data:
ret[minion] = full_ret
return ret
def get_jids():
'''
Return a list of all job ids
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT jid, load
FROM jids'''
cur.execute(sql)
data = cur.fetchall()
ret = {}
for jid, load in data:
ret[jid] = salt.utils.jid.format_jid_instance(jid, load)
return ret
def get_minions():
'''
Return a list of minions
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT DISTINCT id
FROM salt_returns'''
cur.execute(sql)
data = cur.fetchall()
ret = []
for minion in data:
ret.append(minion[0])
return ret
def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument
'''
Do any work necessary to prepare a JID, including sending a custom id
'''
return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
def _purge_jobs(timestamp):
'''
Purge records from the returner tables.
:param job_age_in_seconds: Purge jobs older than this
:return:
'''
with _get_serv() as cursor:
try:
sql = 'delete from jids where jid in (select distinct jid from salt_returns where alter_time < %s)'
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
try:
sql = 'delete from salt_returns where alter_time < %s'
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
try:
sql = 'delete from salt_events where alter_time < %s'
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
return True
def _archive_jobs(timestamp):
'''
Copy rows to a set of backup tables, then purge rows.
:param timestamp: Archive rows older than this timestamp
:return:
'''
source_tables = ['jids',
'salt_returns',
'salt_events']
with _get_serv() as cursor:
target_tables = {}
for table_name in source_tables:
try:
tmp_table_name = table_name + '_archive'
sql = 'create table IF NOT exists {0} (LIKE {1})'.format(tmp_table_name, table_name)
cursor.execute(sql)
cursor.execute('COMMIT')
target_tables[table_name] = tmp_table_name
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
try:
sql = 'insert into {0} select * from {1} where jid in (select distinct jid from salt_returns where alter_time < %s)'.format(target_tables['jids'], 'jids')
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
except Exception as e:
log.error(e)
raise
try:
sql = 'insert into {0} select * from {1} where alter_time < %s'.format(target_tables['salt_returns'], 'salt_returns')
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
try:
sql = 'insert into {0} select * from {1} where alter_time < %s'.format(target_tables['salt_events'], 'salt_events')
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
return _purge_jobs(timestamp)
def clean_old_jobs():
'''
Called in the master's event loop every loop_interval. Archives and/or
deletes the events and job details from the database.
:return:
'''
if __opts__.get('keep_jobs', False) and int(__opts__.get('keep_jobs', 0)) > 0:
try:
with _get_serv() as cur:
sql = "select (NOW() - interval '{0}' hour) as stamp;".format(__opts__['keep_jobs'])
cur.execute(sql)
rows = cur.fetchall()
stamp = rows[0][0]
if __opts__.get('archive_jobs', False):
_archive_jobs(stamp)
else:
_purge_jobs(stamp)
except Exception as e:
log.error(e)
|
saltstack/salt
|
salt/returners/pgjsonb.py
|
get_load
|
python
|
def get_load(jid):
'''
Return the load data that marks a specified jid
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT load FROM jids WHERE jid = %s;'''
cur.execute(sql, (jid,))
data = cur.fetchone()
if data:
return data[0]
return {}
|
Return the load data that marks a specified jid
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/pgjsonb.py#L347-L358
| null |
# -*- coding: utf-8 -*-
'''
Return data to a PostgreSQL server with json data stored in Pg's jsonb data type
:maintainer: Dave Boucha <dave@saltstack.com>, Seth House <shouse@saltstack.com>, C. R. Oldham <cr@saltstack.com>
:maturity: Stable
:depends: python-psycopg2
:platform: all
.. note::
There are three PostgreSQL returners. Any can function as an external
:ref:`master job cache <external-job-cache>`. but each has different
features. SaltStack recommends
:mod:`returners.pgjsonb <salt.returners.pgjsonb>` if you are working with
a version of PostgreSQL that has the appropriate native binary JSON types.
Otherwise, review
:mod:`returners.postgres <salt.returners.postgres>` and
:mod:`returners.postgres_local_cache <salt.returners.postgres_local_cache>`
to see which module best suits your particular needs.
To enable this returner, the minion will need the python client for PostgreSQL
installed and the following values configured in the minion or master
config. These are the defaults:
.. code-block:: yaml
returner.pgjsonb.host: 'salt'
returner.pgjsonb.user: 'salt'
returner.pgjsonb.pass: 'salt'
returner.pgjsonb.db: 'salt'
returner.pgjsonb.port: 5432
SSL is optional. The defaults are set to None. If you do not want to use SSL,
either exclude these options or set them to None.
.. code-block:: yaml
returner.pgjsonb.sslmode: None
returner.pgjsonb.sslcert: None
returner.pgjsonb.sslkey: None
returner.pgjsonb.sslrootcert: None
returner.pgjsonb.sslcrl: None
.. versionadded:: 2017.5.0
Alternative configuration values can be used by prefacing the configuration
with `alternative.`. Any values not found in the alternative configuration will
be pulled from the default location. As stated above, SSL configuration is
optional. The following ssl options are simply for illustration purposes:
.. code-block:: yaml
alternative.pgjsonb.host: 'salt'
alternative.pgjsonb.user: 'salt'
alternative.pgjsonb.pass: 'salt'
alternative.pgjsonb.db: 'salt'
alternative.pgjsonb.port: 5432
alternative.pgjsonb.ssl_ca: '/etc/pki/mysql/certs/localhost.pem'
alternative.pgjsonb.ssl_cert: '/etc/pki/mysql/certs/localhost.crt'
alternative.pgjsonb.ssl_key: '/etc/pki/mysql/certs/localhost.key'
Should you wish the returner data to be cleaned out every so often, set
``keep_jobs`` to the number of hours for the jobs to live in the tables.
Setting it to ``0`` or leaving it unset will cause the data to stay in the tables.
Should you wish to archive jobs in a different table for later processing,
set ``archive_jobs`` to True. Salt will create 3 archive tables;
- ``jids_archive``
- ``salt_returns_archive``
- ``salt_events_archive``
and move the contents of ``jids``, ``salt_returns``, and ``salt_events`` that are
more than ``keep_jobs`` hours old to these tables.
.. versionadded:: 2019.2.0
Use the following Pg database schema:
.. code-block:: sql
CREATE DATABASE salt
WITH ENCODING 'utf-8';
--
-- Table structure for table `jids`
--
DROP TABLE IF EXISTS jids;
CREATE TABLE jids (
jid varchar(255) NOT NULL primary key,
load jsonb NOT NULL
);
CREATE INDEX idx_jids_jsonb on jids
USING gin (load)
WITH (fastupdate=on);
--
-- Table structure for table `salt_returns`
--
DROP TABLE IF EXISTS salt_returns;
CREATE TABLE salt_returns (
fun varchar(50) NOT NULL,
jid varchar(255) NOT NULL,
return jsonb NOT NULL,
id varchar(255) NOT NULL,
success varchar(10) NOT NULL,
full_ret jsonb NOT NULL,
alter_time TIMESTAMP WITH TIME ZONE DEFAULT NOW());
CREATE INDEX idx_salt_returns_id ON salt_returns (id);
CREATE INDEX idx_salt_returns_jid ON salt_returns (jid);
CREATE INDEX idx_salt_returns_fun ON salt_returns (fun);
CREATE INDEX idx_salt_returns_return ON salt_returns
USING gin (return) with (fastupdate=on);
CREATE INDEX idx_salt_returns_full_ret ON salt_returns
USING gin (full_ret) with (fastupdate=on);
--
-- Table structure for table `salt_events`
--
DROP TABLE IF EXISTS salt_events;
DROP SEQUENCE IF EXISTS seq_salt_events_id;
CREATE SEQUENCE seq_salt_events_id;
CREATE TABLE salt_events (
id BIGINT NOT NULL UNIQUE DEFAULT nextval('seq_salt_events_id'),
tag varchar(255) NOT NULL,
data jsonb NOT NULL,
alter_time TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
master_id varchar(255) NOT NULL);
CREATE INDEX idx_salt_events_tag on
salt_events (tag);
CREATE INDEX idx_salt_events_data ON salt_events
USING gin (data) with (fastupdate=on);
Required python modules: Psycopg2
To use this returner, append '--return pgjsonb' to the salt command.
.. code-block:: bash
salt '*' test.ping --return pgjsonb
To use the alternative configuration, append '--return_config alternative' to the salt command.
.. versionadded:: 2015.5.0
.. code-block:: bash
salt '*' test.ping --return pgjsonb --return_config alternative
To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command.
.. versionadded:: 2016.3.0
.. code-block:: bash
salt '*' test.ping --return pgjsonb --return_kwargs '{"db": "another-salt"}'
'''
from __future__ import absolute_import, print_function, unicode_literals
# Let's not allow PyLint complain about string substitution
# pylint: disable=W1321,E1321
# Import python libs
from contextlib import contextmanager
import sys
import time
import logging
# Import salt libs
import salt.returners
import salt.utils.jid
import salt.exceptions
from salt.ext import six
# Import third party libs
try:
import psycopg2
import psycopg2.extras
HAS_PG = True
except ImportError:
HAS_PG = False
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pgjsonb'
PG_SAVE_LOAD_SQL = '''INSERT INTO jids (jid, load) VALUES (%(jid)s, %(load)s)'''
def __virtual__():
if not HAS_PG:
return False, 'Could not import pgjsonb returner; python-psycopg2 is not installed.'
return True
def _get_options(ret=None):
'''
Returns options used for the MySQL connection.
'''
defaults = {
'host': 'localhost',
'user': 'salt',
'pass': 'salt',
'db': 'salt',
'port': 5432
}
attrs = {
'host': 'host',
'user': 'user',
'pass': 'pass',
'db': 'db',
'port': 'port',
'sslmode': 'sslmode',
'sslcert': 'sslcert',
'sslkey': 'sslkey',
'sslrootcert': 'sslrootcert',
'sslcrl': 'sslcrl',
}
_options = salt.returners.get_returner_options('returner.{0}'.format(__virtualname__),
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__,
defaults=defaults)
# Ensure port is an int
if 'port' in _options:
_options['port'] = int(_options['port'])
return _options
@contextmanager
def _get_serv(ret=None, commit=False):
'''
Return a Pg cursor
'''
_options = _get_options(ret)
try:
# An empty ssl_options dictionary passed to MySQLdb.connect will
# effectively connect w/o SSL.
ssl_options = {
k: v for k, v in six.iteritems(_options)
if k in ['sslmode', 'sslcert', 'sslkey', 'sslrootcert', 'sslcrl']
}
conn = psycopg2.connect(
host=_options.get('host'),
port=_options.get('port'),
dbname=_options.get('db'),
user=_options.get('user'),
password=_options.get('pass'),
**ssl_options
)
except psycopg2.OperationalError as exc:
raise salt.exceptions.SaltMasterError('pgjsonb returner could not connect to database: {exc}'.format(exc=exc))
if conn.server_version is not None and conn.server_version >= 90500:
global PG_SAVE_LOAD_SQL
PG_SAVE_LOAD_SQL = '''INSERT INTO jids
(jid, load)
VALUES (%(jid)s, %(load)s)
ON CONFLICT (jid) DO UPDATE
SET load=%(load)s'''
cursor = conn.cursor()
try:
yield cursor
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
else:
if commit:
cursor.execute("COMMIT")
else:
cursor.execute("ROLLBACK")
finally:
conn.close()
def returner(ret):
'''
Return data to a Pg server
'''
try:
with _get_serv(ret, commit=True) as cur:
sql = '''INSERT INTO salt_returns
(fun, jid, return, id, success, full_ret, alter_time)
VALUES (%s, %s, %s, %s, %s, %s, to_timestamp(%s))'''
cur.execute(sql, (ret['fun'], ret['jid'],
psycopg2.extras.Json(ret['return']),
ret['id'],
ret.get('success', False),
psycopg2.extras.Json(ret),
time.time()))
except salt.exceptions.SaltMasterError:
log.critical('Could not store return with pgjsonb returner. PostgreSQL server unavailable.')
def event_return(events):
'''
Return event to Pg server
Requires that configuration be enabled via 'event_return'
option in master config.
'''
with _get_serv(events, commit=True) as cur:
for event in events:
tag = event.get('tag', '')
data = event.get('data', '')
sql = '''INSERT INTO salt_events (tag, data, master_id, alter_time)
VALUES (%s, %s, %s, to_timestamp(%s))'''
cur.execute(sql, (tag, psycopg2.extras.Json(data),
__opts__['id'], time.time()))
def save_load(jid, load, minions=None):
'''
Save the load to the specified jid id
'''
with _get_serv(commit=True) as cur:
try:
cur.execute(PG_SAVE_LOAD_SQL,
{'jid': jid, 'load': psycopg2.extras.Json(load)})
except psycopg2.IntegrityError:
# https://github.com/saltstack/salt/issues/22171
# Without this try/except we get tons of duplicate entry errors
# which result in job returns not being stored properly
pass
def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument
'''
Included for API consistency
'''
pass
def get_jid(jid):
'''
Return the information returned when the specified job id was executed
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT id, full_ret FROM salt_returns
WHERE jid = %s'''
cur.execute(sql, (jid,))
data = cur.fetchall()
ret = {}
if data:
for minion, full_ret in data:
ret[minion] = full_ret
return ret
def get_fun(fun):
'''
Return a dict of the last function called for all minions
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT s.id,s.jid, s.full_ret
FROM salt_returns s
JOIN ( SELECT MAX(`jid`) as jid
from salt_returns GROUP BY fun, id) max
ON s.jid = max.jid
WHERE s.fun = %s
'''
cur.execute(sql, (fun,))
data = cur.fetchall()
ret = {}
if data:
for minion, _, full_ret in data:
ret[minion] = full_ret
return ret
def get_jids():
'''
Return a list of all job ids
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT jid, load
FROM jids'''
cur.execute(sql)
data = cur.fetchall()
ret = {}
for jid, load in data:
ret[jid] = salt.utils.jid.format_jid_instance(jid, load)
return ret
def get_minions():
'''
Return a list of minions
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT DISTINCT id
FROM salt_returns'''
cur.execute(sql)
data = cur.fetchall()
ret = []
for minion in data:
ret.append(minion[0])
return ret
def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument
'''
Do any work necessary to prepare a JID, including sending a custom id
'''
return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
def _purge_jobs(timestamp):
'''
Purge records from the returner tables.
:param job_age_in_seconds: Purge jobs older than this
:return:
'''
with _get_serv() as cursor:
try:
sql = 'delete from jids where jid in (select distinct jid from salt_returns where alter_time < %s)'
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
try:
sql = 'delete from salt_returns where alter_time < %s'
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
try:
sql = 'delete from salt_events where alter_time < %s'
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
return True
def _archive_jobs(timestamp):
'''
Copy rows to a set of backup tables, then purge rows.
:param timestamp: Archive rows older than this timestamp
:return:
'''
source_tables = ['jids',
'salt_returns',
'salt_events']
with _get_serv() as cursor:
target_tables = {}
for table_name in source_tables:
try:
tmp_table_name = table_name + '_archive'
sql = 'create table IF NOT exists {0} (LIKE {1})'.format(tmp_table_name, table_name)
cursor.execute(sql)
cursor.execute('COMMIT')
target_tables[table_name] = tmp_table_name
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
try:
sql = 'insert into {0} select * from {1} where jid in (select distinct jid from salt_returns where alter_time < %s)'.format(target_tables['jids'], 'jids')
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
except Exception as e:
log.error(e)
raise
try:
sql = 'insert into {0} select * from {1} where alter_time < %s'.format(target_tables['salt_returns'], 'salt_returns')
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
try:
sql = 'insert into {0} select * from {1} where alter_time < %s'.format(target_tables['salt_events'], 'salt_events')
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
return _purge_jobs(timestamp)
def clean_old_jobs():
'''
Called in the master's event loop every loop_interval. Archives and/or
deletes the events and job details from the database.
:return:
'''
if __opts__.get('keep_jobs', False) and int(__opts__.get('keep_jobs', 0)) > 0:
try:
with _get_serv() as cur:
sql = "select (NOW() - interval '{0}' hour) as stamp;".format(__opts__['keep_jobs'])
cur.execute(sql)
rows = cur.fetchall()
stamp = rows[0][0]
if __opts__.get('archive_jobs', False):
_archive_jobs(stamp)
else:
_purge_jobs(stamp)
except Exception as e:
log.error(e)
|
saltstack/salt
|
salt/returners/pgjsonb.py
|
get_jid
|
python
|
def get_jid(jid):
'''
Return the information returned when the specified job id was executed
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT id, full_ret FROM salt_returns
WHERE jid = %s'''
cur.execute(sql, (jid,))
data = cur.fetchall()
ret = {}
if data:
for minion, full_ret in data:
ret[minion] = full_ret
return ret
|
Return the information returned when the specified job id was executed
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/pgjsonb.py#L361-L376
| null |
# -*- coding: utf-8 -*-
'''
Return data to a PostgreSQL server with json data stored in Pg's jsonb data type
:maintainer: Dave Boucha <dave@saltstack.com>, Seth House <shouse@saltstack.com>, C. R. Oldham <cr@saltstack.com>
:maturity: Stable
:depends: python-psycopg2
:platform: all
.. note::
There are three PostgreSQL returners. Any can function as an external
:ref:`master job cache <external-job-cache>`. but each has different
features. SaltStack recommends
:mod:`returners.pgjsonb <salt.returners.pgjsonb>` if you are working with
a version of PostgreSQL that has the appropriate native binary JSON types.
Otherwise, review
:mod:`returners.postgres <salt.returners.postgres>` and
:mod:`returners.postgres_local_cache <salt.returners.postgres_local_cache>`
to see which module best suits your particular needs.
To enable this returner, the minion will need the python client for PostgreSQL
installed and the following values configured in the minion or master
config. These are the defaults:
.. code-block:: yaml
returner.pgjsonb.host: 'salt'
returner.pgjsonb.user: 'salt'
returner.pgjsonb.pass: 'salt'
returner.pgjsonb.db: 'salt'
returner.pgjsonb.port: 5432
SSL is optional. The defaults are set to None. If you do not want to use SSL,
either exclude these options or set them to None.
.. code-block:: yaml
returner.pgjsonb.sslmode: None
returner.pgjsonb.sslcert: None
returner.pgjsonb.sslkey: None
returner.pgjsonb.sslrootcert: None
returner.pgjsonb.sslcrl: None
.. versionadded:: 2017.5.0
Alternative configuration values can be used by prefacing the configuration
with `alternative.`. Any values not found in the alternative configuration will
be pulled from the default location. As stated above, SSL configuration is
optional. The following ssl options are simply for illustration purposes:
.. code-block:: yaml
alternative.pgjsonb.host: 'salt'
alternative.pgjsonb.user: 'salt'
alternative.pgjsonb.pass: 'salt'
alternative.pgjsonb.db: 'salt'
alternative.pgjsonb.port: 5432
alternative.pgjsonb.ssl_ca: '/etc/pki/mysql/certs/localhost.pem'
alternative.pgjsonb.ssl_cert: '/etc/pki/mysql/certs/localhost.crt'
alternative.pgjsonb.ssl_key: '/etc/pki/mysql/certs/localhost.key'
Should you wish the returner data to be cleaned out every so often, set
``keep_jobs`` to the number of hours for the jobs to live in the tables.
Setting it to ``0`` or leaving it unset will cause the data to stay in the tables.
Should you wish to archive jobs in a different table for later processing,
set ``archive_jobs`` to True. Salt will create 3 archive tables;
- ``jids_archive``
- ``salt_returns_archive``
- ``salt_events_archive``
and move the contents of ``jids``, ``salt_returns``, and ``salt_events`` that are
more than ``keep_jobs`` hours old to these tables.
.. versionadded:: 2019.2.0
Use the following Pg database schema:
.. code-block:: sql
CREATE DATABASE salt
WITH ENCODING 'utf-8';
--
-- Table structure for table `jids`
--
DROP TABLE IF EXISTS jids;
CREATE TABLE jids (
jid varchar(255) NOT NULL primary key,
load jsonb NOT NULL
);
CREATE INDEX idx_jids_jsonb on jids
USING gin (load)
WITH (fastupdate=on);
--
-- Table structure for table `salt_returns`
--
DROP TABLE IF EXISTS salt_returns;
CREATE TABLE salt_returns (
fun varchar(50) NOT NULL,
jid varchar(255) NOT NULL,
return jsonb NOT NULL,
id varchar(255) NOT NULL,
success varchar(10) NOT NULL,
full_ret jsonb NOT NULL,
alter_time TIMESTAMP WITH TIME ZONE DEFAULT NOW());
CREATE INDEX idx_salt_returns_id ON salt_returns (id);
CREATE INDEX idx_salt_returns_jid ON salt_returns (jid);
CREATE INDEX idx_salt_returns_fun ON salt_returns (fun);
CREATE INDEX idx_salt_returns_return ON salt_returns
USING gin (return) with (fastupdate=on);
CREATE INDEX idx_salt_returns_full_ret ON salt_returns
USING gin (full_ret) with (fastupdate=on);
--
-- Table structure for table `salt_events`
--
DROP TABLE IF EXISTS salt_events;
DROP SEQUENCE IF EXISTS seq_salt_events_id;
CREATE SEQUENCE seq_salt_events_id;
CREATE TABLE salt_events (
id BIGINT NOT NULL UNIQUE DEFAULT nextval('seq_salt_events_id'),
tag varchar(255) NOT NULL,
data jsonb NOT NULL,
alter_time TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
master_id varchar(255) NOT NULL);
CREATE INDEX idx_salt_events_tag on
salt_events (tag);
CREATE INDEX idx_salt_events_data ON salt_events
USING gin (data) with (fastupdate=on);
Required python modules: Psycopg2
To use this returner, append '--return pgjsonb' to the salt command.
.. code-block:: bash
salt '*' test.ping --return pgjsonb
To use the alternative configuration, append '--return_config alternative' to the salt command.
.. versionadded:: 2015.5.0
.. code-block:: bash
salt '*' test.ping --return pgjsonb --return_config alternative
To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command.
.. versionadded:: 2016.3.0
.. code-block:: bash
salt '*' test.ping --return pgjsonb --return_kwargs '{"db": "another-salt"}'
'''
from __future__ import absolute_import, print_function, unicode_literals
# Let's not allow PyLint complain about string substitution
# pylint: disable=W1321,E1321
# Import python libs
from contextlib import contextmanager
import sys
import time
import logging
# Import salt libs
import salt.returners
import salt.utils.jid
import salt.exceptions
from salt.ext import six
# Import third party libs
try:
import psycopg2
import psycopg2.extras
HAS_PG = True
except ImportError:
HAS_PG = False
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pgjsonb'
PG_SAVE_LOAD_SQL = '''INSERT INTO jids (jid, load) VALUES (%(jid)s, %(load)s)'''
def __virtual__():
if not HAS_PG:
return False, 'Could not import pgjsonb returner; python-psycopg2 is not installed.'
return True
def _get_options(ret=None):
'''
Returns options used for the MySQL connection.
'''
defaults = {
'host': 'localhost',
'user': 'salt',
'pass': 'salt',
'db': 'salt',
'port': 5432
}
attrs = {
'host': 'host',
'user': 'user',
'pass': 'pass',
'db': 'db',
'port': 'port',
'sslmode': 'sslmode',
'sslcert': 'sslcert',
'sslkey': 'sslkey',
'sslrootcert': 'sslrootcert',
'sslcrl': 'sslcrl',
}
_options = salt.returners.get_returner_options('returner.{0}'.format(__virtualname__),
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__,
defaults=defaults)
# Ensure port is an int
if 'port' in _options:
_options['port'] = int(_options['port'])
return _options
@contextmanager
def _get_serv(ret=None, commit=False):
'''
Return a Pg cursor
'''
_options = _get_options(ret)
try:
# An empty ssl_options dictionary passed to MySQLdb.connect will
# effectively connect w/o SSL.
ssl_options = {
k: v for k, v in six.iteritems(_options)
if k in ['sslmode', 'sslcert', 'sslkey', 'sslrootcert', 'sslcrl']
}
conn = psycopg2.connect(
host=_options.get('host'),
port=_options.get('port'),
dbname=_options.get('db'),
user=_options.get('user'),
password=_options.get('pass'),
**ssl_options
)
except psycopg2.OperationalError as exc:
raise salt.exceptions.SaltMasterError('pgjsonb returner could not connect to database: {exc}'.format(exc=exc))
if conn.server_version is not None and conn.server_version >= 90500:
global PG_SAVE_LOAD_SQL
PG_SAVE_LOAD_SQL = '''INSERT INTO jids
(jid, load)
VALUES (%(jid)s, %(load)s)
ON CONFLICT (jid) DO UPDATE
SET load=%(load)s'''
cursor = conn.cursor()
try:
yield cursor
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
else:
if commit:
cursor.execute("COMMIT")
else:
cursor.execute("ROLLBACK")
finally:
conn.close()
def returner(ret):
'''
Return data to a Pg server
'''
try:
with _get_serv(ret, commit=True) as cur:
sql = '''INSERT INTO salt_returns
(fun, jid, return, id, success, full_ret, alter_time)
VALUES (%s, %s, %s, %s, %s, %s, to_timestamp(%s))'''
cur.execute(sql, (ret['fun'], ret['jid'],
psycopg2.extras.Json(ret['return']),
ret['id'],
ret.get('success', False),
psycopg2.extras.Json(ret),
time.time()))
except salt.exceptions.SaltMasterError:
log.critical('Could not store return with pgjsonb returner. PostgreSQL server unavailable.')
def event_return(events):
'''
Return event to Pg server
Requires that configuration be enabled via 'event_return'
option in master config.
'''
with _get_serv(events, commit=True) as cur:
for event in events:
tag = event.get('tag', '')
data = event.get('data', '')
sql = '''INSERT INTO salt_events (tag, data, master_id, alter_time)
VALUES (%s, %s, %s, to_timestamp(%s))'''
cur.execute(sql, (tag, psycopg2.extras.Json(data),
__opts__['id'], time.time()))
def save_load(jid, load, minions=None):
'''
Save the load to the specified jid id
'''
with _get_serv(commit=True) as cur:
try:
cur.execute(PG_SAVE_LOAD_SQL,
{'jid': jid, 'load': psycopg2.extras.Json(load)})
except psycopg2.IntegrityError:
# https://github.com/saltstack/salt/issues/22171
# Without this try/except we get tons of duplicate entry errors
# which result in job returns not being stored properly
pass
def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument
'''
Included for API consistency
'''
pass
def get_load(jid):
'''
Return the load data that marks a specified jid
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT load FROM jids WHERE jid = %s;'''
cur.execute(sql, (jid,))
data = cur.fetchone()
if data:
return data[0]
return {}
def get_fun(fun):
'''
Return a dict of the last function called for all minions
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT s.id,s.jid, s.full_ret
FROM salt_returns s
JOIN ( SELECT MAX(`jid`) as jid
from salt_returns GROUP BY fun, id) max
ON s.jid = max.jid
WHERE s.fun = %s
'''
cur.execute(sql, (fun,))
data = cur.fetchall()
ret = {}
if data:
for minion, _, full_ret in data:
ret[minion] = full_ret
return ret
def get_jids():
'''
Return a list of all job ids
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT jid, load
FROM jids'''
cur.execute(sql)
data = cur.fetchall()
ret = {}
for jid, load in data:
ret[jid] = salt.utils.jid.format_jid_instance(jid, load)
return ret
def get_minions():
'''
Return a list of minions
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT DISTINCT id
FROM salt_returns'''
cur.execute(sql)
data = cur.fetchall()
ret = []
for minion in data:
ret.append(minion[0])
return ret
def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument
'''
Do any work necessary to prepare a JID, including sending a custom id
'''
return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
def _purge_jobs(timestamp):
'''
Purge records from the returner tables.
:param job_age_in_seconds: Purge jobs older than this
:return:
'''
with _get_serv() as cursor:
try:
sql = 'delete from jids where jid in (select distinct jid from salt_returns where alter_time < %s)'
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
try:
sql = 'delete from salt_returns where alter_time < %s'
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
try:
sql = 'delete from salt_events where alter_time < %s'
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
return True
def _archive_jobs(timestamp):
'''
Copy rows to a set of backup tables, then purge rows.
:param timestamp: Archive rows older than this timestamp
:return:
'''
source_tables = ['jids',
'salt_returns',
'salt_events']
with _get_serv() as cursor:
target_tables = {}
for table_name in source_tables:
try:
tmp_table_name = table_name + '_archive'
sql = 'create table IF NOT exists {0} (LIKE {1})'.format(tmp_table_name, table_name)
cursor.execute(sql)
cursor.execute('COMMIT')
target_tables[table_name] = tmp_table_name
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
try:
sql = 'insert into {0} select * from {1} where jid in (select distinct jid from salt_returns where alter_time < %s)'.format(target_tables['jids'], 'jids')
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
except Exception as e:
log.error(e)
raise
try:
sql = 'insert into {0} select * from {1} where alter_time < %s'.format(target_tables['salt_returns'], 'salt_returns')
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
try:
sql = 'insert into {0} select * from {1} where alter_time < %s'.format(target_tables['salt_events'], 'salt_events')
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
return _purge_jobs(timestamp)
def clean_old_jobs():
'''
Called in the master's event loop every loop_interval. Archives and/or
deletes the events and job details from the database.
:return:
'''
if __opts__.get('keep_jobs', False) and int(__opts__.get('keep_jobs', 0)) > 0:
try:
with _get_serv() as cur:
sql = "select (NOW() - interval '{0}' hour) as stamp;".format(__opts__['keep_jobs'])
cur.execute(sql)
rows = cur.fetchall()
stamp = rows[0][0]
if __opts__.get('archive_jobs', False):
_archive_jobs(stamp)
else:
_purge_jobs(stamp)
except Exception as e:
log.error(e)
|
saltstack/salt
|
salt/returners/pgjsonb.py
|
get_fun
|
python
|
def get_fun(fun):
'''
Return a dict of the last function called for all minions
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT s.id,s.jid, s.full_ret
FROM salt_returns s
JOIN ( SELECT MAX(`jid`) as jid
from salt_returns GROUP BY fun, id) max
ON s.jid = max.jid
WHERE s.fun = %s
'''
cur.execute(sql, (fun,))
data = cur.fetchall()
ret = {}
if data:
for minion, _, full_ret in data:
ret[minion] = full_ret
return ret
|
Return a dict of the last function called for all minions
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/pgjsonb.py#L379-L400
| null |
# -*- coding: utf-8 -*-
'''
Return data to a PostgreSQL server with json data stored in Pg's jsonb data type
:maintainer: Dave Boucha <dave@saltstack.com>, Seth House <shouse@saltstack.com>, C. R. Oldham <cr@saltstack.com>
:maturity: Stable
:depends: python-psycopg2
:platform: all
.. note::
There are three PostgreSQL returners. Any can function as an external
:ref:`master job cache <external-job-cache>`. but each has different
features. SaltStack recommends
:mod:`returners.pgjsonb <salt.returners.pgjsonb>` if you are working with
a version of PostgreSQL that has the appropriate native binary JSON types.
Otherwise, review
:mod:`returners.postgres <salt.returners.postgres>` and
:mod:`returners.postgres_local_cache <salt.returners.postgres_local_cache>`
to see which module best suits your particular needs.
To enable this returner, the minion will need the python client for PostgreSQL
installed and the following values configured in the minion or master
config. These are the defaults:
.. code-block:: yaml
returner.pgjsonb.host: 'salt'
returner.pgjsonb.user: 'salt'
returner.pgjsonb.pass: 'salt'
returner.pgjsonb.db: 'salt'
returner.pgjsonb.port: 5432
SSL is optional. The defaults are set to None. If you do not want to use SSL,
either exclude these options or set them to None.
.. code-block:: yaml
returner.pgjsonb.sslmode: None
returner.pgjsonb.sslcert: None
returner.pgjsonb.sslkey: None
returner.pgjsonb.sslrootcert: None
returner.pgjsonb.sslcrl: None
.. versionadded:: 2017.5.0
Alternative configuration values can be used by prefacing the configuration
with `alternative.`. Any values not found in the alternative configuration will
be pulled from the default location. As stated above, SSL configuration is
optional. The following ssl options are simply for illustration purposes:
.. code-block:: yaml
alternative.pgjsonb.host: 'salt'
alternative.pgjsonb.user: 'salt'
alternative.pgjsonb.pass: 'salt'
alternative.pgjsonb.db: 'salt'
alternative.pgjsonb.port: 5432
alternative.pgjsonb.ssl_ca: '/etc/pki/mysql/certs/localhost.pem'
alternative.pgjsonb.ssl_cert: '/etc/pki/mysql/certs/localhost.crt'
alternative.pgjsonb.ssl_key: '/etc/pki/mysql/certs/localhost.key'
Should you wish the returner data to be cleaned out every so often, set
``keep_jobs`` to the number of hours for the jobs to live in the tables.
Setting it to ``0`` or leaving it unset will cause the data to stay in the tables.
Should you wish to archive jobs in a different table for later processing,
set ``archive_jobs`` to True. Salt will create 3 archive tables;
- ``jids_archive``
- ``salt_returns_archive``
- ``salt_events_archive``
and move the contents of ``jids``, ``salt_returns``, and ``salt_events`` that are
more than ``keep_jobs`` hours old to these tables.
.. versionadded:: 2019.2.0
Use the following Pg database schema:
.. code-block:: sql
CREATE DATABASE salt
WITH ENCODING 'utf-8';
--
-- Table structure for table `jids`
--
DROP TABLE IF EXISTS jids;
CREATE TABLE jids (
jid varchar(255) NOT NULL primary key,
load jsonb NOT NULL
);
CREATE INDEX idx_jids_jsonb on jids
USING gin (load)
WITH (fastupdate=on);
--
-- Table structure for table `salt_returns`
--
DROP TABLE IF EXISTS salt_returns;
CREATE TABLE salt_returns (
fun varchar(50) NOT NULL,
jid varchar(255) NOT NULL,
return jsonb NOT NULL,
id varchar(255) NOT NULL,
success varchar(10) NOT NULL,
full_ret jsonb NOT NULL,
alter_time TIMESTAMP WITH TIME ZONE DEFAULT NOW());
CREATE INDEX idx_salt_returns_id ON salt_returns (id);
CREATE INDEX idx_salt_returns_jid ON salt_returns (jid);
CREATE INDEX idx_salt_returns_fun ON salt_returns (fun);
CREATE INDEX idx_salt_returns_return ON salt_returns
USING gin (return) with (fastupdate=on);
CREATE INDEX idx_salt_returns_full_ret ON salt_returns
USING gin (full_ret) with (fastupdate=on);
--
-- Table structure for table `salt_events`
--
DROP TABLE IF EXISTS salt_events;
DROP SEQUENCE IF EXISTS seq_salt_events_id;
CREATE SEQUENCE seq_salt_events_id;
CREATE TABLE salt_events (
id BIGINT NOT NULL UNIQUE DEFAULT nextval('seq_salt_events_id'),
tag varchar(255) NOT NULL,
data jsonb NOT NULL,
alter_time TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
master_id varchar(255) NOT NULL);
CREATE INDEX idx_salt_events_tag on
salt_events (tag);
CREATE INDEX idx_salt_events_data ON salt_events
USING gin (data) with (fastupdate=on);
Required python modules: Psycopg2
To use this returner, append '--return pgjsonb' to the salt command.
.. code-block:: bash
salt '*' test.ping --return pgjsonb
To use the alternative configuration, append '--return_config alternative' to the salt command.
.. versionadded:: 2015.5.0
.. code-block:: bash
salt '*' test.ping --return pgjsonb --return_config alternative
To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command.
.. versionadded:: 2016.3.0
.. code-block:: bash
salt '*' test.ping --return pgjsonb --return_kwargs '{"db": "another-salt"}'
'''
from __future__ import absolute_import, print_function, unicode_literals
# Let's not allow PyLint complain about string substitution
# pylint: disable=W1321,E1321
# Import python libs
from contextlib import contextmanager
import sys
import time
import logging
# Import salt libs
import salt.returners
import salt.utils.jid
import salt.exceptions
from salt.ext import six
# Import third party libs
try:
import psycopg2
import psycopg2.extras
HAS_PG = True
except ImportError:
HAS_PG = False
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pgjsonb'
PG_SAVE_LOAD_SQL = '''INSERT INTO jids (jid, load) VALUES (%(jid)s, %(load)s)'''
def __virtual__():
if not HAS_PG:
return False, 'Could not import pgjsonb returner; python-psycopg2 is not installed.'
return True
def _get_options(ret=None):
'''
Returns options used for the MySQL connection.
'''
defaults = {
'host': 'localhost',
'user': 'salt',
'pass': 'salt',
'db': 'salt',
'port': 5432
}
attrs = {
'host': 'host',
'user': 'user',
'pass': 'pass',
'db': 'db',
'port': 'port',
'sslmode': 'sslmode',
'sslcert': 'sslcert',
'sslkey': 'sslkey',
'sslrootcert': 'sslrootcert',
'sslcrl': 'sslcrl',
}
_options = salt.returners.get_returner_options('returner.{0}'.format(__virtualname__),
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__,
defaults=defaults)
# Ensure port is an int
if 'port' in _options:
_options['port'] = int(_options['port'])
return _options
@contextmanager
def _get_serv(ret=None, commit=False):
'''
Return a Pg cursor
'''
_options = _get_options(ret)
try:
# An empty ssl_options dictionary passed to MySQLdb.connect will
# effectively connect w/o SSL.
ssl_options = {
k: v for k, v in six.iteritems(_options)
if k in ['sslmode', 'sslcert', 'sslkey', 'sslrootcert', 'sslcrl']
}
conn = psycopg2.connect(
host=_options.get('host'),
port=_options.get('port'),
dbname=_options.get('db'),
user=_options.get('user'),
password=_options.get('pass'),
**ssl_options
)
except psycopg2.OperationalError as exc:
raise salt.exceptions.SaltMasterError('pgjsonb returner could not connect to database: {exc}'.format(exc=exc))
if conn.server_version is not None and conn.server_version >= 90500:
global PG_SAVE_LOAD_SQL
PG_SAVE_LOAD_SQL = '''INSERT INTO jids
(jid, load)
VALUES (%(jid)s, %(load)s)
ON CONFLICT (jid) DO UPDATE
SET load=%(load)s'''
cursor = conn.cursor()
try:
yield cursor
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
else:
if commit:
cursor.execute("COMMIT")
else:
cursor.execute("ROLLBACK")
finally:
conn.close()
def returner(ret):
'''
Return data to a Pg server
'''
try:
with _get_serv(ret, commit=True) as cur:
sql = '''INSERT INTO salt_returns
(fun, jid, return, id, success, full_ret, alter_time)
VALUES (%s, %s, %s, %s, %s, %s, to_timestamp(%s))'''
cur.execute(sql, (ret['fun'], ret['jid'],
psycopg2.extras.Json(ret['return']),
ret['id'],
ret.get('success', False),
psycopg2.extras.Json(ret),
time.time()))
except salt.exceptions.SaltMasterError:
log.critical('Could not store return with pgjsonb returner. PostgreSQL server unavailable.')
def event_return(events):
'''
Return event to Pg server
Requires that configuration be enabled via 'event_return'
option in master config.
'''
with _get_serv(events, commit=True) as cur:
for event in events:
tag = event.get('tag', '')
data = event.get('data', '')
sql = '''INSERT INTO salt_events (tag, data, master_id, alter_time)
VALUES (%s, %s, %s, to_timestamp(%s))'''
cur.execute(sql, (tag, psycopg2.extras.Json(data),
__opts__['id'], time.time()))
def save_load(jid, load, minions=None):
'''
Save the load to the specified jid id
'''
with _get_serv(commit=True) as cur:
try:
cur.execute(PG_SAVE_LOAD_SQL,
{'jid': jid, 'load': psycopg2.extras.Json(load)})
except psycopg2.IntegrityError:
# https://github.com/saltstack/salt/issues/22171
# Without this try/except we get tons of duplicate entry errors
# which result in job returns not being stored properly
pass
def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument
'''
Included for API consistency
'''
pass
def get_load(jid):
'''
Return the load data that marks a specified jid
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT load FROM jids WHERE jid = %s;'''
cur.execute(sql, (jid,))
data = cur.fetchone()
if data:
return data[0]
return {}
def get_jid(jid):
'''
Return the information returned when the specified job id was executed
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT id, full_ret FROM salt_returns
WHERE jid = %s'''
cur.execute(sql, (jid,))
data = cur.fetchall()
ret = {}
if data:
for minion, full_ret in data:
ret[minion] = full_ret
return ret
def get_jids():
'''
Return a list of all job ids
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT jid, load
FROM jids'''
cur.execute(sql)
data = cur.fetchall()
ret = {}
for jid, load in data:
ret[jid] = salt.utils.jid.format_jid_instance(jid, load)
return ret
def get_minions():
'''
Return a list of minions
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT DISTINCT id
FROM salt_returns'''
cur.execute(sql)
data = cur.fetchall()
ret = []
for minion in data:
ret.append(minion[0])
return ret
def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument
'''
Do any work necessary to prepare a JID, including sending a custom id
'''
return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
def _purge_jobs(timestamp):
'''
Purge records from the returner tables.
:param job_age_in_seconds: Purge jobs older than this
:return:
'''
with _get_serv() as cursor:
try:
sql = 'delete from jids where jid in (select distinct jid from salt_returns where alter_time < %s)'
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
try:
sql = 'delete from salt_returns where alter_time < %s'
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
try:
sql = 'delete from salt_events where alter_time < %s'
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
return True
def _archive_jobs(timestamp):
'''
Copy rows to a set of backup tables, then purge rows.
:param timestamp: Archive rows older than this timestamp
:return:
'''
source_tables = ['jids',
'salt_returns',
'salt_events']
with _get_serv() as cursor:
target_tables = {}
for table_name in source_tables:
try:
tmp_table_name = table_name + '_archive'
sql = 'create table IF NOT exists {0} (LIKE {1})'.format(tmp_table_name, table_name)
cursor.execute(sql)
cursor.execute('COMMIT')
target_tables[table_name] = tmp_table_name
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
try:
sql = 'insert into {0} select * from {1} where jid in (select distinct jid from salt_returns where alter_time < %s)'.format(target_tables['jids'], 'jids')
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
except Exception as e:
log.error(e)
raise
try:
sql = 'insert into {0} select * from {1} where alter_time < %s'.format(target_tables['salt_returns'], 'salt_returns')
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
try:
sql = 'insert into {0} select * from {1} where alter_time < %s'.format(target_tables['salt_events'], 'salt_events')
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
return _purge_jobs(timestamp)
def clean_old_jobs():
'''
Called in the master's event loop every loop_interval. Archives and/or
deletes the events and job details from the database.
:return:
'''
if __opts__.get('keep_jobs', False) and int(__opts__.get('keep_jobs', 0)) > 0:
try:
with _get_serv() as cur:
sql = "select (NOW() - interval '{0}' hour) as stamp;".format(__opts__['keep_jobs'])
cur.execute(sql)
rows = cur.fetchall()
stamp = rows[0][0]
if __opts__.get('archive_jobs', False):
_archive_jobs(stamp)
else:
_purge_jobs(stamp)
except Exception as e:
log.error(e)
|
saltstack/salt
|
salt/returners/pgjsonb.py
|
_purge_jobs
|
python
|
def _purge_jobs(timestamp):
'''
Purge records from the returner tables.
:param job_age_in_seconds: Purge jobs older than this
:return:
'''
with _get_serv() as cursor:
try:
sql = 'delete from jids where jid in (select distinct jid from salt_returns where alter_time < %s)'
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
try:
sql = 'delete from salt_returns where alter_time < %s'
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
try:
sql = 'delete from salt_events where alter_time < %s'
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
return True
|
Purge records from the returner tables.
:param job_age_in_seconds: Purge jobs older than this
:return:
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/pgjsonb.py#L444-L481
| null |
# -*- coding: utf-8 -*-
'''
Return data to a PostgreSQL server with json data stored in Pg's jsonb data type
:maintainer: Dave Boucha <dave@saltstack.com>, Seth House <shouse@saltstack.com>, C. R. Oldham <cr@saltstack.com>
:maturity: Stable
:depends: python-psycopg2
:platform: all
.. note::
There are three PostgreSQL returners. Any can function as an external
:ref:`master job cache <external-job-cache>`. but each has different
features. SaltStack recommends
:mod:`returners.pgjsonb <salt.returners.pgjsonb>` if you are working with
a version of PostgreSQL that has the appropriate native binary JSON types.
Otherwise, review
:mod:`returners.postgres <salt.returners.postgres>` and
:mod:`returners.postgres_local_cache <salt.returners.postgres_local_cache>`
to see which module best suits your particular needs.
To enable this returner, the minion will need the python client for PostgreSQL
installed and the following values configured in the minion or master
config. These are the defaults:
.. code-block:: yaml
returner.pgjsonb.host: 'salt'
returner.pgjsonb.user: 'salt'
returner.pgjsonb.pass: 'salt'
returner.pgjsonb.db: 'salt'
returner.pgjsonb.port: 5432
SSL is optional. The defaults are set to None. If you do not want to use SSL,
either exclude these options or set them to None.
.. code-block:: yaml
returner.pgjsonb.sslmode: None
returner.pgjsonb.sslcert: None
returner.pgjsonb.sslkey: None
returner.pgjsonb.sslrootcert: None
returner.pgjsonb.sslcrl: None
.. versionadded:: 2017.5.0
Alternative configuration values can be used by prefacing the configuration
with `alternative.`. Any values not found in the alternative configuration will
be pulled from the default location. As stated above, SSL configuration is
optional. The following ssl options are simply for illustration purposes:
.. code-block:: yaml
alternative.pgjsonb.host: 'salt'
alternative.pgjsonb.user: 'salt'
alternative.pgjsonb.pass: 'salt'
alternative.pgjsonb.db: 'salt'
alternative.pgjsonb.port: 5432
alternative.pgjsonb.ssl_ca: '/etc/pki/mysql/certs/localhost.pem'
alternative.pgjsonb.ssl_cert: '/etc/pki/mysql/certs/localhost.crt'
alternative.pgjsonb.ssl_key: '/etc/pki/mysql/certs/localhost.key'
Should you wish the returner data to be cleaned out every so often, set
``keep_jobs`` to the number of hours for the jobs to live in the tables.
Setting it to ``0`` or leaving it unset will cause the data to stay in the tables.
Should you wish to archive jobs in a different table for later processing,
set ``archive_jobs`` to True. Salt will create 3 archive tables;
- ``jids_archive``
- ``salt_returns_archive``
- ``salt_events_archive``
and move the contents of ``jids``, ``salt_returns``, and ``salt_events`` that are
more than ``keep_jobs`` hours old to these tables.
.. versionadded:: 2019.2.0
Use the following Pg database schema:
.. code-block:: sql
CREATE DATABASE salt
WITH ENCODING 'utf-8';
--
-- Table structure for table `jids`
--
DROP TABLE IF EXISTS jids;
CREATE TABLE jids (
jid varchar(255) NOT NULL primary key,
load jsonb NOT NULL
);
CREATE INDEX idx_jids_jsonb on jids
USING gin (load)
WITH (fastupdate=on);
--
-- Table structure for table `salt_returns`
--
DROP TABLE IF EXISTS salt_returns;
CREATE TABLE salt_returns (
fun varchar(50) NOT NULL,
jid varchar(255) NOT NULL,
return jsonb NOT NULL,
id varchar(255) NOT NULL,
success varchar(10) NOT NULL,
full_ret jsonb NOT NULL,
alter_time TIMESTAMP WITH TIME ZONE DEFAULT NOW());
CREATE INDEX idx_salt_returns_id ON salt_returns (id);
CREATE INDEX idx_salt_returns_jid ON salt_returns (jid);
CREATE INDEX idx_salt_returns_fun ON salt_returns (fun);
CREATE INDEX idx_salt_returns_return ON salt_returns
USING gin (return) with (fastupdate=on);
CREATE INDEX idx_salt_returns_full_ret ON salt_returns
USING gin (full_ret) with (fastupdate=on);
--
-- Table structure for table `salt_events`
--
DROP TABLE IF EXISTS salt_events;
DROP SEQUENCE IF EXISTS seq_salt_events_id;
CREATE SEQUENCE seq_salt_events_id;
CREATE TABLE salt_events (
id BIGINT NOT NULL UNIQUE DEFAULT nextval('seq_salt_events_id'),
tag varchar(255) NOT NULL,
data jsonb NOT NULL,
alter_time TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
master_id varchar(255) NOT NULL);
CREATE INDEX idx_salt_events_tag on
salt_events (tag);
CREATE INDEX idx_salt_events_data ON salt_events
USING gin (data) with (fastupdate=on);
Required python modules: Psycopg2
To use this returner, append '--return pgjsonb' to the salt command.
.. code-block:: bash
salt '*' test.ping --return pgjsonb
To use the alternative configuration, append '--return_config alternative' to the salt command.
.. versionadded:: 2015.5.0
.. code-block:: bash
salt '*' test.ping --return pgjsonb --return_config alternative
To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command.
.. versionadded:: 2016.3.0
.. code-block:: bash
salt '*' test.ping --return pgjsonb --return_kwargs '{"db": "another-salt"}'
'''
from __future__ import absolute_import, print_function, unicode_literals
# Let's not allow PyLint complain about string substitution
# pylint: disable=W1321,E1321
# Import python libs
from contextlib import contextmanager
import sys
import time
import logging
# Import salt libs
import salt.returners
import salt.utils.jid
import salt.exceptions
from salt.ext import six
# Import third party libs
try:
import psycopg2
import psycopg2.extras
HAS_PG = True
except ImportError:
HAS_PG = False
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pgjsonb'
PG_SAVE_LOAD_SQL = '''INSERT INTO jids (jid, load) VALUES (%(jid)s, %(load)s)'''
def __virtual__():
if not HAS_PG:
return False, 'Could not import pgjsonb returner; python-psycopg2 is not installed.'
return True
def _get_options(ret=None):
'''
Returns options used for the MySQL connection.
'''
defaults = {
'host': 'localhost',
'user': 'salt',
'pass': 'salt',
'db': 'salt',
'port': 5432
}
attrs = {
'host': 'host',
'user': 'user',
'pass': 'pass',
'db': 'db',
'port': 'port',
'sslmode': 'sslmode',
'sslcert': 'sslcert',
'sslkey': 'sslkey',
'sslrootcert': 'sslrootcert',
'sslcrl': 'sslcrl',
}
_options = salt.returners.get_returner_options('returner.{0}'.format(__virtualname__),
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__,
defaults=defaults)
# Ensure port is an int
if 'port' in _options:
_options['port'] = int(_options['port'])
return _options
@contextmanager
def _get_serv(ret=None, commit=False):
'''
Return a Pg cursor
'''
_options = _get_options(ret)
try:
# An empty ssl_options dictionary passed to MySQLdb.connect will
# effectively connect w/o SSL.
ssl_options = {
k: v for k, v in six.iteritems(_options)
if k in ['sslmode', 'sslcert', 'sslkey', 'sslrootcert', 'sslcrl']
}
conn = psycopg2.connect(
host=_options.get('host'),
port=_options.get('port'),
dbname=_options.get('db'),
user=_options.get('user'),
password=_options.get('pass'),
**ssl_options
)
except psycopg2.OperationalError as exc:
raise salt.exceptions.SaltMasterError('pgjsonb returner could not connect to database: {exc}'.format(exc=exc))
if conn.server_version is not None and conn.server_version >= 90500:
global PG_SAVE_LOAD_SQL
PG_SAVE_LOAD_SQL = '''INSERT INTO jids
(jid, load)
VALUES (%(jid)s, %(load)s)
ON CONFLICT (jid) DO UPDATE
SET load=%(load)s'''
cursor = conn.cursor()
try:
yield cursor
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
else:
if commit:
cursor.execute("COMMIT")
else:
cursor.execute("ROLLBACK")
finally:
conn.close()
def returner(ret):
'''
Return data to a Pg server
'''
try:
with _get_serv(ret, commit=True) as cur:
sql = '''INSERT INTO salt_returns
(fun, jid, return, id, success, full_ret, alter_time)
VALUES (%s, %s, %s, %s, %s, %s, to_timestamp(%s))'''
cur.execute(sql, (ret['fun'], ret['jid'],
psycopg2.extras.Json(ret['return']),
ret['id'],
ret.get('success', False),
psycopg2.extras.Json(ret),
time.time()))
except salt.exceptions.SaltMasterError:
log.critical('Could not store return with pgjsonb returner. PostgreSQL server unavailable.')
def event_return(events):
'''
Return event to Pg server
Requires that configuration be enabled via 'event_return'
option in master config.
'''
with _get_serv(events, commit=True) as cur:
for event in events:
tag = event.get('tag', '')
data = event.get('data', '')
sql = '''INSERT INTO salt_events (tag, data, master_id, alter_time)
VALUES (%s, %s, %s, to_timestamp(%s))'''
cur.execute(sql, (tag, psycopg2.extras.Json(data),
__opts__['id'], time.time()))
def save_load(jid, load, minions=None):
'''
Save the load to the specified jid id
'''
with _get_serv(commit=True) as cur:
try:
cur.execute(PG_SAVE_LOAD_SQL,
{'jid': jid, 'load': psycopg2.extras.Json(load)})
except psycopg2.IntegrityError:
# https://github.com/saltstack/salt/issues/22171
# Without this try/except we get tons of duplicate entry errors
# which result in job returns not being stored properly
pass
def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument
'''
Included for API consistency
'''
pass
def get_load(jid):
'''
Return the load data that marks a specified jid
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT load FROM jids WHERE jid = %s;'''
cur.execute(sql, (jid,))
data = cur.fetchone()
if data:
return data[0]
return {}
def get_jid(jid):
'''
Return the information returned when the specified job id was executed
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT id, full_ret FROM salt_returns
WHERE jid = %s'''
cur.execute(sql, (jid,))
data = cur.fetchall()
ret = {}
if data:
for minion, full_ret in data:
ret[minion] = full_ret
return ret
def get_fun(fun):
'''
Return a dict of the last function called for all minions
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT s.id,s.jid, s.full_ret
FROM salt_returns s
JOIN ( SELECT MAX(`jid`) as jid
from salt_returns GROUP BY fun, id) max
ON s.jid = max.jid
WHERE s.fun = %s
'''
cur.execute(sql, (fun,))
data = cur.fetchall()
ret = {}
if data:
for minion, _, full_ret in data:
ret[minion] = full_ret
return ret
def get_jids():
'''
Return a list of all job ids
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT jid, load
FROM jids'''
cur.execute(sql)
data = cur.fetchall()
ret = {}
for jid, load in data:
ret[jid] = salt.utils.jid.format_jid_instance(jid, load)
return ret
def get_minions():
'''
Return a list of minions
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT DISTINCT id
FROM salt_returns'''
cur.execute(sql)
data = cur.fetchall()
ret = []
for minion in data:
ret.append(minion[0])
return ret
def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument
'''
Do any work necessary to prepare a JID, including sending a custom id
'''
return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
def _archive_jobs(timestamp):
'''
Copy rows to a set of backup tables, then purge rows.
:param timestamp: Archive rows older than this timestamp
:return:
'''
source_tables = ['jids',
'salt_returns',
'salt_events']
with _get_serv() as cursor:
target_tables = {}
for table_name in source_tables:
try:
tmp_table_name = table_name + '_archive'
sql = 'create table IF NOT exists {0} (LIKE {1})'.format(tmp_table_name, table_name)
cursor.execute(sql)
cursor.execute('COMMIT')
target_tables[table_name] = tmp_table_name
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
try:
sql = 'insert into {0} select * from {1} where jid in (select distinct jid from salt_returns where alter_time < %s)'.format(target_tables['jids'], 'jids')
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
except Exception as e:
log.error(e)
raise
try:
sql = 'insert into {0} select * from {1} where alter_time < %s'.format(target_tables['salt_returns'], 'salt_returns')
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
try:
sql = 'insert into {0} select * from {1} where alter_time < %s'.format(target_tables['salt_events'], 'salt_events')
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
return _purge_jobs(timestamp)
def clean_old_jobs():
'''
Called in the master's event loop every loop_interval. Archives and/or
deletes the events and job details from the database.
:return:
'''
if __opts__.get('keep_jobs', False) and int(__opts__.get('keep_jobs', 0)) > 0:
try:
with _get_serv() as cur:
sql = "select (NOW() - interval '{0}' hour) as stamp;".format(__opts__['keep_jobs'])
cur.execute(sql)
rows = cur.fetchall()
stamp = rows[0][0]
if __opts__.get('archive_jobs', False):
_archive_jobs(stamp)
else:
_purge_jobs(stamp)
except Exception as e:
log.error(e)
|
saltstack/salt
|
salt/returners/pgjsonb.py
|
_archive_jobs
|
python
|
def _archive_jobs(timestamp):
'''
Copy rows to a set of backup tables, then purge rows.
:param timestamp: Archive rows older than this timestamp
:return:
'''
source_tables = ['jids',
'salt_returns',
'salt_events']
with _get_serv() as cursor:
target_tables = {}
for table_name in source_tables:
try:
tmp_table_name = table_name + '_archive'
sql = 'create table IF NOT exists {0} (LIKE {1})'.format(tmp_table_name, table_name)
cursor.execute(sql)
cursor.execute('COMMIT')
target_tables[table_name] = tmp_table_name
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
try:
sql = 'insert into {0} select * from {1} where jid in (select distinct jid from salt_returns where alter_time < %s)'.format(target_tables['jids'], 'jids')
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
except Exception as e:
log.error(e)
raise
try:
sql = 'insert into {0} select * from {1} where alter_time < %s'.format(target_tables['salt_returns'], 'salt_returns')
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
try:
sql = 'insert into {0} select * from {1} where alter_time < %s'.format(target_tables['salt_events'], 'salt_events')
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
return _purge_jobs(timestamp)
|
Copy rows to a set of backup tables, then purge rows.
:param timestamp: Archive rows older than this timestamp
:return:
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/pgjsonb.py#L484-L542
| null |
# -*- coding: utf-8 -*-
'''
Return data to a PostgreSQL server with json data stored in Pg's jsonb data type
:maintainer: Dave Boucha <dave@saltstack.com>, Seth House <shouse@saltstack.com>, C. R. Oldham <cr@saltstack.com>
:maturity: Stable
:depends: python-psycopg2
:platform: all
.. note::
There are three PostgreSQL returners. Any can function as an external
:ref:`master job cache <external-job-cache>`. but each has different
features. SaltStack recommends
:mod:`returners.pgjsonb <salt.returners.pgjsonb>` if you are working with
a version of PostgreSQL that has the appropriate native binary JSON types.
Otherwise, review
:mod:`returners.postgres <salt.returners.postgres>` and
:mod:`returners.postgres_local_cache <salt.returners.postgres_local_cache>`
to see which module best suits your particular needs.
To enable this returner, the minion will need the python client for PostgreSQL
installed and the following values configured in the minion or master
config. These are the defaults:
.. code-block:: yaml
returner.pgjsonb.host: 'salt'
returner.pgjsonb.user: 'salt'
returner.pgjsonb.pass: 'salt'
returner.pgjsonb.db: 'salt'
returner.pgjsonb.port: 5432
SSL is optional. The defaults are set to None. If you do not want to use SSL,
either exclude these options or set them to None.
.. code-block:: yaml
returner.pgjsonb.sslmode: None
returner.pgjsonb.sslcert: None
returner.pgjsonb.sslkey: None
returner.pgjsonb.sslrootcert: None
returner.pgjsonb.sslcrl: None
.. versionadded:: 2017.5.0
Alternative configuration values can be used by prefacing the configuration
with `alternative.`. Any values not found in the alternative configuration will
be pulled from the default location. As stated above, SSL configuration is
optional. The following ssl options are simply for illustration purposes:
.. code-block:: yaml
alternative.pgjsonb.host: 'salt'
alternative.pgjsonb.user: 'salt'
alternative.pgjsonb.pass: 'salt'
alternative.pgjsonb.db: 'salt'
alternative.pgjsonb.port: 5432
alternative.pgjsonb.ssl_ca: '/etc/pki/mysql/certs/localhost.pem'
alternative.pgjsonb.ssl_cert: '/etc/pki/mysql/certs/localhost.crt'
alternative.pgjsonb.ssl_key: '/etc/pki/mysql/certs/localhost.key'
Should you wish the returner data to be cleaned out every so often, set
``keep_jobs`` to the number of hours for the jobs to live in the tables.
Setting it to ``0`` or leaving it unset will cause the data to stay in the tables.
Should you wish to archive jobs in a different table for later processing,
set ``archive_jobs`` to True. Salt will create 3 archive tables;
- ``jids_archive``
- ``salt_returns_archive``
- ``salt_events_archive``
and move the contents of ``jids``, ``salt_returns``, and ``salt_events`` that are
more than ``keep_jobs`` hours old to these tables.
.. versionadded:: 2019.2.0
Use the following Pg database schema:
.. code-block:: sql
CREATE DATABASE salt
WITH ENCODING 'utf-8';
--
-- Table structure for table `jids`
--
DROP TABLE IF EXISTS jids;
CREATE TABLE jids (
jid varchar(255) NOT NULL primary key,
load jsonb NOT NULL
);
CREATE INDEX idx_jids_jsonb on jids
USING gin (load)
WITH (fastupdate=on);
--
-- Table structure for table `salt_returns`
--
DROP TABLE IF EXISTS salt_returns;
CREATE TABLE salt_returns (
fun varchar(50) NOT NULL,
jid varchar(255) NOT NULL,
return jsonb NOT NULL,
id varchar(255) NOT NULL,
success varchar(10) NOT NULL,
full_ret jsonb NOT NULL,
alter_time TIMESTAMP WITH TIME ZONE DEFAULT NOW());
CREATE INDEX idx_salt_returns_id ON salt_returns (id);
CREATE INDEX idx_salt_returns_jid ON salt_returns (jid);
CREATE INDEX idx_salt_returns_fun ON salt_returns (fun);
CREATE INDEX idx_salt_returns_return ON salt_returns
USING gin (return) with (fastupdate=on);
CREATE INDEX idx_salt_returns_full_ret ON salt_returns
USING gin (full_ret) with (fastupdate=on);
--
-- Table structure for table `salt_events`
--
DROP TABLE IF EXISTS salt_events;
DROP SEQUENCE IF EXISTS seq_salt_events_id;
CREATE SEQUENCE seq_salt_events_id;
CREATE TABLE salt_events (
id BIGINT NOT NULL UNIQUE DEFAULT nextval('seq_salt_events_id'),
tag varchar(255) NOT NULL,
data jsonb NOT NULL,
alter_time TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
master_id varchar(255) NOT NULL);
CREATE INDEX idx_salt_events_tag on
salt_events (tag);
CREATE INDEX idx_salt_events_data ON salt_events
USING gin (data) with (fastupdate=on);
Required python modules: Psycopg2
To use this returner, append '--return pgjsonb' to the salt command.
.. code-block:: bash
salt '*' test.ping --return pgjsonb
To use the alternative configuration, append '--return_config alternative' to the salt command.
.. versionadded:: 2015.5.0
.. code-block:: bash
salt '*' test.ping --return pgjsonb --return_config alternative
To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command.
.. versionadded:: 2016.3.0
.. code-block:: bash
salt '*' test.ping --return pgjsonb --return_kwargs '{"db": "another-salt"}'
'''
from __future__ import absolute_import, print_function, unicode_literals
# Let's not allow PyLint complain about string substitution
# pylint: disable=W1321,E1321
# Import python libs
from contextlib import contextmanager
import sys
import time
import logging
# Import salt libs
import salt.returners
import salt.utils.jid
import salt.exceptions
from salt.ext import six
# Import third party libs
try:
import psycopg2
import psycopg2.extras
HAS_PG = True
except ImportError:
HAS_PG = False
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pgjsonb'
PG_SAVE_LOAD_SQL = '''INSERT INTO jids (jid, load) VALUES (%(jid)s, %(load)s)'''
def __virtual__():
if not HAS_PG:
return False, 'Could not import pgjsonb returner; python-psycopg2 is not installed.'
return True
def _get_options(ret=None):
'''
Returns options used for the MySQL connection.
'''
defaults = {
'host': 'localhost',
'user': 'salt',
'pass': 'salt',
'db': 'salt',
'port': 5432
}
attrs = {
'host': 'host',
'user': 'user',
'pass': 'pass',
'db': 'db',
'port': 'port',
'sslmode': 'sslmode',
'sslcert': 'sslcert',
'sslkey': 'sslkey',
'sslrootcert': 'sslrootcert',
'sslcrl': 'sslcrl',
}
_options = salt.returners.get_returner_options('returner.{0}'.format(__virtualname__),
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__,
defaults=defaults)
# Ensure port is an int
if 'port' in _options:
_options['port'] = int(_options['port'])
return _options
@contextmanager
def _get_serv(ret=None, commit=False):
'''
Return a Pg cursor
'''
_options = _get_options(ret)
try:
# An empty ssl_options dictionary passed to MySQLdb.connect will
# effectively connect w/o SSL.
ssl_options = {
k: v for k, v in six.iteritems(_options)
if k in ['sslmode', 'sslcert', 'sslkey', 'sslrootcert', 'sslcrl']
}
conn = psycopg2.connect(
host=_options.get('host'),
port=_options.get('port'),
dbname=_options.get('db'),
user=_options.get('user'),
password=_options.get('pass'),
**ssl_options
)
except psycopg2.OperationalError as exc:
raise salt.exceptions.SaltMasterError('pgjsonb returner could not connect to database: {exc}'.format(exc=exc))
if conn.server_version is not None and conn.server_version >= 90500:
global PG_SAVE_LOAD_SQL
PG_SAVE_LOAD_SQL = '''INSERT INTO jids
(jid, load)
VALUES (%(jid)s, %(load)s)
ON CONFLICT (jid) DO UPDATE
SET load=%(load)s'''
cursor = conn.cursor()
try:
yield cursor
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
else:
if commit:
cursor.execute("COMMIT")
else:
cursor.execute("ROLLBACK")
finally:
conn.close()
def returner(ret):
'''
Return data to a Pg server
'''
try:
with _get_serv(ret, commit=True) as cur:
sql = '''INSERT INTO salt_returns
(fun, jid, return, id, success, full_ret, alter_time)
VALUES (%s, %s, %s, %s, %s, %s, to_timestamp(%s))'''
cur.execute(sql, (ret['fun'], ret['jid'],
psycopg2.extras.Json(ret['return']),
ret['id'],
ret.get('success', False),
psycopg2.extras.Json(ret),
time.time()))
except salt.exceptions.SaltMasterError:
log.critical('Could not store return with pgjsonb returner. PostgreSQL server unavailable.')
def event_return(events):
'''
Return event to Pg server
Requires that configuration be enabled via 'event_return'
option in master config.
'''
with _get_serv(events, commit=True) as cur:
for event in events:
tag = event.get('tag', '')
data = event.get('data', '')
sql = '''INSERT INTO salt_events (tag, data, master_id, alter_time)
VALUES (%s, %s, %s, to_timestamp(%s))'''
cur.execute(sql, (tag, psycopg2.extras.Json(data),
__opts__['id'], time.time()))
def save_load(jid, load, minions=None):
'''
Save the load to the specified jid id
'''
with _get_serv(commit=True) as cur:
try:
cur.execute(PG_SAVE_LOAD_SQL,
{'jid': jid, 'load': psycopg2.extras.Json(load)})
except psycopg2.IntegrityError:
# https://github.com/saltstack/salt/issues/22171
# Without this try/except we get tons of duplicate entry errors
# which result in job returns not being stored properly
pass
def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument
'''
Included for API consistency
'''
pass
def get_load(jid):
'''
Return the load data that marks a specified jid
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT load FROM jids WHERE jid = %s;'''
cur.execute(sql, (jid,))
data = cur.fetchone()
if data:
return data[0]
return {}
def get_jid(jid):
'''
Return the information returned when the specified job id was executed
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT id, full_ret FROM salt_returns
WHERE jid = %s'''
cur.execute(sql, (jid,))
data = cur.fetchall()
ret = {}
if data:
for minion, full_ret in data:
ret[minion] = full_ret
return ret
def get_fun(fun):
'''
Return a dict of the last function called for all minions
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT s.id,s.jid, s.full_ret
FROM salt_returns s
JOIN ( SELECT MAX(`jid`) as jid
from salt_returns GROUP BY fun, id) max
ON s.jid = max.jid
WHERE s.fun = %s
'''
cur.execute(sql, (fun,))
data = cur.fetchall()
ret = {}
if data:
for minion, _, full_ret in data:
ret[minion] = full_ret
return ret
def get_jids():
'''
Return a list of all job ids
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT jid, load
FROM jids'''
cur.execute(sql)
data = cur.fetchall()
ret = {}
for jid, load in data:
ret[jid] = salt.utils.jid.format_jid_instance(jid, load)
return ret
def get_minions():
'''
Return a list of minions
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT DISTINCT id
FROM salt_returns'''
cur.execute(sql)
data = cur.fetchall()
ret = []
for minion in data:
ret.append(minion[0])
return ret
def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument
'''
Do any work necessary to prepare a JID, including sending a custom id
'''
return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
def _purge_jobs(timestamp):
'''
Purge records from the returner tables.
:param job_age_in_seconds: Purge jobs older than this
:return:
'''
with _get_serv() as cursor:
try:
sql = 'delete from jids where jid in (select distinct jid from salt_returns where alter_time < %s)'
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
try:
sql = 'delete from salt_returns where alter_time < %s'
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
try:
sql = 'delete from salt_events where alter_time < %s'
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
return True
def clean_old_jobs():
'''
Called in the master's event loop every loop_interval. Archives and/or
deletes the events and job details from the database.
:return:
'''
if __opts__.get('keep_jobs', False) and int(__opts__.get('keep_jobs', 0)) > 0:
try:
with _get_serv() as cur:
sql = "select (NOW() - interval '{0}' hour) as stamp;".format(__opts__['keep_jobs'])
cur.execute(sql)
rows = cur.fetchall()
stamp = rows[0][0]
if __opts__.get('archive_jobs', False):
_archive_jobs(stamp)
else:
_purge_jobs(stamp)
except Exception as e:
log.error(e)
|
saltstack/salt
|
salt/returners/pgjsonb.py
|
clean_old_jobs
|
python
|
def clean_old_jobs():
'''
Called in the master's event loop every loop_interval. Archives and/or
deletes the events and job details from the database.
:return:
'''
if __opts__.get('keep_jobs', False) and int(__opts__.get('keep_jobs', 0)) > 0:
try:
with _get_serv() as cur:
sql = "select (NOW() - interval '{0}' hour) as stamp;".format(__opts__['keep_jobs'])
cur.execute(sql)
rows = cur.fetchall()
stamp = rows[0][0]
if __opts__.get('archive_jobs', False):
_archive_jobs(stamp)
else:
_purge_jobs(stamp)
except Exception as e:
log.error(e)
|
Called in the master's event loop every loop_interval. Archives and/or
deletes the events and job details from the database.
:return:
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/returners/pgjsonb.py#L545-L564
| null |
# -*- coding: utf-8 -*-
'''
Return data to a PostgreSQL server with json data stored in Pg's jsonb data type
:maintainer: Dave Boucha <dave@saltstack.com>, Seth House <shouse@saltstack.com>, C. R. Oldham <cr@saltstack.com>
:maturity: Stable
:depends: python-psycopg2
:platform: all
.. note::
There are three PostgreSQL returners. Any can function as an external
:ref:`master job cache <external-job-cache>`. but each has different
features. SaltStack recommends
:mod:`returners.pgjsonb <salt.returners.pgjsonb>` if you are working with
a version of PostgreSQL that has the appropriate native binary JSON types.
Otherwise, review
:mod:`returners.postgres <salt.returners.postgres>` and
:mod:`returners.postgres_local_cache <salt.returners.postgres_local_cache>`
to see which module best suits your particular needs.
To enable this returner, the minion will need the python client for PostgreSQL
installed and the following values configured in the minion or master
config. These are the defaults:
.. code-block:: yaml
returner.pgjsonb.host: 'salt'
returner.pgjsonb.user: 'salt'
returner.pgjsonb.pass: 'salt'
returner.pgjsonb.db: 'salt'
returner.pgjsonb.port: 5432
SSL is optional. The defaults are set to None. If you do not want to use SSL,
either exclude these options or set them to None.
.. code-block:: yaml
returner.pgjsonb.sslmode: None
returner.pgjsonb.sslcert: None
returner.pgjsonb.sslkey: None
returner.pgjsonb.sslrootcert: None
returner.pgjsonb.sslcrl: None
.. versionadded:: 2017.5.0
Alternative configuration values can be used by prefacing the configuration
with `alternative.`. Any values not found in the alternative configuration will
be pulled from the default location. As stated above, SSL configuration is
optional. The following ssl options are simply for illustration purposes:
.. code-block:: yaml
alternative.pgjsonb.host: 'salt'
alternative.pgjsonb.user: 'salt'
alternative.pgjsonb.pass: 'salt'
alternative.pgjsonb.db: 'salt'
alternative.pgjsonb.port: 5432
alternative.pgjsonb.ssl_ca: '/etc/pki/mysql/certs/localhost.pem'
alternative.pgjsonb.ssl_cert: '/etc/pki/mysql/certs/localhost.crt'
alternative.pgjsonb.ssl_key: '/etc/pki/mysql/certs/localhost.key'
Should you wish the returner data to be cleaned out every so often, set
``keep_jobs`` to the number of hours for the jobs to live in the tables.
Setting it to ``0`` or leaving it unset will cause the data to stay in the tables.
Should you wish to archive jobs in a different table for later processing,
set ``archive_jobs`` to True. Salt will create 3 archive tables;
- ``jids_archive``
- ``salt_returns_archive``
- ``salt_events_archive``
and move the contents of ``jids``, ``salt_returns``, and ``salt_events`` that are
more than ``keep_jobs`` hours old to these tables.
.. versionadded:: 2019.2.0
Use the following Pg database schema:
.. code-block:: sql
CREATE DATABASE salt
WITH ENCODING 'utf-8';
--
-- Table structure for table `jids`
--
DROP TABLE IF EXISTS jids;
CREATE TABLE jids (
jid varchar(255) NOT NULL primary key,
load jsonb NOT NULL
);
CREATE INDEX idx_jids_jsonb on jids
USING gin (load)
WITH (fastupdate=on);
--
-- Table structure for table `salt_returns`
--
DROP TABLE IF EXISTS salt_returns;
CREATE TABLE salt_returns (
fun varchar(50) NOT NULL,
jid varchar(255) NOT NULL,
return jsonb NOT NULL,
id varchar(255) NOT NULL,
success varchar(10) NOT NULL,
full_ret jsonb NOT NULL,
alter_time TIMESTAMP WITH TIME ZONE DEFAULT NOW());
CREATE INDEX idx_salt_returns_id ON salt_returns (id);
CREATE INDEX idx_salt_returns_jid ON salt_returns (jid);
CREATE INDEX idx_salt_returns_fun ON salt_returns (fun);
CREATE INDEX idx_salt_returns_return ON salt_returns
USING gin (return) with (fastupdate=on);
CREATE INDEX idx_salt_returns_full_ret ON salt_returns
USING gin (full_ret) with (fastupdate=on);
--
-- Table structure for table `salt_events`
--
DROP TABLE IF EXISTS salt_events;
DROP SEQUENCE IF EXISTS seq_salt_events_id;
CREATE SEQUENCE seq_salt_events_id;
CREATE TABLE salt_events (
id BIGINT NOT NULL UNIQUE DEFAULT nextval('seq_salt_events_id'),
tag varchar(255) NOT NULL,
data jsonb NOT NULL,
alter_time TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
master_id varchar(255) NOT NULL);
CREATE INDEX idx_salt_events_tag on
salt_events (tag);
CREATE INDEX idx_salt_events_data ON salt_events
USING gin (data) with (fastupdate=on);
Required python modules: Psycopg2
To use this returner, append '--return pgjsonb' to the salt command.
.. code-block:: bash
salt '*' test.ping --return pgjsonb
To use the alternative configuration, append '--return_config alternative' to the salt command.
.. versionadded:: 2015.5.0
.. code-block:: bash
salt '*' test.ping --return pgjsonb --return_config alternative
To override individual configuration items, append --return_kwargs '{"key:": "value"}' to the salt command.
.. versionadded:: 2016.3.0
.. code-block:: bash
salt '*' test.ping --return pgjsonb --return_kwargs '{"db": "another-salt"}'
'''
from __future__ import absolute_import, print_function, unicode_literals
# Let's not allow PyLint complain about string substitution
# pylint: disable=W1321,E1321
# Import python libs
from contextlib import contextmanager
import sys
import time
import logging
# Import salt libs
import salt.returners
import salt.utils.jid
import salt.exceptions
from salt.ext import six
# Import third party libs
try:
import psycopg2
import psycopg2.extras
HAS_PG = True
except ImportError:
HAS_PG = False
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pgjsonb'
PG_SAVE_LOAD_SQL = '''INSERT INTO jids (jid, load) VALUES (%(jid)s, %(load)s)'''
def __virtual__():
if not HAS_PG:
return False, 'Could not import pgjsonb returner; python-psycopg2 is not installed.'
return True
def _get_options(ret=None):
'''
Returns options used for the MySQL connection.
'''
defaults = {
'host': 'localhost',
'user': 'salt',
'pass': 'salt',
'db': 'salt',
'port': 5432
}
attrs = {
'host': 'host',
'user': 'user',
'pass': 'pass',
'db': 'db',
'port': 'port',
'sslmode': 'sslmode',
'sslcert': 'sslcert',
'sslkey': 'sslkey',
'sslrootcert': 'sslrootcert',
'sslcrl': 'sslcrl',
}
_options = salt.returners.get_returner_options('returner.{0}'.format(__virtualname__),
ret,
attrs,
__salt__=__salt__,
__opts__=__opts__,
defaults=defaults)
# Ensure port is an int
if 'port' in _options:
_options['port'] = int(_options['port'])
return _options
@contextmanager
def _get_serv(ret=None, commit=False):
'''
Return a Pg cursor
'''
_options = _get_options(ret)
try:
# An empty ssl_options dictionary passed to MySQLdb.connect will
# effectively connect w/o SSL.
ssl_options = {
k: v for k, v in six.iteritems(_options)
if k in ['sslmode', 'sslcert', 'sslkey', 'sslrootcert', 'sslcrl']
}
conn = psycopg2.connect(
host=_options.get('host'),
port=_options.get('port'),
dbname=_options.get('db'),
user=_options.get('user'),
password=_options.get('pass'),
**ssl_options
)
except psycopg2.OperationalError as exc:
raise salt.exceptions.SaltMasterError('pgjsonb returner could not connect to database: {exc}'.format(exc=exc))
if conn.server_version is not None and conn.server_version >= 90500:
global PG_SAVE_LOAD_SQL
PG_SAVE_LOAD_SQL = '''INSERT INTO jids
(jid, load)
VALUES (%(jid)s, %(load)s)
ON CONFLICT (jid) DO UPDATE
SET load=%(load)s'''
cursor = conn.cursor()
try:
yield cursor
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
else:
if commit:
cursor.execute("COMMIT")
else:
cursor.execute("ROLLBACK")
finally:
conn.close()
def returner(ret):
'''
Return data to a Pg server
'''
try:
with _get_serv(ret, commit=True) as cur:
sql = '''INSERT INTO salt_returns
(fun, jid, return, id, success, full_ret, alter_time)
VALUES (%s, %s, %s, %s, %s, %s, to_timestamp(%s))'''
cur.execute(sql, (ret['fun'], ret['jid'],
psycopg2.extras.Json(ret['return']),
ret['id'],
ret.get('success', False),
psycopg2.extras.Json(ret),
time.time()))
except salt.exceptions.SaltMasterError:
log.critical('Could not store return with pgjsonb returner. PostgreSQL server unavailable.')
def event_return(events):
'''
Return event to Pg server
Requires that configuration be enabled via 'event_return'
option in master config.
'''
with _get_serv(events, commit=True) as cur:
for event in events:
tag = event.get('tag', '')
data = event.get('data', '')
sql = '''INSERT INTO salt_events (tag, data, master_id, alter_time)
VALUES (%s, %s, %s, to_timestamp(%s))'''
cur.execute(sql, (tag, psycopg2.extras.Json(data),
__opts__['id'], time.time()))
def save_load(jid, load, minions=None):
'''
Save the load to the specified jid id
'''
with _get_serv(commit=True) as cur:
try:
cur.execute(PG_SAVE_LOAD_SQL,
{'jid': jid, 'load': psycopg2.extras.Json(load)})
except psycopg2.IntegrityError:
# https://github.com/saltstack/salt/issues/22171
# Without this try/except we get tons of duplicate entry errors
# which result in job returns not being stored properly
pass
def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument
'''
Included for API consistency
'''
pass
def get_load(jid):
'''
Return the load data that marks a specified jid
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT load FROM jids WHERE jid = %s;'''
cur.execute(sql, (jid,))
data = cur.fetchone()
if data:
return data[0]
return {}
def get_jid(jid):
'''
Return the information returned when the specified job id was executed
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT id, full_ret FROM salt_returns
WHERE jid = %s'''
cur.execute(sql, (jid,))
data = cur.fetchall()
ret = {}
if data:
for minion, full_ret in data:
ret[minion] = full_ret
return ret
def get_fun(fun):
'''
Return a dict of the last function called for all minions
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT s.id,s.jid, s.full_ret
FROM salt_returns s
JOIN ( SELECT MAX(`jid`) as jid
from salt_returns GROUP BY fun, id) max
ON s.jid = max.jid
WHERE s.fun = %s
'''
cur.execute(sql, (fun,))
data = cur.fetchall()
ret = {}
if data:
for minion, _, full_ret in data:
ret[minion] = full_ret
return ret
def get_jids():
'''
Return a list of all job ids
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT jid, load
FROM jids'''
cur.execute(sql)
data = cur.fetchall()
ret = {}
for jid, load in data:
ret[jid] = salt.utils.jid.format_jid_instance(jid, load)
return ret
def get_minions():
'''
Return a list of minions
'''
with _get_serv(ret=None, commit=True) as cur:
sql = '''SELECT DISTINCT id
FROM salt_returns'''
cur.execute(sql)
data = cur.fetchall()
ret = []
for minion in data:
ret.append(minion[0])
return ret
def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument
'''
Do any work necessary to prepare a JID, including sending a custom id
'''
return passed_jid if passed_jid is not None else salt.utils.jid.gen_jid(__opts__)
def _purge_jobs(timestamp):
'''
Purge records from the returner tables.
:param job_age_in_seconds: Purge jobs older than this
:return:
'''
with _get_serv() as cursor:
try:
sql = 'delete from jids where jid in (select distinct jid from salt_returns where alter_time < %s)'
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
try:
sql = 'delete from salt_returns where alter_time < %s'
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
try:
sql = 'delete from salt_events where alter_time < %s'
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
return True
def _archive_jobs(timestamp):
'''
Copy rows to a set of backup tables, then purge rows.
:param timestamp: Archive rows older than this timestamp
:return:
'''
source_tables = ['jids',
'salt_returns',
'salt_events']
with _get_serv() as cursor:
target_tables = {}
for table_name in source_tables:
try:
tmp_table_name = table_name + '_archive'
sql = 'create table IF NOT exists {0} (LIKE {1})'.format(tmp_table_name, table_name)
cursor.execute(sql)
cursor.execute('COMMIT')
target_tables[table_name] = tmp_table_name
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
try:
sql = 'insert into {0} select * from {1} where jid in (select distinct jid from salt_returns where alter_time < %s)'.format(target_tables['jids'], 'jids')
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
except Exception as e:
log.error(e)
raise
try:
sql = 'insert into {0} select * from {1} where alter_time < %s'.format(target_tables['salt_returns'], 'salt_returns')
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
try:
sql = 'insert into {0} select * from {1} where alter_time < %s'.format(target_tables['salt_events'], 'salt_events')
cursor.execute(sql, (timestamp,))
cursor.execute('COMMIT')
except psycopg2.DatabaseError as err:
error = err.args
sys.stderr.write(six.text_type(error))
cursor.execute("ROLLBACK")
raise err
return _purge_jobs(timestamp)
|
saltstack/salt
|
salt/modules/win_status.py
|
cpustats
|
python
|
def cpustats():
'''
Return information about the CPU.
Returns
dict: A dictionary containing information about the CPU stats
CLI Example:
.. code-block:: bash
salt * status.cpustats
'''
# Tries to gather information similar to that returned by a Linux machine
# Avoid using WMI as there's a lot of overhead
# Time related info
user, system, idle, interrupt, dpc = psutil.cpu_times()
cpu = {'user': user,
'system': system,
'idle': idle,
'irq': interrupt,
'dpc': dpc}
# Count related info
ctx_switches, interrupts, soft_interrupts, sys_calls = psutil.cpu_stats()
intr = {'irqs': {'irqs': [],
'total': interrupts}}
soft_irq = {'softirqs': [],
'total': soft_interrupts}
return {'btime': psutil.boot_time(),
'cpu': cpu,
'ctxt': ctx_switches,
'intr': intr,
'processes': len(psutil.pids()),
'softirq': soft_irq,
'syscalls': sys_calls}
|
Return information about the CPU.
Returns
dict: A dictionary containing information about the CPU stats
CLI Example:
.. code-block:: bash
salt * status.cpustats
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_status.py#L167-L202
| null |
# -*- coding: utf-8 -*-
'''
Module for returning various status data about a minion.
These data can be useful for compiling into stats later,
or for problem solving if your minion is having problems.
.. versionadded:: 0.12.0
:depends: - wmi
'''
# Import Python Libs
from __future__ import absolute_import, unicode_literals, print_function
import ctypes
import datetime
import logging
import subprocess
log = logging.getLogger(__name__)
# Import Salt Libs
import salt.utils.event
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.win_pdh
from salt.utils.network import host_to_ips as _host_to_ips
from salt.utils.functools import namespaced_function as _namespaced_function
# Import 3rd party Libs
from salt.ext import six
# These imports needed for namespaced functions
# pylint: disable=W0611
from salt.modules.status import ping_master, time_
import copy
# pylint: enable=W0611
# Import 3rd Party Libs
try:
if salt.utils.platform.is_windows():
import wmi
import salt.utils.winapi
HAS_WMI = True
else:
HAS_WMI = False
except ImportError:
HAS_WMI = False
HAS_PSUTIL = False
if salt.utils.platform.is_windows():
import psutil
HAS_PSUTIL = True
__opts__ = {}
__virtualname__ = 'status'
# Taken from https://www.geoffchappell.com/studies/windows/km/ntoskrnl/api/ex/sysinfo/performance.htm
class SYSTEM_PERFORMANCE_INFORMATION(ctypes.Structure):
_fields_ = [('IdleProcessTime', ctypes.c_int64),
('IoReadTransferCount', ctypes.c_int64),
('IoWriteTransferCount', ctypes.c_int64),
('IoOtherTransferCount', ctypes.c_int64),
('IoReadOperationCount', ctypes.c_ulong),
('IoWriteOperationCount', ctypes.c_ulong),
('IoOtherOperationCount', ctypes.c_ulong),
('AvailablePages', ctypes.c_ulong),
('CommittedPages', ctypes.c_ulong),
('CommitLimit', ctypes.c_ulong),
('PeakCommitment', ctypes.c_ulong),
('PageFaultCount', ctypes.c_ulong),
('CopyOnWriteCount', ctypes.c_ulong),
('TransitionCount', ctypes.c_ulong),
('CacheTransitionCount', ctypes.c_ulong),
('DemandZeroCount', ctypes.c_ulong),
('PageReadCount', ctypes.c_ulong),
('PageReadIoCount', ctypes.c_ulong),
('CacheReadCount', ctypes.c_ulong), # Was c_ulong ** 2
('CacheIoCount', ctypes.c_ulong),
('DirtyPagesWriteCount', ctypes.c_ulong),
('DirtyWriteIoCount', ctypes.c_ulong),
('MappedPagesWriteCount', ctypes.c_ulong),
('MappedWriteIoCount', ctypes.c_ulong),
('PagedPoolPages', ctypes.c_ulong),
('NonPagedPoolPages', ctypes.c_ulong),
('PagedPoolAllocs', ctypes.c_ulong),
('PagedPoolFrees', ctypes.c_ulong),
('NonPagedPoolAllocs', ctypes.c_ulong),
('NonPagedPoolFrees', ctypes.c_ulong),
('FreeSystemPtes', ctypes.c_ulong),
('ResidentSystemCodePage', ctypes.c_ulong),
('TotalSystemDriverPages', ctypes.c_ulong),
('TotalSystemCodePages', ctypes.c_ulong),
('NonPagedPoolLookasideHits', ctypes.c_ulong),
('PagedPoolLookasideHits', ctypes.c_ulong),
('AvailablePagedPoolPages', ctypes.c_ulong),
('ResidentSystemCachePage', ctypes.c_ulong),
('ResidentPagedPoolPage', ctypes.c_ulong),
('ResidentSystemDriverPage', ctypes.c_ulong),
('CcFastReadNoWait', ctypes.c_ulong),
('CcFastReadWait', ctypes.c_ulong),
('CcFastReadResourceMiss', ctypes.c_ulong),
('CcFastReadNotPossible', ctypes.c_ulong),
('CcFastMdlReadNoWait', ctypes.c_ulong),
('CcFastMdlReadWait', ctypes.c_ulong),
('CcFastMdlReadResourceMiss', ctypes.c_ulong),
('CcFastMdlReadNotPossible', ctypes.c_ulong),
('CcMapDataNoWait', ctypes.c_ulong),
('CcMapDataWait', ctypes.c_ulong),
('CcMapDataNoWaitMiss', ctypes.c_ulong),
('CcMapDataWaitMiss', ctypes.c_ulong),
('CcPinMappedDataCount', ctypes.c_ulong),
('CcPinReadNoWait', ctypes.c_ulong),
('CcPinReadWait', ctypes.c_ulong),
('CcPinReadNoWaitMiss', ctypes.c_ulong),
('CcPinReadWaitMiss', ctypes.c_ulong),
('CcCopyReadNoWait', ctypes.c_ulong),
('CcCopyReadWait', ctypes.c_ulong),
('CcCopyReadNoWaitMiss', ctypes.c_ulong),
('CcCopyReadWaitMiss', ctypes.c_ulong),
('CcMdlReadNoWait', ctypes.c_ulong),
('CcMdlReadWait', ctypes.c_ulong),
('CcMdlReadNoWaitMiss', ctypes.c_ulong),
('CcMdlReadWaitMiss', ctypes.c_ulong),
('CcReadAheadIos', ctypes.c_ulong),
('CcLazyWriteIos', ctypes.c_ulong),
('CcLazyWritePages', ctypes.c_ulong),
('CcDataFlushes', ctypes.c_ulong),
('CcDataPages', ctypes.c_ulong),
('ContextSwitches', ctypes.c_ulong),
('FirstLevelTbFills', ctypes.c_ulong),
('SecondLevelTbFills', ctypes.c_ulong),
('SystemCalls', ctypes.c_ulong),
# Windows 8 and above
('CcTotalDirtyPages', ctypes.c_ulonglong),
('CcDirtyPagesThreshold', ctypes.c_ulonglong),
('ResidentAvailablePages', ctypes.c_longlong),
# Windows 10 and above
('SharedCommittedPages', ctypes.c_ulonglong)]
def __virtual__():
'''
Only works on Windows systems with WMI and WinAPI
'''
if not salt.utils.platform.is_windows():
return False, 'win_status.py: Requires Windows'
if not HAS_WMI:
return False, 'win_status.py: Requires WMI and WinAPI'
if not HAS_PSUTIL:
return False, 'win_status.py: Requires psutil'
# Namespace modules from `status.py`
global ping_master, time_
ping_master = _namespaced_function(ping_master, globals())
time_ = _namespaced_function(time_, globals())
return __virtualname__
__func_alias__ = {
'time_': 'time'
}
def meminfo():
'''
Return information about physical and virtual memory on the system
Returns:
dict: A dictionary of information about memory on the system
CLI Example:
.. code-block:: bash
salt * status.meminfo
'''
# Get physical memory
vm_total, vm_available, vm_percent, vm_used, vm_free = psutil.virtual_memory()
# Get swap memory
swp_total, swp_used, swp_free, swp_percent, _, _ = psutil.swap_memory()
def get_unit_value(memory):
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {}
for i, s in enumerate(symbols):
prefix[s] = 1 << (i + 1) * 10
for s in reversed(symbols):
if memory >= prefix[s]:
value = float(memory) / prefix[s]
return {'unit': s,
'value': value}
return {'unit': 'B',
'value': memory}
return {'VmallocTotal': get_unit_value(vm_total),
'VmallocUsed': get_unit_value(vm_used),
'VmallocFree': get_unit_value(vm_free),
'VmallocAvail': get_unit_value(vm_available),
'SwapTotal': get_unit_value(swp_total),
'SwapUsed': get_unit_value(swp_used),
'SwapFree': get_unit_value(swp_free)}
def vmstats():
'''
Return information about the virtual memory on the machine
Returns:
dict: A dictionary of virtual memory stats
CLI Example:
.. code-block:: bash
salt * status.vmstats
'''
# Setup the SPI Structure
spi = SYSTEM_PERFORMANCE_INFORMATION()
retlen = ctypes.c_ulong()
# 2 means to query System Performance Information and return it in a
# SYSTEM_PERFORMANCE_INFORMATION Structure
ctypes.windll.ntdll.NtQuerySystemInformation(
2, ctypes.byref(spi), ctypes.sizeof(spi), ctypes.byref(retlen))
# Return each defined field in a dict
ret = {}
for field in spi._fields_:
ret.update({field[0]: getattr(spi, field[0])})
return ret
def loadavg():
'''
Returns counter information related to the load of the machine
Returns:
dict: A dictionary of counters
CLI Example:
.. code-block:: bash
salt * status.loadavg
'''
# Counter List (obj, instance, counter)
counter_list = [
('Memory', None, 'Available Bytes'),
('Memory', None, 'Pages/sec'),
('Paging File', '*', '% Usage'),
('Processor', '*', '% Processor Time'),
('Processor', '*', 'DPCs Queued/sec'),
('Processor', '*', '% Privileged Time'),
('Processor', '*', '% User Time'),
('Processor', '*', '% DPC Time'),
('Processor', '*', '% Interrupt Time'),
('Server', None, 'Work Item Shortages'),
('Server Work Queues', '*', 'Queue Length'),
('System', None, 'Processor Queue Length'),
('System', None, 'Context Switches/sec'),
]
return salt.utils.win_pdh.get_counters(counter_list=counter_list)
def cpuload():
'''
.. versionadded:: 2015.8.0
Return the processor load as a percentage
CLI Example:
.. code-block:: bash
salt '*' status.cpuload
'''
return psutil.cpu_percent()
def diskusage(human_readable=False, path=None):
'''
.. versionadded:: 2015.8.0
Return the disk usage for this minion
human_readable : False
If ``True``, usage will be in KB/MB/GB etc.
CLI Example:
.. code-block:: bash
salt '*' status.diskusage path=c:/salt
'''
if not path:
path = 'c:/'
disk_stats = psutil.disk_usage(path)
total_val = disk_stats.total
used_val = disk_stats.used
free_val = disk_stats.free
percent = disk_stats.percent
if human_readable:
total_val = _byte_calc(total_val)
used_val = _byte_calc(used_val)
free_val = _byte_calc(free_val)
return {'total': total_val,
'used': used_val,
'free': free_val,
'percent': percent}
def procs(count=False):
'''
Return the process data
count : False
If ``True``, this function will simply return the number of processes.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' status.procs
salt '*' status.procs count
'''
with salt.utils.winapi.Com():
wmi_obj = wmi.WMI()
processes = wmi_obj.win32_process()
#this short circuit's the function to get a short simple proc count.
if count:
return len(processes)
#a propper run of the function, creating a nonsensically long out put.
process_info = {}
for proc in processes:
process_info[proc.ProcessId] = _get_process_info(proc)
return process_info
def saltmem(human_readable=False):
'''
.. versionadded:: 2015.8.0
Returns the amount of memory that salt is using
human_readable : False
return the value in a nicely formatted number
CLI Example:
.. code-block:: bash
salt '*' status.saltmem
salt '*' status.saltmem human_readable=True
'''
# psutil.Process defaults to current process (`os.getpid()`)
p = psutil.Process()
# Use oneshot to get a snapshot
with p.oneshot():
mem = p.memory_info().rss
if human_readable:
return _byte_calc(mem)
return mem
def uptime(human_readable=False):
'''
.. versionadded:: 2015.8.0
Return the system uptime for the machine
Args:
human_readable (bool):
Return uptime in human readable format if ``True``, otherwise
return seconds. Default is ``False``
.. note::
Human readable format is ``days, hours:min:sec``. Days will only
be displayed if more than 0
Returns:
str:
The uptime in seconds or human readable format depending on the
value of ``human_readable``
CLI Example:
.. code-block:: bash
salt '*' status.uptime
salt '*' status.uptime human_readable=True
'''
# Get startup time
startup_time = datetime.datetime.fromtimestamp(psutil.boot_time())
# Subtract startup time from current time to get the uptime of the system
uptime = datetime.datetime.now() - startup_time
return six.text_type(uptime) if human_readable else uptime.total_seconds()
def _get_process_info(proc):
'''
Return process information
'''
cmd = salt.utils.stringutils.to_unicode(proc.CommandLine or '')
name = salt.utils.stringutils.to_unicode(proc.Name)
info = dict(
cmd=cmd,
name=name,
**_get_process_owner(proc)
)
return info
def _get_process_owner(process):
owner = {}
domain, error_code, user = None, None, None
try:
domain, error_code, user = process.GetOwner()
owner['user'] = salt.utils.stringutils.to_unicode(user)
owner['user_domain'] = salt.utils.stringutils.to_unicode(domain)
except Exception as exc:
pass
if not error_code and all((user, domain)):
owner['user'] = salt.utils.stringutils.to_unicode(user)
owner['user_domain'] = salt.utils.stringutils.to_unicode(domain)
elif process.ProcessId in [0, 4] and error_code == 2:
# Access Denied for System Idle Process and System
owner['user'] = 'SYSTEM'
owner['user_domain'] = 'NT AUTHORITY'
else:
log.warning('Error getting owner of process; PID=\'%s\'; Error: %s',
process.ProcessId, error_code)
return owner
def _byte_calc(val):
if val < 1024:
tstr = six.text_type(val)+'B'
elif val < 1038336:
tstr = six.text_type(val/1024)+'KB'
elif val < 1073741824:
tstr = six.text_type(val/1038336)+'MB'
elif val < 1099511627776:
tstr = six.text_type(val/1073741824)+'GB'
else:
tstr = six.text_type(val/1099511627776)+'TB'
return tstr
def master(master=None, connected=True):
'''
.. versionadded:: 2015.5.0
Fire an event if the minion gets disconnected from its master. This
function is meant to be run via a scheduled job from the minion. If
master_ip is an FQDN/Hostname, is must be resolvable to a valid IPv4
address.
CLI Example:
.. code-block:: bash
salt '*' status.master
'''
def _win_remotes_on(port):
'''
Windows specific helper function.
Returns set of ipv4 host addresses of remote established connections
on local or remote tcp port.
Parses output of shell 'netstat' to get connections
PS C:> netstat -n -p TCP
Active Connections
Proto Local Address Foreign Address State
TCP 10.1.1.26:3389 10.1.1.1:4505 ESTABLISHED
TCP 10.1.1.26:56862 10.1.1.10:49155 TIME_WAIT
TCP 10.1.1.26:56868 169.254.169.254:80 CLOSE_WAIT
TCP 127.0.0.1:49197 127.0.0.1:49198 ESTABLISHED
TCP 127.0.0.1:49198 127.0.0.1:49197 ESTABLISHED
'''
remotes = set()
try:
data = subprocess.check_output(['netstat', '-n', '-p', 'TCP']) # pylint: disable=minimum-python-version
except subprocess.CalledProcessError:
log.error('Failed netstat')
raise
lines = salt.utils.stringutils.to_unicode(data).split('\n')
for line in lines:
if 'ESTABLISHED' not in line:
continue
chunks = line.split()
remote_host, remote_port = chunks[2].rsplit(':', 1)
if int(remote_port) != port:
continue
remotes.add(remote_host)
return remotes
# the default publishing port
port = 4505
master_ips = None
if master:
master_ips = _host_to_ips(master)
if not master_ips:
return
if __salt__['config.get']('publish_port') != '':
port = int(__salt__['config.get']('publish_port'))
master_connection_status = False
connected_ips = _win_remotes_on(port)
# Get connection status for master
for master_ip in master_ips:
if master_ip in connected_ips:
master_connection_status = True
break
# Connection to master is not as expected
if master_connection_status is not connected:
event = salt.utils.event.get_event('minion', opts=__opts__, listen=False)
if master_connection_status:
event.fire_event({'master': master}, salt.minion.master_event(type='connected'))
else:
event.fire_event({'master': master}, salt.minion.master_event(type='disconnected'))
return master_connection_status
|
saltstack/salt
|
salt/modules/win_status.py
|
meminfo
|
python
|
def meminfo():
'''
Return information about physical and virtual memory on the system
Returns:
dict: A dictionary of information about memory on the system
CLI Example:
.. code-block:: bash
salt * status.meminfo
'''
# Get physical memory
vm_total, vm_available, vm_percent, vm_used, vm_free = psutil.virtual_memory()
# Get swap memory
swp_total, swp_used, swp_free, swp_percent, _, _ = psutil.swap_memory()
def get_unit_value(memory):
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {}
for i, s in enumerate(symbols):
prefix[s] = 1 << (i + 1) * 10
for s in reversed(symbols):
if memory >= prefix[s]:
value = float(memory) / prefix[s]
return {'unit': s,
'value': value}
return {'unit': 'B',
'value': memory}
return {'VmallocTotal': get_unit_value(vm_total),
'VmallocUsed': get_unit_value(vm_used),
'VmallocFree': get_unit_value(vm_free),
'VmallocAvail': get_unit_value(vm_available),
'SwapTotal': get_unit_value(swp_total),
'SwapUsed': get_unit_value(swp_used),
'SwapFree': get_unit_value(swp_free)}
|
Return information about physical and virtual memory on the system
Returns:
dict: A dictionary of information about memory on the system
CLI Example:
.. code-block:: bash
salt * status.meminfo
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_status.py#L205-L242
|
[
"def get_unit_value(memory):\n symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')\n prefix = {}\n for i, s in enumerate(symbols):\n prefix[s] = 1 << (i + 1) * 10\n for s in reversed(symbols):\n if memory >= prefix[s]:\n value = float(memory) / prefix[s]\n return {'unit': s,\n 'value': value}\n return {'unit': 'B',\n 'value': memory}\n"
] |
# -*- coding: utf-8 -*-
'''
Module for returning various status data about a minion.
These data can be useful for compiling into stats later,
or for problem solving if your minion is having problems.
.. versionadded:: 0.12.0
:depends: - wmi
'''
# Import Python Libs
from __future__ import absolute_import, unicode_literals, print_function
import ctypes
import datetime
import logging
import subprocess
log = logging.getLogger(__name__)
# Import Salt Libs
import salt.utils.event
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.win_pdh
from salt.utils.network import host_to_ips as _host_to_ips
from salt.utils.functools import namespaced_function as _namespaced_function
# Import 3rd party Libs
from salt.ext import six
# These imports needed for namespaced functions
# pylint: disable=W0611
from salt.modules.status import ping_master, time_
import copy
# pylint: enable=W0611
# Import 3rd Party Libs
try:
if salt.utils.platform.is_windows():
import wmi
import salt.utils.winapi
HAS_WMI = True
else:
HAS_WMI = False
except ImportError:
HAS_WMI = False
HAS_PSUTIL = False
if salt.utils.platform.is_windows():
import psutil
HAS_PSUTIL = True
__opts__ = {}
__virtualname__ = 'status'
# Taken from https://www.geoffchappell.com/studies/windows/km/ntoskrnl/api/ex/sysinfo/performance.htm
class SYSTEM_PERFORMANCE_INFORMATION(ctypes.Structure):
_fields_ = [('IdleProcessTime', ctypes.c_int64),
('IoReadTransferCount', ctypes.c_int64),
('IoWriteTransferCount', ctypes.c_int64),
('IoOtherTransferCount', ctypes.c_int64),
('IoReadOperationCount', ctypes.c_ulong),
('IoWriteOperationCount', ctypes.c_ulong),
('IoOtherOperationCount', ctypes.c_ulong),
('AvailablePages', ctypes.c_ulong),
('CommittedPages', ctypes.c_ulong),
('CommitLimit', ctypes.c_ulong),
('PeakCommitment', ctypes.c_ulong),
('PageFaultCount', ctypes.c_ulong),
('CopyOnWriteCount', ctypes.c_ulong),
('TransitionCount', ctypes.c_ulong),
('CacheTransitionCount', ctypes.c_ulong),
('DemandZeroCount', ctypes.c_ulong),
('PageReadCount', ctypes.c_ulong),
('PageReadIoCount', ctypes.c_ulong),
('CacheReadCount', ctypes.c_ulong), # Was c_ulong ** 2
('CacheIoCount', ctypes.c_ulong),
('DirtyPagesWriteCount', ctypes.c_ulong),
('DirtyWriteIoCount', ctypes.c_ulong),
('MappedPagesWriteCount', ctypes.c_ulong),
('MappedWriteIoCount', ctypes.c_ulong),
('PagedPoolPages', ctypes.c_ulong),
('NonPagedPoolPages', ctypes.c_ulong),
('PagedPoolAllocs', ctypes.c_ulong),
('PagedPoolFrees', ctypes.c_ulong),
('NonPagedPoolAllocs', ctypes.c_ulong),
('NonPagedPoolFrees', ctypes.c_ulong),
('FreeSystemPtes', ctypes.c_ulong),
('ResidentSystemCodePage', ctypes.c_ulong),
('TotalSystemDriverPages', ctypes.c_ulong),
('TotalSystemCodePages', ctypes.c_ulong),
('NonPagedPoolLookasideHits', ctypes.c_ulong),
('PagedPoolLookasideHits', ctypes.c_ulong),
('AvailablePagedPoolPages', ctypes.c_ulong),
('ResidentSystemCachePage', ctypes.c_ulong),
('ResidentPagedPoolPage', ctypes.c_ulong),
('ResidentSystemDriverPage', ctypes.c_ulong),
('CcFastReadNoWait', ctypes.c_ulong),
('CcFastReadWait', ctypes.c_ulong),
('CcFastReadResourceMiss', ctypes.c_ulong),
('CcFastReadNotPossible', ctypes.c_ulong),
('CcFastMdlReadNoWait', ctypes.c_ulong),
('CcFastMdlReadWait', ctypes.c_ulong),
('CcFastMdlReadResourceMiss', ctypes.c_ulong),
('CcFastMdlReadNotPossible', ctypes.c_ulong),
('CcMapDataNoWait', ctypes.c_ulong),
('CcMapDataWait', ctypes.c_ulong),
('CcMapDataNoWaitMiss', ctypes.c_ulong),
('CcMapDataWaitMiss', ctypes.c_ulong),
('CcPinMappedDataCount', ctypes.c_ulong),
('CcPinReadNoWait', ctypes.c_ulong),
('CcPinReadWait', ctypes.c_ulong),
('CcPinReadNoWaitMiss', ctypes.c_ulong),
('CcPinReadWaitMiss', ctypes.c_ulong),
('CcCopyReadNoWait', ctypes.c_ulong),
('CcCopyReadWait', ctypes.c_ulong),
('CcCopyReadNoWaitMiss', ctypes.c_ulong),
('CcCopyReadWaitMiss', ctypes.c_ulong),
('CcMdlReadNoWait', ctypes.c_ulong),
('CcMdlReadWait', ctypes.c_ulong),
('CcMdlReadNoWaitMiss', ctypes.c_ulong),
('CcMdlReadWaitMiss', ctypes.c_ulong),
('CcReadAheadIos', ctypes.c_ulong),
('CcLazyWriteIos', ctypes.c_ulong),
('CcLazyWritePages', ctypes.c_ulong),
('CcDataFlushes', ctypes.c_ulong),
('CcDataPages', ctypes.c_ulong),
('ContextSwitches', ctypes.c_ulong),
('FirstLevelTbFills', ctypes.c_ulong),
('SecondLevelTbFills', ctypes.c_ulong),
('SystemCalls', ctypes.c_ulong),
# Windows 8 and above
('CcTotalDirtyPages', ctypes.c_ulonglong),
('CcDirtyPagesThreshold', ctypes.c_ulonglong),
('ResidentAvailablePages', ctypes.c_longlong),
# Windows 10 and above
('SharedCommittedPages', ctypes.c_ulonglong)]
def __virtual__():
'''
Only works on Windows systems with WMI and WinAPI
'''
if not salt.utils.platform.is_windows():
return False, 'win_status.py: Requires Windows'
if not HAS_WMI:
return False, 'win_status.py: Requires WMI and WinAPI'
if not HAS_PSUTIL:
return False, 'win_status.py: Requires psutil'
# Namespace modules from `status.py`
global ping_master, time_
ping_master = _namespaced_function(ping_master, globals())
time_ = _namespaced_function(time_, globals())
return __virtualname__
__func_alias__ = {
'time_': 'time'
}
def cpustats():
'''
Return information about the CPU.
Returns
dict: A dictionary containing information about the CPU stats
CLI Example:
.. code-block:: bash
salt * status.cpustats
'''
# Tries to gather information similar to that returned by a Linux machine
# Avoid using WMI as there's a lot of overhead
# Time related info
user, system, idle, interrupt, dpc = psutil.cpu_times()
cpu = {'user': user,
'system': system,
'idle': idle,
'irq': interrupt,
'dpc': dpc}
# Count related info
ctx_switches, interrupts, soft_interrupts, sys_calls = psutil.cpu_stats()
intr = {'irqs': {'irqs': [],
'total': interrupts}}
soft_irq = {'softirqs': [],
'total': soft_interrupts}
return {'btime': psutil.boot_time(),
'cpu': cpu,
'ctxt': ctx_switches,
'intr': intr,
'processes': len(psutil.pids()),
'softirq': soft_irq,
'syscalls': sys_calls}
def vmstats():
'''
Return information about the virtual memory on the machine
Returns:
dict: A dictionary of virtual memory stats
CLI Example:
.. code-block:: bash
salt * status.vmstats
'''
# Setup the SPI Structure
spi = SYSTEM_PERFORMANCE_INFORMATION()
retlen = ctypes.c_ulong()
# 2 means to query System Performance Information and return it in a
# SYSTEM_PERFORMANCE_INFORMATION Structure
ctypes.windll.ntdll.NtQuerySystemInformation(
2, ctypes.byref(spi), ctypes.sizeof(spi), ctypes.byref(retlen))
# Return each defined field in a dict
ret = {}
for field in spi._fields_:
ret.update({field[0]: getattr(spi, field[0])})
return ret
def loadavg():
'''
Returns counter information related to the load of the machine
Returns:
dict: A dictionary of counters
CLI Example:
.. code-block:: bash
salt * status.loadavg
'''
# Counter List (obj, instance, counter)
counter_list = [
('Memory', None, 'Available Bytes'),
('Memory', None, 'Pages/sec'),
('Paging File', '*', '% Usage'),
('Processor', '*', '% Processor Time'),
('Processor', '*', 'DPCs Queued/sec'),
('Processor', '*', '% Privileged Time'),
('Processor', '*', '% User Time'),
('Processor', '*', '% DPC Time'),
('Processor', '*', '% Interrupt Time'),
('Server', None, 'Work Item Shortages'),
('Server Work Queues', '*', 'Queue Length'),
('System', None, 'Processor Queue Length'),
('System', None, 'Context Switches/sec'),
]
return salt.utils.win_pdh.get_counters(counter_list=counter_list)
def cpuload():
'''
.. versionadded:: 2015.8.0
Return the processor load as a percentage
CLI Example:
.. code-block:: bash
salt '*' status.cpuload
'''
return psutil.cpu_percent()
def diskusage(human_readable=False, path=None):
'''
.. versionadded:: 2015.8.0
Return the disk usage for this minion
human_readable : False
If ``True``, usage will be in KB/MB/GB etc.
CLI Example:
.. code-block:: bash
salt '*' status.diskusage path=c:/salt
'''
if not path:
path = 'c:/'
disk_stats = psutil.disk_usage(path)
total_val = disk_stats.total
used_val = disk_stats.used
free_val = disk_stats.free
percent = disk_stats.percent
if human_readable:
total_val = _byte_calc(total_val)
used_val = _byte_calc(used_val)
free_val = _byte_calc(free_val)
return {'total': total_val,
'used': used_val,
'free': free_val,
'percent': percent}
def procs(count=False):
'''
Return the process data
count : False
If ``True``, this function will simply return the number of processes.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' status.procs
salt '*' status.procs count
'''
with salt.utils.winapi.Com():
wmi_obj = wmi.WMI()
processes = wmi_obj.win32_process()
#this short circuit's the function to get a short simple proc count.
if count:
return len(processes)
#a propper run of the function, creating a nonsensically long out put.
process_info = {}
for proc in processes:
process_info[proc.ProcessId] = _get_process_info(proc)
return process_info
def saltmem(human_readable=False):
'''
.. versionadded:: 2015.8.0
Returns the amount of memory that salt is using
human_readable : False
return the value in a nicely formatted number
CLI Example:
.. code-block:: bash
salt '*' status.saltmem
salt '*' status.saltmem human_readable=True
'''
# psutil.Process defaults to current process (`os.getpid()`)
p = psutil.Process()
# Use oneshot to get a snapshot
with p.oneshot():
mem = p.memory_info().rss
if human_readable:
return _byte_calc(mem)
return mem
def uptime(human_readable=False):
'''
.. versionadded:: 2015.8.0
Return the system uptime for the machine
Args:
human_readable (bool):
Return uptime in human readable format if ``True``, otherwise
return seconds. Default is ``False``
.. note::
Human readable format is ``days, hours:min:sec``. Days will only
be displayed if more than 0
Returns:
str:
The uptime in seconds or human readable format depending on the
value of ``human_readable``
CLI Example:
.. code-block:: bash
salt '*' status.uptime
salt '*' status.uptime human_readable=True
'''
# Get startup time
startup_time = datetime.datetime.fromtimestamp(psutil.boot_time())
# Subtract startup time from current time to get the uptime of the system
uptime = datetime.datetime.now() - startup_time
return six.text_type(uptime) if human_readable else uptime.total_seconds()
def _get_process_info(proc):
'''
Return process information
'''
cmd = salt.utils.stringutils.to_unicode(proc.CommandLine or '')
name = salt.utils.stringutils.to_unicode(proc.Name)
info = dict(
cmd=cmd,
name=name,
**_get_process_owner(proc)
)
return info
def _get_process_owner(process):
owner = {}
domain, error_code, user = None, None, None
try:
domain, error_code, user = process.GetOwner()
owner['user'] = salt.utils.stringutils.to_unicode(user)
owner['user_domain'] = salt.utils.stringutils.to_unicode(domain)
except Exception as exc:
pass
if not error_code and all((user, domain)):
owner['user'] = salt.utils.stringutils.to_unicode(user)
owner['user_domain'] = salt.utils.stringutils.to_unicode(domain)
elif process.ProcessId in [0, 4] and error_code == 2:
# Access Denied for System Idle Process and System
owner['user'] = 'SYSTEM'
owner['user_domain'] = 'NT AUTHORITY'
else:
log.warning('Error getting owner of process; PID=\'%s\'; Error: %s',
process.ProcessId, error_code)
return owner
def _byte_calc(val):
if val < 1024:
tstr = six.text_type(val)+'B'
elif val < 1038336:
tstr = six.text_type(val/1024)+'KB'
elif val < 1073741824:
tstr = six.text_type(val/1038336)+'MB'
elif val < 1099511627776:
tstr = six.text_type(val/1073741824)+'GB'
else:
tstr = six.text_type(val/1099511627776)+'TB'
return tstr
def master(master=None, connected=True):
'''
.. versionadded:: 2015.5.0
Fire an event if the minion gets disconnected from its master. This
function is meant to be run via a scheduled job from the minion. If
master_ip is an FQDN/Hostname, is must be resolvable to a valid IPv4
address.
CLI Example:
.. code-block:: bash
salt '*' status.master
'''
def _win_remotes_on(port):
'''
Windows specific helper function.
Returns set of ipv4 host addresses of remote established connections
on local or remote tcp port.
Parses output of shell 'netstat' to get connections
PS C:> netstat -n -p TCP
Active Connections
Proto Local Address Foreign Address State
TCP 10.1.1.26:3389 10.1.1.1:4505 ESTABLISHED
TCP 10.1.1.26:56862 10.1.1.10:49155 TIME_WAIT
TCP 10.1.1.26:56868 169.254.169.254:80 CLOSE_WAIT
TCP 127.0.0.1:49197 127.0.0.1:49198 ESTABLISHED
TCP 127.0.0.1:49198 127.0.0.1:49197 ESTABLISHED
'''
remotes = set()
try:
data = subprocess.check_output(['netstat', '-n', '-p', 'TCP']) # pylint: disable=minimum-python-version
except subprocess.CalledProcessError:
log.error('Failed netstat')
raise
lines = salt.utils.stringutils.to_unicode(data).split('\n')
for line in lines:
if 'ESTABLISHED' not in line:
continue
chunks = line.split()
remote_host, remote_port = chunks[2].rsplit(':', 1)
if int(remote_port) != port:
continue
remotes.add(remote_host)
return remotes
# the default publishing port
port = 4505
master_ips = None
if master:
master_ips = _host_to_ips(master)
if not master_ips:
return
if __salt__['config.get']('publish_port') != '':
port = int(__salt__['config.get']('publish_port'))
master_connection_status = False
connected_ips = _win_remotes_on(port)
# Get connection status for master
for master_ip in master_ips:
if master_ip in connected_ips:
master_connection_status = True
break
# Connection to master is not as expected
if master_connection_status is not connected:
event = salt.utils.event.get_event('minion', opts=__opts__, listen=False)
if master_connection_status:
event.fire_event({'master': master}, salt.minion.master_event(type='connected'))
else:
event.fire_event({'master': master}, salt.minion.master_event(type='disconnected'))
return master_connection_status
|
saltstack/salt
|
salt/modules/win_status.py
|
vmstats
|
python
|
def vmstats():
'''
Return information about the virtual memory on the machine
Returns:
dict: A dictionary of virtual memory stats
CLI Example:
.. code-block:: bash
salt * status.vmstats
'''
# Setup the SPI Structure
spi = SYSTEM_PERFORMANCE_INFORMATION()
retlen = ctypes.c_ulong()
# 2 means to query System Performance Information and return it in a
# SYSTEM_PERFORMANCE_INFORMATION Structure
ctypes.windll.ntdll.NtQuerySystemInformation(
2, ctypes.byref(spi), ctypes.sizeof(spi), ctypes.byref(retlen))
# Return each defined field in a dict
ret = {}
for field in spi._fields_:
ret.update({field[0]: getattr(spi, field[0])})
return ret
|
Return information about the virtual memory on the machine
Returns:
dict: A dictionary of virtual memory stats
CLI Example:
.. code-block:: bash
salt * status.vmstats
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_status.py#L245-L272
| null |
# -*- coding: utf-8 -*-
'''
Module for returning various status data about a minion.
These data can be useful for compiling into stats later,
or for problem solving if your minion is having problems.
.. versionadded:: 0.12.0
:depends: - wmi
'''
# Import Python Libs
from __future__ import absolute_import, unicode_literals, print_function
import ctypes
import datetime
import logging
import subprocess
log = logging.getLogger(__name__)
# Import Salt Libs
import salt.utils.event
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.win_pdh
from salt.utils.network import host_to_ips as _host_to_ips
from salt.utils.functools import namespaced_function as _namespaced_function
# Import 3rd party Libs
from salt.ext import six
# These imports needed for namespaced functions
# pylint: disable=W0611
from salt.modules.status import ping_master, time_
import copy
# pylint: enable=W0611
# Import 3rd Party Libs
try:
if salt.utils.platform.is_windows():
import wmi
import salt.utils.winapi
HAS_WMI = True
else:
HAS_WMI = False
except ImportError:
HAS_WMI = False
HAS_PSUTIL = False
if salt.utils.platform.is_windows():
import psutil
HAS_PSUTIL = True
__opts__ = {}
__virtualname__ = 'status'
# Taken from https://www.geoffchappell.com/studies/windows/km/ntoskrnl/api/ex/sysinfo/performance.htm
class SYSTEM_PERFORMANCE_INFORMATION(ctypes.Structure):
_fields_ = [('IdleProcessTime', ctypes.c_int64),
('IoReadTransferCount', ctypes.c_int64),
('IoWriteTransferCount', ctypes.c_int64),
('IoOtherTransferCount', ctypes.c_int64),
('IoReadOperationCount', ctypes.c_ulong),
('IoWriteOperationCount', ctypes.c_ulong),
('IoOtherOperationCount', ctypes.c_ulong),
('AvailablePages', ctypes.c_ulong),
('CommittedPages', ctypes.c_ulong),
('CommitLimit', ctypes.c_ulong),
('PeakCommitment', ctypes.c_ulong),
('PageFaultCount', ctypes.c_ulong),
('CopyOnWriteCount', ctypes.c_ulong),
('TransitionCount', ctypes.c_ulong),
('CacheTransitionCount', ctypes.c_ulong),
('DemandZeroCount', ctypes.c_ulong),
('PageReadCount', ctypes.c_ulong),
('PageReadIoCount', ctypes.c_ulong),
('CacheReadCount', ctypes.c_ulong), # Was c_ulong ** 2
('CacheIoCount', ctypes.c_ulong),
('DirtyPagesWriteCount', ctypes.c_ulong),
('DirtyWriteIoCount', ctypes.c_ulong),
('MappedPagesWriteCount', ctypes.c_ulong),
('MappedWriteIoCount', ctypes.c_ulong),
('PagedPoolPages', ctypes.c_ulong),
('NonPagedPoolPages', ctypes.c_ulong),
('PagedPoolAllocs', ctypes.c_ulong),
('PagedPoolFrees', ctypes.c_ulong),
('NonPagedPoolAllocs', ctypes.c_ulong),
('NonPagedPoolFrees', ctypes.c_ulong),
('FreeSystemPtes', ctypes.c_ulong),
('ResidentSystemCodePage', ctypes.c_ulong),
('TotalSystemDriverPages', ctypes.c_ulong),
('TotalSystemCodePages', ctypes.c_ulong),
('NonPagedPoolLookasideHits', ctypes.c_ulong),
('PagedPoolLookasideHits', ctypes.c_ulong),
('AvailablePagedPoolPages', ctypes.c_ulong),
('ResidentSystemCachePage', ctypes.c_ulong),
('ResidentPagedPoolPage', ctypes.c_ulong),
('ResidentSystemDriverPage', ctypes.c_ulong),
('CcFastReadNoWait', ctypes.c_ulong),
('CcFastReadWait', ctypes.c_ulong),
('CcFastReadResourceMiss', ctypes.c_ulong),
('CcFastReadNotPossible', ctypes.c_ulong),
('CcFastMdlReadNoWait', ctypes.c_ulong),
('CcFastMdlReadWait', ctypes.c_ulong),
('CcFastMdlReadResourceMiss', ctypes.c_ulong),
('CcFastMdlReadNotPossible', ctypes.c_ulong),
('CcMapDataNoWait', ctypes.c_ulong),
('CcMapDataWait', ctypes.c_ulong),
('CcMapDataNoWaitMiss', ctypes.c_ulong),
('CcMapDataWaitMiss', ctypes.c_ulong),
('CcPinMappedDataCount', ctypes.c_ulong),
('CcPinReadNoWait', ctypes.c_ulong),
('CcPinReadWait', ctypes.c_ulong),
('CcPinReadNoWaitMiss', ctypes.c_ulong),
('CcPinReadWaitMiss', ctypes.c_ulong),
('CcCopyReadNoWait', ctypes.c_ulong),
('CcCopyReadWait', ctypes.c_ulong),
('CcCopyReadNoWaitMiss', ctypes.c_ulong),
('CcCopyReadWaitMiss', ctypes.c_ulong),
('CcMdlReadNoWait', ctypes.c_ulong),
('CcMdlReadWait', ctypes.c_ulong),
('CcMdlReadNoWaitMiss', ctypes.c_ulong),
('CcMdlReadWaitMiss', ctypes.c_ulong),
('CcReadAheadIos', ctypes.c_ulong),
('CcLazyWriteIos', ctypes.c_ulong),
('CcLazyWritePages', ctypes.c_ulong),
('CcDataFlushes', ctypes.c_ulong),
('CcDataPages', ctypes.c_ulong),
('ContextSwitches', ctypes.c_ulong),
('FirstLevelTbFills', ctypes.c_ulong),
('SecondLevelTbFills', ctypes.c_ulong),
('SystemCalls', ctypes.c_ulong),
# Windows 8 and above
('CcTotalDirtyPages', ctypes.c_ulonglong),
('CcDirtyPagesThreshold', ctypes.c_ulonglong),
('ResidentAvailablePages', ctypes.c_longlong),
# Windows 10 and above
('SharedCommittedPages', ctypes.c_ulonglong)]
def __virtual__():
'''
Only works on Windows systems with WMI and WinAPI
'''
if not salt.utils.platform.is_windows():
return False, 'win_status.py: Requires Windows'
if not HAS_WMI:
return False, 'win_status.py: Requires WMI and WinAPI'
if not HAS_PSUTIL:
return False, 'win_status.py: Requires psutil'
# Namespace modules from `status.py`
global ping_master, time_
ping_master = _namespaced_function(ping_master, globals())
time_ = _namespaced_function(time_, globals())
return __virtualname__
__func_alias__ = {
'time_': 'time'
}
def cpustats():
'''
Return information about the CPU.
Returns
dict: A dictionary containing information about the CPU stats
CLI Example:
.. code-block:: bash
salt * status.cpustats
'''
# Tries to gather information similar to that returned by a Linux machine
# Avoid using WMI as there's a lot of overhead
# Time related info
user, system, idle, interrupt, dpc = psutil.cpu_times()
cpu = {'user': user,
'system': system,
'idle': idle,
'irq': interrupt,
'dpc': dpc}
# Count related info
ctx_switches, interrupts, soft_interrupts, sys_calls = psutil.cpu_stats()
intr = {'irqs': {'irqs': [],
'total': interrupts}}
soft_irq = {'softirqs': [],
'total': soft_interrupts}
return {'btime': psutil.boot_time(),
'cpu': cpu,
'ctxt': ctx_switches,
'intr': intr,
'processes': len(psutil.pids()),
'softirq': soft_irq,
'syscalls': sys_calls}
def meminfo():
'''
Return information about physical and virtual memory on the system
Returns:
dict: A dictionary of information about memory on the system
CLI Example:
.. code-block:: bash
salt * status.meminfo
'''
# Get physical memory
vm_total, vm_available, vm_percent, vm_used, vm_free = psutil.virtual_memory()
# Get swap memory
swp_total, swp_used, swp_free, swp_percent, _, _ = psutil.swap_memory()
def get_unit_value(memory):
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {}
for i, s in enumerate(symbols):
prefix[s] = 1 << (i + 1) * 10
for s in reversed(symbols):
if memory >= prefix[s]:
value = float(memory) / prefix[s]
return {'unit': s,
'value': value}
return {'unit': 'B',
'value': memory}
return {'VmallocTotal': get_unit_value(vm_total),
'VmallocUsed': get_unit_value(vm_used),
'VmallocFree': get_unit_value(vm_free),
'VmallocAvail': get_unit_value(vm_available),
'SwapTotal': get_unit_value(swp_total),
'SwapUsed': get_unit_value(swp_used),
'SwapFree': get_unit_value(swp_free)}
def loadavg():
'''
Returns counter information related to the load of the machine
Returns:
dict: A dictionary of counters
CLI Example:
.. code-block:: bash
salt * status.loadavg
'''
# Counter List (obj, instance, counter)
counter_list = [
('Memory', None, 'Available Bytes'),
('Memory', None, 'Pages/sec'),
('Paging File', '*', '% Usage'),
('Processor', '*', '% Processor Time'),
('Processor', '*', 'DPCs Queued/sec'),
('Processor', '*', '% Privileged Time'),
('Processor', '*', '% User Time'),
('Processor', '*', '% DPC Time'),
('Processor', '*', '% Interrupt Time'),
('Server', None, 'Work Item Shortages'),
('Server Work Queues', '*', 'Queue Length'),
('System', None, 'Processor Queue Length'),
('System', None, 'Context Switches/sec'),
]
return salt.utils.win_pdh.get_counters(counter_list=counter_list)
def cpuload():
'''
.. versionadded:: 2015.8.0
Return the processor load as a percentage
CLI Example:
.. code-block:: bash
salt '*' status.cpuload
'''
return psutil.cpu_percent()
def diskusage(human_readable=False, path=None):
'''
.. versionadded:: 2015.8.0
Return the disk usage for this minion
human_readable : False
If ``True``, usage will be in KB/MB/GB etc.
CLI Example:
.. code-block:: bash
salt '*' status.diskusage path=c:/salt
'''
if not path:
path = 'c:/'
disk_stats = psutil.disk_usage(path)
total_val = disk_stats.total
used_val = disk_stats.used
free_val = disk_stats.free
percent = disk_stats.percent
if human_readable:
total_val = _byte_calc(total_val)
used_val = _byte_calc(used_val)
free_val = _byte_calc(free_val)
return {'total': total_val,
'used': used_val,
'free': free_val,
'percent': percent}
def procs(count=False):
'''
Return the process data
count : False
If ``True``, this function will simply return the number of processes.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' status.procs
salt '*' status.procs count
'''
with salt.utils.winapi.Com():
wmi_obj = wmi.WMI()
processes = wmi_obj.win32_process()
#this short circuit's the function to get a short simple proc count.
if count:
return len(processes)
#a propper run of the function, creating a nonsensically long out put.
process_info = {}
for proc in processes:
process_info[proc.ProcessId] = _get_process_info(proc)
return process_info
def saltmem(human_readable=False):
'''
.. versionadded:: 2015.8.0
Returns the amount of memory that salt is using
human_readable : False
return the value in a nicely formatted number
CLI Example:
.. code-block:: bash
salt '*' status.saltmem
salt '*' status.saltmem human_readable=True
'''
# psutil.Process defaults to current process (`os.getpid()`)
p = psutil.Process()
# Use oneshot to get a snapshot
with p.oneshot():
mem = p.memory_info().rss
if human_readable:
return _byte_calc(mem)
return mem
def uptime(human_readable=False):
'''
.. versionadded:: 2015.8.0
Return the system uptime for the machine
Args:
human_readable (bool):
Return uptime in human readable format if ``True``, otherwise
return seconds. Default is ``False``
.. note::
Human readable format is ``days, hours:min:sec``. Days will only
be displayed if more than 0
Returns:
str:
The uptime in seconds or human readable format depending on the
value of ``human_readable``
CLI Example:
.. code-block:: bash
salt '*' status.uptime
salt '*' status.uptime human_readable=True
'''
# Get startup time
startup_time = datetime.datetime.fromtimestamp(psutil.boot_time())
# Subtract startup time from current time to get the uptime of the system
uptime = datetime.datetime.now() - startup_time
return six.text_type(uptime) if human_readable else uptime.total_seconds()
def _get_process_info(proc):
'''
Return process information
'''
cmd = salt.utils.stringutils.to_unicode(proc.CommandLine or '')
name = salt.utils.stringutils.to_unicode(proc.Name)
info = dict(
cmd=cmd,
name=name,
**_get_process_owner(proc)
)
return info
def _get_process_owner(process):
owner = {}
domain, error_code, user = None, None, None
try:
domain, error_code, user = process.GetOwner()
owner['user'] = salt.utils.stringutils.to_unicode(user)
owner['user_domain'] = salt.utils.stringutils.to_unicode(domain)
except Exception as exc:
pass
if not error_code and all((user, domain)):
owner['user'] = salt.utils.stringutils.to_unicode(user)
owner['user_domain'] = salt.utils.stringutils.to_unicode(domain)
elif process.ProcessId in [0, 4] and error_code == 2:
# Access Denied for System Idle Process and System
owner['user'] = 'SYSTEM'
owner['user_domain'] = 'NT AUTHORITY'
else:
log.warning('Error getting owner of process; PID=\'%s\'; Error: %s',
process.ProcessId, error_code)
return owner
def _byte_calc(val):
if val < 1024:
tstr = six.text_type(val)+'B'
elif val < 1038336:
tstr = six.text_type(val/1024)+'KB'
elif val < 1073741824:
tstr = six.text_type(val/1038336)+'MB'
elif val < 1099511627776:
tstr = six.text_type(val/1073741824)+'GB'
else:
tstr = six.text_type(val/1099511627776)+'TB'
return tstr
def master(master=None, connected=True):
'''
.. versionadded:: 2015.5.0
Fire an event if the minion gets disconnected from its master. This
function is meant to be run via a scheduled job from the minion. If
master_ip is an FQDN/Hostname, is must be resolvable to a valid IPv4
address.
CLI Example:
.. code-block:: bash
salt '*' status.master
'''
def _win_remotes_on(port):
'''
Windows specific helper function.
Returns set of ipv4 host addresses of remote established connections
on local or remote tcp port.
Parses output of shell 'netstat' to get connections
PS C:> netstat -n -p TCP
Active Connections
Proto Local Address Foreign Address State
TCP 10.1.1.26:3389 10.1.1.1:4505 ESTABLISHED
TCP 10.1.1.26:56862 10.1.1.10:49155 TIME_WAIT
TCP 10.1.1.26:56868 169.254.169.254:80 CLOSE_WAIT
TCP 127.0.0.1:49197 127.0.0.1:49198 ESTABLISHED
TCP 127.0.0.1:49198 127.0.0.1:49197 ESTABLISHED
'''
remotes = set()
try:
data = subprocess.check_output(['netstat', '-n', '-p', 'TCP']) # pylint: disable=minimum-python-version
except subprocess.CalledProcessError:
log.error('Failed netstat')
raise
lines = salt.utils.stringutils.to_unicode(data).split('\n')
for line in lines:
if 'ESTABLISHED' not in line:
continue
chunks = line.split()
remote_host, remote_port = chunks[2].rsplit(':', 1)
if int(remote_port) != port:
continue
remotes.add(remote_host)
return remotes
# the default publishing port
port = 4505
master_ips = None
if master:
master_ips = _host_to_ips(master)
if not master_ips:
return
if __salt__['config.get']('publish_port') != '':
port = int(__salt__['config.get']('publish_port'))
master_connection_status = False
connected_ips = _win_remotes_on(port)
# Get connection status for master
for master_ip in master_ips:
if master_ip in connected_ips:
master_connection_status = True
break
# Connection to master is not as expected
if master_connection_status is not connected:
event = salt.utils.event.get_event('minion', opts=__opts__, listen=False)
if master_connection_status:
event.fire_event({'master': master}, salt.minion.master_event(type='connected'))
else:
event.fire_event({'master': master}, salt.minion.master_event(type='disconnected'))
return master_connection_status
|
saltstack/salt
|
salt/modules/win_status.py
|
diskusage
|
python
|
def diskusage(human_readable=False, path=None):
'''
.. versionadded:: 2015.8.0
Return the disk usage for this minion
human_readable : False
If ``True``, usage will be in KB/MB/GB etc.
CLI Example:
.. code-block:: bash
salt '*' status.diskusage path=c:/salt
'''
if not path:
path = 'c:/'
disk_stats = psutil.disk_usage(path)
total_val = disk_stats.total
used_val = disk_stats.used
free_val = disk_stats.free
percent = disk_stats.percent
if human_readable:
total_val = _byte_calc(total_val)
used_val = _byte_calc(used_val)
free_val = _byte_calc(free_val)
return {'total': total_val,
'used': used_val,
'free': free_val,
'percent': percent}
|
.. versionadded:: 2015.8.0
Return the disk usage for this minion
human_readable : False
If ``True``, usage will be in KB/MB/GB etc.
CLI Example:
.. code-block:: bash
salt '*' status.diskusage path=c:/salt
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_status.py#L322-L355
|
[
"def _byte_calc(val):\n if val < 1024:\n tstr = six.text_type(val)+'B'\n elif val < 1038336:\n tstr = six.text_type(val/1024)+'KB'\n elif val < 1073741824:\n tstr = six.text_type(val/1038336)+'MB'\n elif val < 1099511627776:\n tstr = six.text_type(val/1073741824)+'GB'\n else:\n tstr = six.text_type(val/1099511627776)+'TB'\n return tstr\n"
] |
# -*- coding: utf-8 -*-
'''
Module for returning various status data about a minion.
These data can be useful for compiling into stats later,
or for problem solving if your minion is having problems.
.. versionadded:: 0.12.0
:depends: - wmi
'''
# Import Python Libs
from __future__ import absolute_import, unicode_literals, print_function
import ctypes
import datetime
import logging
import subprocess
log = logging.getLogger(__name__)
# Import Salt Libs
import salt.utils.event
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.win_pdh
from salt.utils.network import host_to_ips as _host_to_ips
from salt.utils.functools import namespaced_function as _namespaced_function
# Import 3rd party Libs
from salt.ext import six
# These imports needed for namespaced functions
# pylint: disable=W0611
from salt.modules.status import ping_master, time_
import copy
# pylint: enable=W0611
# Import 3rd Party Libs
try:
if salt.utils.platform.is_windows():
import wmi
import salt.utils.winapi
HAS_WMI = True
else:
HAS_WMI = False
except ImportError:
HAS_WMI = False
HAS_PSUTIL = False
if salt.utils.platform.is_windows():
import psutil
HAS_PSUTIL = True
__opts__ = {}
__virtualname__ = 'status'
# Taken from https://www.geoffchappell.com/studies/windows/km/ntoskrnl/api/ex/sysinfo/performance.htm
class SYSTEM_PERFORMANCE_INFORMATION(ctypes.Structure):
_fields_ = [('IdleProcessTime', ctypes.c_int64),
('IoReadTransferCount', ctypes.c_int64),
('IoWriteTransferCount', ctypes.c_int64),
('IoOtherTransferCount', ctypes.c_int64),
('IoReadOperationCount', ctypes.c_ulong),
('IoWriteOperationCount', ctypes.c_ulong),
('IoOtherOperationCount', ctypes.c_ulong),
('AvailablePages', ctypes.c_ulong),
('CommittedPages', ctypes.c_ulong),
('CommitLimit', ctypes.c_ulong),
('PeakCommitment', ctypes.c_ulong),
('PageFaultCount', ctypes.c_ulong),
('CopyOnWriteCount', ctypes.c_ulong),
('TransitionCount', ctypes.c_ulong),
('CacheTransitionCount', ctypes.c_ulong),
('DemandZeroCount', ctypes.c_ulong),
('PageReadCount', ctypes.c_ulong),
('PageReadIoCount', ctypes.c_ulong),
('CacheReadCount', ctypes.c_ulong), # Was c_ulong ** 2
('CacheIoCount', ctypes.c_ulong),
('DirtyPagesWriteCount', ctypes.c_ulong),
('DirtyWriteIoCount', ctypes.c_ulong),
('MappedPagesWriteCount', ctypes.c_ulong),
('MappedWriteIoCount', ctypes.c_ulong),
('PagedPoolPages', ctypes.c_ulong),
('NonPagedPoolPages', ctypes.c_ulong),
('PagedPoolAllocs', ctypes.c_ulong),
('PagedPoolFrees', ctypes.c_ulong),
('NonPagedPoolAllocs', ctypes.c_ulong),
('NonPagedPoolFrees', ctypes.c_ulong),
('FreeSystemPtes', ctypes.c_ulong),
('ResidentSystemCodePage', ctypes.c_ulong),
('TotalSystemDriverPages', ctypes.c_ulong),
('TotalSystemCodePages', ctypes.c_ulong),
('NonPagedPoolLookasideHits', ctypes.c_ulong),
('PagedPoolLookasideHits', ctypes.c_ulong),
('AvailablePagedPoolPages', ctypes.c_ulong),
('ResidentSystemCachePage', ctypes.c_ulong),
('ResidentPagedPoolPage', ctypes.c_ulong),
('ResidentSystemDriverPage', ctypes.c_ulong),
('CcFastReadNoWait', ctypes.c_ulong),
('CcFastReadWait', ctypes.c_ulong),
('CcFastReadResourceMiss', ctypes.c_ulong),
('CcFastReadNotPossible', ctypes.c_ulong),
('CcFastMdlReadNoWait', ctypes.c_ulong),
('CcFastMdlReadWait', ctypes.c_ulong),
('CcFastMdlReadResourceMiss', ctypes.c_ulong),
('CcFastMdlReadNotPossible', ctypes.c_ulong),
('CcMapDataNoWait', ctypes.c_ulong),
('CcMapDataWait', ctypes.c_ulong),
('CcMapDataNoWaitMiss', ctypes.c_ulong),
('CcMapDataWaitMiss', ctypes.c_ulong),
('CcPinMappedDataCount', ctypes.c_ulong),
('CcPinReadNoWait', ctypes.c_ulong),
('CcPinReadWait', ctypes.c_ulong),
('CcPinReadNoWaitMiss', ctypes.c_ulong),
('CcPinReadWaitMiss', ctypes.c_ulong),
('CcCopyReadNoWait', ctypes.c_ulong),
('CcCopyReadWait', ctypes.c_ulong),
('CcCopyReadNoWaitMiss', ctypes.c_ulong),
('CcCopyReadWaitMiss', ctypes.c_ulong),
('CcMdlReadNoWait', ctypes.c_ulong),
('CcMdlReadWait', ctypes.c_ulong),
('CcMdlReadNoWaitMiss', ctypes.c_ulong),
('CcMdlReadWaitMiss', ctypes.c_ulong),
('CcReadAheadIos', ctypes.c_ulong),
('CcLazyWriteIos', ctypes.c_ulong),
('CcLazyWritePages', ctypes.c_ulong),
('CcDataFlushes', ctypes.c_ulong),
('CcDataPages', ctypes.c_ulong),
('ContextSwitches', ctypes.c_ulong),
('FirstLevelTbFills', ctypes.c_ulong),
('SecondLevelTbFills', ctypes.c_ulong),
('SystemCalls', ctypes.c_ulong),
# Windows 8 and above
('CcTotalDirtyPages', ctypes.c_ulonglong),
('CcDirtyPagesThreshold', ctypes.c_ulonglong),
('ResidentAvailablePages', ctypes.c_longlong),
# Windows 10 and above
('SharedCommittedPages', ctypes.c_ulonglong)]
def __virtual__():
'''
Only works on Windows systems with WMI and WinAPI
'''
if not salt.utils.platform.is_windows():
return False, 'win_status.py: Requires Windows'
if not HAS_WMI:
return False, 'win_status.py: Requires WMI and WinAPI'
if not HAS_PSUTIL:
return False, 'win_status.py: Requires psutil'
# Namespace modules from `status.py`
global ping_master, time_
ping_master = _namespaced_function(ping_master, globals())
time_ = _namespaced_function(time_, globals())
return __virtualname__
__func_alias__ = {
'time_': 'time'
}
def cpustats():
'''
Return information about the CPU.
Returns
dict: A dictionary containing information about the CPU stats
CLI Example:
.. code-block:: bash
salt * status.cpustats
'''
# Tries to gather information similar to that returned by a Linux machine
# Avoid using WMI as there's a lot of overhead
# Time related info
user, system, idle, interrupt, dpc = psutil.cpu_times()
cpu = {'user': user,
'system': system,
'idle': idle,
'irq': interrupt,
'dpc': dpc}
# Count related info
ctx_switches, interrupts, soft_interrupts, sys_calls = psutil.cpu_stats()
intr = {'irqs': {'irqs': [],
'total': interrupts}}
soft_irq = {'softirqs': [],
'total': soft_interrupts}
return {'btime': psutil.boot_time(),
'cpu': cpu,
'ctxt': ctx_switches,
'intr': intr,
'processes': len(psutil.pids()),
'softirq': soft_irq,
'syscalls': sys_calls}
def meminfo():
'''
Return information about physical and virtual memory on the system
Returns:
dict: A dictionary of information about memory on the system
CLI Example:
.. code-block:: bash
salt * status.meminfo
'''
# Get physical memory
vm_total, vm_available, vm_percent, vm_used, vm_free = psutil.virtual_memory()
# Get swap memory
swp_total, swp_used, swp_free, swp_percent, _, _ = psutil.swap_memory()
def get_unit_value(memory):
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {}
for i, s in enumerate(symbols):
prefix[s] = 1 << (i + 1) * 10
for s in reversed(symbols):
if memory >= prefix[s]:
value = float(memory) / prefix[s]
return {'unit': s,
'value': value}
return {'unit': 'B',
'value': memory}
return {'VmallocTotal': get_unit_value(vm_total),
'VmallocUsed': get_unit_value(vm_used),
'VmallocFree': get_unit_value(vm_free),
'VmallocAvail': get_unit_value(vm_available),
'SwapTotal': get_unit_value(swp_total),
'SwapUsed': get_unit_value(swp_used),
'SwapFree': get_unit_value(swp_free)}
def vmstats():
'''
Return information about the virtual memory on the machine
Returns:
dict: A dictionary of virtual memory stats
CLI Example:
.. code-block:: bash
salt * status.vmstats
'''
# Setup the SPI Structure
spi = SYSTEM_PERFORMANCE_INFORMATION()
retlen = ctypes.c_ulong()
# 2 means to query System Performance Information and return it in a
# SYSTEM_PERFORMANCE_INFORMATION Structure
ctypes.windll.ntdll.NtQuerySystemInformation(
2, ctypes.byref(spi), ctypes.sizeof(spi), ctypes.byref(retlen))
# Return each defined field in a dict
ret = {}
for field in spi._fields_:
ret.update({field[0]: getattr(spi, field[0])})
return ret
def loadavg():
'''
Returns counter information related to the load of the machine
Returns:
dict: A dictionary of counters
CLI Example:
.. code-block:: bash
salt * status.loadavg
'''
# Counter List (obj, instance, counter)
counter_list = [
('Memory', None, 'Available Bytes'),
('Memory', None, 'Pages/sec'),
('Paging File', '*', '% Usage'),
('Processor', '*', '% Processor Time'),
('Processor', '*', 'DPCs Queued/sec'),
('Processor', '*', '% Privileged Time'),
('Processor', '*', '% User Time'),
('Processor', '*', '% DPC Time'),
('Processor', '*', '% Interrupt Time'),
('Server', None, 'Work Item Shortages'),
('Server Work Queues', '*', 'Queue Length'),
('System', None, 'Processor Queue Length'),
('System', None, 'Context Switches/sec'),
]
return salt.utils.win_pdh.get_counters(counter_list=counter_list)
def cpuload():
'''
.. versionadded:: 2015.8.0
Return the processor load as a percentage
CLI Example:
.. code-block:: bash
salt '*' status.cpuload
'''
return psutil.cpu_percent()
def procs(count=False):
'''
Return the process data
count : False
If ``True``, this function will simply return the number of processes.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' status.procs
salt '*' status.procs count
'''
with salt.utils.winapi.Com():
wmi_obj = wmi.WMI()
processes = wmi_obj.win32_process()
#this short circuit's the function to get a short simple proc count.
if count:
return len(processes)
#a propper run of the function, creating a nonsensically long out put.
process_info = {}
for proc in processes:
process_info[proc.ProcessId] = _get_process_info(proc)
return process_info
def saltmem(human_readable=False):
'''
.. versionadded:: 2015.8.0
Returns the amount of memory that salt is using
human_readable : False
return the value in a nicely formatted number
CLI Example:
.. code-block:: bash
salt '*' status.saltmem
salt '*' status.saltmem human_readable=True
'''
# psutil.Process defaults to current process (`os.getpid()`)
p = psutil.Process()
# Use oneshot to get a snapshot
with p.oneshot():
mem = p.memory_info().rss
if human_readable:
return _byte_calc(mem)
return mem
def uptime(human_readable=False):
'''
.. versionadded:: 2015.8.0
Return the system uptime for the machine
Args:
human_readable (bool):
Return uptime in human readable format if ``True``, otherwise
return seconds. Default is ``False``
.. note::
Human readable format is ``days, hours:min:sec``. Days will only
be displayed if more than 0
Returns:
str:
The uptime in seconds or human readable format depending on the
value of ``human_readable``
CLI Example:
.. code-block:: bash
salt '*' status.uptime
salt '*' status.uptime human_readable=True
'''
# Get startup time
startup_time = datetime.datetime.fromtimestamp(psutil.boot_time())
# Subtract startup time from current time to get the uptime of the system
uptime = datetime.datetime.now() - startup_time
return six.text_type(uptime) if human_readable else uptime.total_seconds()
def _get_process_info(proc):
'''
Return process information
'''
cmd = salt.utils.stringutils.to_unicode(proc.CommandLine or '')
name = salt.utils.stringutils.to_unicode(proc.Name)
info = dict(
cmd=cmd,
name=name,
**_get_process_owner(proc)
)
return info
def _get_process_owner(process):
owner = {}
domain, error_code, user = None, None, None
try:
domain, error_code, user = process.GetOwner()
owner['user'] = salt.utils.stringutils.to_unicode(user)
owner['user_domain'] = salt.utils.stringutils.to_unicode(domain)
except Exception as exc:
pass
if not error_code and all((user, domain)):
owner['user'] = salt.utils.stringutils.to_unicode(user)
owner['user_domain'] = salt.utils.stringutils.to_unicode(domain)
elif process.ProcessId in [0, 4] and error_code == 2:
# Access Denied for System Idle Process and System
owner['user'] = 'SYSTEM'
owner['user_domain'] = 'NT AUTHORITY'
else:
log.warning('Error getting owner of process; PID=\'%s\'; Error: %s',
process.ProcessId, error_code)
return owner
def _byte_calc(val):
if val < 1024:
tstr = six.text_type(val)+'B'
elif val < 1038336:
tstr = six.text_type(val/1024)+'KB'
elif val < 1073741824:
tstr = six.text_type(val/1038336)+'MB'
elif val < 1099511627776:
tstr = six.text_type(val/1073741824)+'GB'
else:
tstr = six.text_type(val/1099511627776)+'TB'
return tstr
def master(master=None, connected=True):
'''
.. versionadded:: 2015.5.0
Fire an event if the minion gets disconnected from its master. This
function is meant to be run via a scheduled job from the minion. If
master_ip is an FQDN/Hostname, is must be resolvable to a valid IPv4
address.
CLI Example:
.. code-block:: bash
salt '*' status.master
'''
def _win_remotes_on(port):
'''
Windows specific helper function.
Returns set of ipv4 host addresses of remote established connections
on local or remote tcp port.
Parses output of shell 'netstat' to get connections
PS C:> netstat -n -p TCP
Active Connections
Proto Local Address Foreign Address State
TCP 10.1.1.26:3389 10.1.1.1:4505 ESTABLISHED
TCP 10.1.1.26:56862 10.1.1.10:49155 TIME_WAIT
TCP 10.1.1.26:56868 169.254.169.254:80 CLOSE_WAIT
TCP 127.0.0.1:49197 127.0.0.1:49198 ESTABLISHED
TCP 127.0.0.1:49198 127.0.0.1:49197 ESTABLISHED
'''
remotes = set()
try:
data = subprocess.check_output(['netstat', '-n', '-p', 'TCP']) # pylint: disable=minimum-python-version
except subprocess.CalledProcessError:
log.error('Failed netstat')
raise
lines = salt.utils.stringutils.to_unicode(data).split('\n')
for line in lines:
if 'ESTABLISHED' not in line:
continue
chunks = line.split()
remote_host, remote_port = chunks[2].rsplit(':', 1)
if int(remote_port) != port:
continue
remotes.add(remote_host)
return remotes
# the default publishing port
port = 4505
master_ips = None
if master:
master_ips = _host_to_ips(master)
if not master_ips:
return
if __salt__['config.get']('publish_port') != '':
port = int(__salt__['config.get']('publish_port'))
master_connection_status = False
connected_ips = _win_remotes_on(port)
# Get connection status for master
for master_ip in master_ips:
if master_ip in connected_ips:
master_connection_status = True
break
# Connection to master is not as expected
if master_connection_status is not connected:
event = salt.utils.event.get_event('minion', opts=__opts__, listen=False)
if master_connection_status:
event.fire_event({'master': master}, salt.minion.master_event(type='connected'))
else:
event.fire_event({'master': master}, salt.minion.master_event(type='disconnected'))
return master_connection_status
|
saltstack/salt
|
salt/modules/win_status.py
|
procs
|
python
|
def procs(count=False):
'''
Return the process data
count : False
If ``True``, this function will simply return the number of processes.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' status.procs
salt '*' status.procs count
'''
with salt.utils.winapi.Com():
wmi_obj = wmi.WMI()
processes = wmi_obj.win32_process()
#this short circuit's the function to get a short simple proc count.
if count:
return len(processes)
#a propper run of the function, creating a nonsensically long out put.
process_info = {}
for proc in processes:
process_info[proc.ProcessId] = _get_process_info(proc)
return process_info
|
Return the process data
count : False
If ``True``, this function will simply return the number of processes.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' status.procs
salt '*' status.procs count
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_status.py#L358-L387
|
[
"def _get_process_info(proc):\n '''\n Return process information\n '''\n cmd = salt.utils.stringutils.to_unicode(proc.CommandLine or '')\n name = salt.utils.stringutils.to_unicode(proc.Name)\n info = dict(\n cmd=cmd,\n name=name,\n **_get_process_owner(proc)\n )\n return info\n"
] |
# -*- coding: utf-8 -*-
'''
Module for returning various status data about a minion.
These data can be useful for compiling into stats later,
or for problem solving if your minion is having problems.
.. versionadded:: 0.12.0
:depends: - wmi
'''
# Import Python Libs
from __future__ import absolute_import, unicode_literals, print_function
import ctypes
import datetime
import logging
import subprocess
log = logging.getLogger(__name__)
# Import Salt Libs
import salt.utils.event
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.win_pdh
from salt.utils.network import host_to_ips as _host_to_ips
from salt.utils.functools import namespaced_function as _namespaced_function
# Import 3rd party Libs
from salt.ext import six
# These imports needed for namespaced functions
# pylint: disable=W0611
from salt.modules.status import ping_master, time_
import copy
# pylint: enable=W0611
# Import 3rd Party Libs
try:
if salt.utils.platform.is_windows():
import wmi
import salt.utils.winapi
HAS_WMI = True
else:
HAS_WMI = False
except ImportError:
HAS_WMI = False
HAS_PSUTIL = False
if salt.utils.platform.is_windows():
import psutil
HAS_PSUTIL = True
__opts__ = {}
__virtualname__ = 'status'
# Taken from https://www.geoffchappell.com/studies/windows/km/ntoskrnl/api/ex/sysinfo/performance.htm
class SYSTEM_PERFORMANCE_INFORMATION(ctypes.Structure):
_fields_ = [('IdleProcessTime', ctypes.c_int64),
('IoReadTransferCount', ctypes.c_int64),
('IoWriteTransferCount', ctypes.c_int64),
('IoOtherTransferCount', ctypes.c_int64),
('IoReadOperationCount', ctypes.c_ulong),
('IoWriteOperationCount', ctypes.c_ulong),
('IoOtherOperationCount', ctypes.c_ulong),
('AvailablePages', ctypes.c_ulong),
('CommittedPages', ctypes.c_ulong),
('CommitLimit', ctypes.c_ulong),
('PeakCommitment', ctypes.c_ulong),
('PageFaultCount', ctypes.c_ulong),
('CopyOnWriteCount', ctypes.c_ulong),
('TransitionCount', ctypes.c_ulong),
('CacheTransitionCount', ctypes.c_ulong),
('DemandZeroCount', ctypes.c_ulong),
('PageReadCount', ctypes.c_ulong),
('PageReadIoCount', ctypes.c_ulong),
('CacheReadCount', ctypes.c_ulong), # Was c_ulong ** 2
('CacheIoCount', ctypes.c_ulong),
('DirtyPagesWriteCount', ctypes.c_ulong),
('DirtyWriteIoCount', ctypes.c_ulong),
('MappedPagesWriteCount', ctypes.c_ulong),
('MappedWriteIoCount', ctypes.c_ulong),
('PagedPoolPages', ctypes.c_ulong),
('NonPagedPoolPages', ctypes.c_ulong),
('PagedPoolAllocs', ctypes.c_ulong),
('PagedPoolFrees', ctypes.c_ulong),
('NonPagedPoolAllocs', ctypes.c_ulong),
('NonPagedPoolFrees', ctypes.c_ulong),
('FreeSystemPtes', ctypes.c_ulong),
('ResidentSystemCodePage', ctypes.c_ulong),
('TotalSystemDriverPages', ctypes.c_ulong),
('TotalSystemCodePages', ctypes.c_ulong),
('NonPagedPoolLookasideHits', ctypes.c_ulong),
('PagedPoolLookasideHits', ctypes.c_ulong),
('AvailablePagedPoolPages', ctypes.c_ulong),
('ResidentSystemCachePage', ctypes.c_ulong),
('ResidentPagedPoolPage', ctypes.c_ulong),
('ResidentSystemDriverPage', ctypes.c_ulong),
('CcFastReadNoWait', ctypes.c_ulong),
('CcFastReadWait', ctypes.c_ulong),
('CcFastReadResourceMiss', ctypes.c_ulong),
('CcFastReadNotPossible', ctypes.c_ulong),
('CcFastMdlReadNoWait', ctypes.c_ulong),
('CcFastMdlReadWait', ctypes.c_ulong),
('CcFastMdlReadResourceMiss', ctypes.c_ulong),
('CcFastMdlReadNotPossible', ctypes.c_ulong),
('CcMapDataNoWait', ctypes.c_ulong),
('CcMapDataWait', ctypes.c_ulong),
('CcMapDataNoWaitMiss', ctypes.c_ulong),
('CcMapDataWaitMiss', ctypes.c_ulong),
('CcPinMappedDataCount', ctypes.c_ulong),
('CcPinReadNoWait', ctypes.c_ulong),
('CcPinReadWait', ctypes.c_ulong),
('CcPinReadNoWaitMiss', ctypes.c_ulong),
('CcPinReadWaitMiss', ctypes.c_ulong),
('CcCopyReadNoWait', ctypes.c_ulong),
('CcCopyReadWait', ctypes.c_ulong),
('CcCopyReadNoWaitMiss', ctypes.c_ulong),
('CcCopyReadWaitMiss', ctypes.c_ulong),
('CcMdlReadNoWait', ctypes.c_ulong),
('CcMdlReadWait', ctypes.c_ulong),
('CcMdlReadNoWaitMiss', ctypes.c_ulong),
('CcMdlReadWaitMiss', ctypes.c_ulong),
('CcReadAheadIos', ctypes.c_ulong),
('CcLazyWriteIos', ctypes.c_ulong),
('CcLazyWritePages', ctypes.c_ulong),
('CcDataFlushes', ctypes.c_ulong),
('CcDataPages', ctypes.c_ulong),
('ContextSwitches', ctypes.c_ulong),
('FirstLevelTbFills', ctypes.c_ulong),
('SecondLevelTbFills', ctypes.c_ulong),
('SystemCalls', ctypes.c_ulong),
# Windows 8 and above
('CcTotalDirtyPages', ctypes.c_ulonglong),
('CcDirtyPagesThreshold', ctypes.c_ulonglong),
('ResidentAvailablePages', ctypes.c_longlong),
# Windows 10 and above
('SharedCommittedPages', ctypes.c_ulonglong)]
def __virtual__():
'''
Only works on Windows systems with WMI and WinAPI
'''
if not salt.utils.platform.is_windows():
return False, 'win_status.py: Requires Windows'
if not HAS_WMI:
return False, 'win_status.py: Requires WMI and WinAPI'
if not HAS_PSUTIL:
return False, 'win_status.py: Requires psutil'
# Namespace modules from `status.py`
global ping_master, time_
ping_master = _namespaced_function(ping_master, globals())
time_ = _namespaced_function(time_, globals())
return __virtualname__
__func_alias__ = {
'time_': 'time'
}
def cpustats():
'''
Return information about the CPU.
Returns
dict: A dictionary containing information about the CPU stats
CLI Example:
.. code-block:: bash
salt * status.cpustats
'''
# Tries to gather information similar to that returned by a Linux machine
# Avoid using WMI as there's a lot of overhead
# Time related info
user, system, idle, interrupt, dpc = psutil.cpu_times()
cpu = {'user': user,
'system': system,
'idle': idle,
'irq': interrupt,
'dpc': dpc}
# Count related info
ctx_switches, interrupts, soft_interrupts, sys_calls = psutil.cpu_stats()
intr = {'irqs': {'irqs': [],
'total': interrupts}}
soft_irq = {'softirqs': [],
'total': soft_interrupts}
return {'btime': psutil.boot_time(),
'cpu': cpu,
'ctxt': ctx_switches,
'intr': intr,
'processes': len(psutil.pids()),
'softirq': soft_irq,
'syscalls': sys_calls}
def meminfo():
'''
Return information about physical and virtual memory on the system
Returns:
dict: A dictionary of information about memory on the system
CLI Example:
.. code-block:: bash
salt * status.meminfo
'''
# Get physical memory
vm_total, vm_available, vm_percent, vm_used, vm_free = psutil.virtual_memory()
# Get swap memory
swp_total, swp_used, swp_free, swp_percent, _, _ = psutil.swap_memory()
def get_unit_value(memory):
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {}
for i, s in enumerate(symbols):
prefix[s] = 1 << (i + 1) * 10
for s in reversed(symbols):
if memory >= prefix[s]:
value = float(memory) / prefix[s]
return {'unit': s,
'value': value}
return {'unit': 'B',
'value': memory}
return {'VmallocTotal': get_unit_value(vm_total),
'VmallocUsed': get_unit_value(vm_used),
'VmallocFree': get_unit_value(vm_free),
'VmallocAvail': get_unit_value(vm_available),
'SwapTotal': get_unit_value(swp_total),
'SwapUsed': get_unit_value(swp_used),
'SwapFree': get_unit_value(swp_free)}
def vmstats():
'''
Return information about the virtual memory on the machine
Returns:
dict: A dictionary of virtual memory stats
CLI Example:
.. code-block:: bash
salt * status.vmstats
'''
# Setup the SPI Structure
spi = SYSTEM_PERFORMANCE_INFORMATION()
retlen = ctypes.c_ulong()
# 2 means to query System Performance Information and return it in a
# SYSTEM_PERFORMANCE_INFORMATION Structure
ctypes.windll.ntdll.NtQuerySystemInformation(
2, ctypes.byref(spi), ctypes.sizeof(spi), ctypes.byref(retlen))
# Return each defined field in a dict
ret = {}
for field in spi._fields_:
ret.update({field[0]: getattr(spi, field[0])})
return ret
def loadavg():
'''
Returns counter information related to the load of the machine
Returns:
dict: A dictionary of counters
CLI Example:
.. code-block:: bash
salt * status.loadavg
'''
# Counter List (obj, instance, counter)
counter_list = [
('Memory', None, 'Available Bytes'),
('Memory', None, 'Pages/sec'),
('Paging File', '*', '% Usage'),
('Processor', '*', '% Processor Time'),
('Processor', '*', 'DPCs Queued/sec'),
('Processor', '*', '% Privileged Time'),
('Processor', '*', '% User Time'),
('Processor', '*', '% DPC Time'),
('Processor', '*', '% Interrupt Time'),
('Server', None, 'Work Item Shortages'),
('Server Work Queues', '*', 'Queue Length'),
('System', None, 'Processor Queue Length'),
('System', None, 'Context Switches/sec'),
]
return salt.utils.win_pdh.get_counters(counter_list=counter_list)
def cpuload():
'''
.. versionadded:: 2015.8.0
Return the processor load as a percentage
CLI Example:
.. code-block:: bash
salt '*' status.cpuload
'''
return psutil.cpu_percent()
def diskusage(human_readable=False, path=None):
'''
.. versionadded:: 2015.8.0
Return the disk usage for this minion
human_readable : False
If ``True``, usage will be in KB/MB/GB etc.
CLI Example:
.. code-block:: bash
salt '*' status.diskusage path=c:/salt
'''
if not path:
path = 'c:/'
disk_stats = psutil.disk_usage(path)
total_val = disk_stats.total
used_val = disk_stats.used
free_val = disk_stats.free
percent = disk_stats.percent
if human_readable:
total_val = _byte_calc(total_val)
used_val = _byte_calc(used_val)
free_val = _byte_calc(free_val)
return {'total': total_val,
'used': used_val,
'free': free_val,
'percent': percent}
def saltmem(human_readable=False):
'''
.. versionadded:: 2015.8.0
Returns the amount of memory that salt is using
human_readable : False
return the value in a nicely formatted number
CLI Example:
.. code-block:: bash
salt '*' status.saltmem
salt '*' status.saltmem human_readable=True
'''
# psutil.Process defaults to current process (`os.getpid()`)
p = psutil.Process()
# Use oneshot to get a snapshot
with p.oneshot():
mem = p.memory_info().rss
if human_readable:
return _byte_calc(mem)
return mem
def uptime(human_readable=False):
'''
.. versionadded:: 2015.8.0
Return the system uptime for the machine
Args:
human_readable (bool):
Return uptime in human readable format if ``True``, otherwise
return seconds. Default is ``False``
.. note::
Human readable format is ``days, hours:min:sec``. Days will only
be displayed if more than 0
Returns:
str:
The uptime in seconds or human readable format depending on the
value of ``human_readable``
CLI Example:
.. code-block:: bash
salt '*' status.uptime
salt '*' status.uptime human_readable=True
'''
# Get startup time
startup_time = datetime.datetime.fromtimestamp(psutil.boot_time())
# Subtract startup time from current time to get the uptime of the system
uptime = datetime.datetime.now() - startup_time
return six.text_type(uptime) if human_readable else uptime.total_seconds()
def _get_process_info(proc):
'''
Return process information
'''
cmd = salt.utils.stringutils.to_unicode(proc.CommandLine or '')
name = salt.utils.stringutils.to_unicode(proc.Name)
info = dict(
cmd=cmd,
name=name,
**_get_process_owner(proc)
)
return info
def _get_process_owner(process):
owner = {}
domain, error_code, user = None, None, None
try:
domain, error_code, user = process.GetOwner()
owner['user'] = salt.utils.stringutils.to_unicode(user)
owner['user_domain'] = salt.utils.stringutils.to_unicode(domain)
except Exception as exc:
pass
if not error_code and all((user, domain)):
owner['user'] = salt.utils.stringutils.to_unicode(user)
owner['user_domain'] = salt.utils.stringutils.to_unicode(domain)
elif process.ProcessId in [0, 4] and error_code == 2:
# Access Denied for System Idle Process and System
owner['user'] = 'SYSTEM'
owner['user_domain'] = 'NT AUTHORITY'
else:
log.warning('Error getting owner of process; PID=\'%s\'; Error: %s',
process.ProcessId, error_code)
return owner
def _byte_calc(val):
if val < 1024:
tstr = six.text_type(val)+'B'
elif val < 1038336:
tstr = six.text_type(val/1024)+'KB'
elif val < 1073741824:
tstr = six.text_type(val/1038336)+'MB'
elif val < 1099511627776:
tstr = six.text_type(val/1073741824)+'GB'
else:
tstr = six.text_type(val/1099511627776)+'TB'
return tstr
def master(master=None, connected=True):
'''
.. versionadded:: 2015.5.0
Fire an event if the minion gets disconnected from its master. This
function is meant to be run via a scheduled job from the minion. If
master_ip is an FQDN/Hostname, is must be resolvable to a valid IPv4
address.
CLI Example:
.. code-block:: bash
salt '*' status.master
'''
def _win_remotes_on(port):
'''
Windows specific helper function.
Returns set of ipv4 host addresses of remote established connections
on local or remote tcp port.
Parses output of shell 'netstat' to get connections
PS C:> netstat -n -p TCP
Active Connections
Proto Local Address Foreign Address State
TCP 10.1.1.26:3389 10.1.1.1:4505 ESTABLISHED
TCP 10.1.1.26:56862 10.1.1.10:49155 TIME_WAIT
TCP 10.1.1.26:56868 169.254.169.254:80 CLOSE_WAIT
TCP 127.0.0.1:49197 127.0.0.1:49198 ESTABLISHED
TCP 127.0.0.1:49198 127.0.0.1:49197 ESTABLISHED
'''
remotes = set()
try:
data = subprocess.check_output(['netstat', '-n', '-p', 'TCP']) # pylint: disable=minimum-python-version
except subprocess.CalledProcessError:
log.error('Failed netstat')
raise
lines = salt.utils.stringutils.to_unicode(data).split('\n')
for line in lines:
if 'ESTABLISHED' not in line:
continue
chunks = line.split()
remote_host, remote_port = chunks[2].rsplit(':', 1)
if int(remote_port) != port:
continue
remotes.add(remote_host)
return remotes
# the default publishing port
port = 4505
master_ips = None
if master:
master_ips = _host_to_ips(master)
if not master_ips:
return
if __salt__['config.get']('publish_port') != '':
port = int(__salt__['config.get']('publish_port'))
master_connection_status = False
connected_ips = _win_remotes_on(port)
# Get connection status for master
for master_ip in master_ips:
if master_ip in connected_ips:
master_connection_status = True
break
# Connection to master is not as expected
if master_connection_status is not connected:
event = salt.utils.event.get_event('minion', opts=__opts__, listen=False)
if master_connection_status:
event.fire_event({'master': master}, salt.minion.master_event(type='connected'))
else:
event.fire_event({'master': master}, salt.minion.master_event(type='disconnected'))
return master_connection_status
|
saltstack/salt
|
salt/modules/win_status.py
|
saltmem
|
python
|
def saltmem(human_readable=False):
'''
.. versionadded:: 2015.8.0
Returns the amount of memory that salt is using
human_readable : False
return the value in a nicely formatted number
CLI Example:
.. code-block:: bash
salt '*' status.saltmem
salt '*' status.saltmem human_readable=True
'''
# psutil.Process defaults to current process (`os.getpid()`)
p = psutil.Process()
# Use oneshot to get a snapshot
with p.oneshot():
mem = p.memory_info().rss
if human_readable:
return _byte_calc(mem)
return mem
|
.. versionadded:: 2015.8.0
Returns the amount of memory that salt is using
human_readable : False
return the value in a nicely formatted number
CLI Example:
.. code-block:: bash
salt '*' status.saltmem
salt '*' status.saltmem human_readable=True
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_status.py#L390-L416
|
[
"def _byte_calc(val):\n if val < 1024:\n tstr = six.text_type(val)+'B'\n elif val < 1038336:\n tstr = six.text_type(val/1024)+'KB'\n elif val < 1073741824:\n tstr = six.text_type(val/1038336)+'MB'\n elif val < 1099511627776:\n tstr = six.text_type(val/1073741824)+'GB'\n else:\n tstr = six.text_type(val/1099511627776)+'TB'\n return tstr\n"
] |
# -*- coding: utf-8 -*-
'''
Module for returning various status data about a minion.
These data can be useful for compiling into stats later,
or for problem solving if your minion is having problems.
.. versionadded:: 0.12.0
:depends: - wmi
'''
# Import Python Libs
from __future__ import absolute_import, unicode_literals, print_function
import ctypes
import datetime
import logging
import subprocess
log = logging.getLogger(__name__)
# Import Salt Libs
import salt.utils.event
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.win_pdh
from salt.utils.network import host_to_ips as _host_to_ips
from salt.utils.functools import namespaced_function as _namespaced_function
# Import 3rd party Libs
from salt.ext import six
# These imports needed for namespaced functions
# pylint: disable=W0611
from salt.modules.status import ping_master, time_
import copy
# pylint: enable=W0611
# Import 3rd Party Libs
try:
if salt.utils.platform.is_windows():
import wmi
import salt.utils.winapi
HAS_WMI = True
else:
HAS_WMI = False
except ImportError:
HAS_WMI = False
HAS_PSUTIL = False
if salt.utils.platform.is_windows():
import psutil
HAS_PSUTIL = True
__opts__ = {}
__virtualname__ = 'status'
# Taken from https://www.geoffchappell.com/studies/windows/km/ntoskrnl/api/ex/sysinfo/performance.htm
class SYSTEM_PERFORMANCE_INFORMATION(ctypes.Structure):
_fields_ = [('IdleProcessTime', ctypes.c_int64),
('IoReadTransferCount', ctypes.c_int64),
('IoWriteTransferCount', ctypes.c_int64),
('IoOtherTransferCount', ctypes.c_int64),
('IoReadOperationCount', ctypes.c_ulong),
('IoWriteOperationCount', ctypes.c_ulong),
('IoOtherOperationCount', ctypes.c_ulong),
('AvailablePages', ctypes.c_ulong),
('CommittedPages', ctypes.c_ulong),
('CommitLimit', ctypes.c_ulong),
('PeakCommitment', ctypes.c_ulong),
('PageFaultCount', ctypes.c_ulong),
('CopyOnWriteCount', ctypes.c_ulong),
('TransitionCount', ctypes.c_ulong),
('CacheTransitionCount', ctypes.c_ulong),
('DemandZeroCount', ctypes.c_ulong),
('PageReadCount', ctypes.c_ulong),
('PageReadIoCount', ctypes.c_ulong),
('CacheReadCount', ctypes.c_ulong), # Was c_ulong ** 2
('CacheIoCount', ctypes.c_ulong),
('DirtyPagesWriteCount', ctypes.c_ulong),
('DirtyWriteIoCount', ctypes.c_ulong),
('MappedPagesWriteCount', ctypes.c_ulong),
('MappedWriteIoCount', ctypes.c_ulong),
('PagedPoolPages', ctypes.c_ulong),
('NonPagedPoolPages', ctypes.c_ulong),
('PagedPoolAllocs', ctypes.c_ulong),
('PagedPoolFrees', ctypes.c_ulong),
('NonPagedPoolAllocs', ctypes.c_ulong),
('NonPagedPoolFrees', ctypes.c_ulong),
('FreeSystemPtes', ctypes.c_ulong),
('ResidentSystemCodePage', ctypes.c_ulong),
('TotalSystemDriverPages', ctypes.c_ulong),
('TotalSystemCodePages', ctypes.c_ulong),
('NonPagedPoolLookasideHits', ctypes.c_ulong),
('PagedPoolLookasideHits', ctypes.c_ulong),
('AvailablePagedPoolPages', ctypes.c_ulong),
('ResidentSystemCachePage', ctypes.c_ulong),
('ResidentPagedPoolPage', ctypes.c_ulong),
('ResidentSystemDriverPage', ctypes.c_ulong),
('CcFastReadNoWait', ctypes.c_ulong),
('CcFastReadWait', ctypes.c_ulong),
('CcFastReadResourceMiss', ctypes.c_ulong),
('CcFastReadNotPossible', ctypes.c_ulong),
('CcFastMdlReadNoWait', ctypes.c_ulong),
('CcFastMdlReadWait', ctypes.c_ulong),
('CcFastMdlReadResourceMiss', ctypes.c_ulong),
('CcFastMdlReadNotPossible', ctypes.c_ulong),
('CcMapDataNoWait', ctypes.c_ulong),
('CcMapDataWait', ctypes.c_ulong),
('CcMapDataNoWaitMiss', ctypes.c_ulong),
('CcMapDataWaitMiss', ctypes.c_ulong),
('CcPinMappedDataCount', ctypes.c_ulong),
('CcPinReadNoWait', ctypes.c_ulong),
('CcPinReadWait', ctypes.c_ulong),
('CcPinReadNoWaitMiss', ctypes.c_ulong),
('CcPinReadWaitMiss', ctypes.c_ulong),
('CcCopyReadNoWait', ctypes.c_ulong),
('CcCopyReadWait', ctypes.c_ulong),
('CcCopyReadNoWaitMiss', ctypes.c_ulong),
('CcCopyReadWaitMiss', ctypes.c_ulong),
('CcMdlReadNoWait', ctypes.c_ulong),
('CcMdlReadWait', ctypes.c_ulong),
('CcMdlReadNoWaitMiss', ctypes.c_ulong),
('CcMdlReadWaitMiss', ctypes.c_ulong),
('CcReadAheadIos', ctypes.c_ulong),
('CcLazyWriteIos', ctypes.c_ulong),
('CcLazyWritePages', ctypes.c_ulong),
('CcDataFlushes', ctypes.c_ulong),
('CcDataPages', ctypes.c_ulong),
('ContextSwitches', ctypes.c_ulong),
('FirstLevelTbFills', ctypes.c_ulong),
('SecondLevelTbFills', ctypes.c_ulong),
('SystemCalls', ctypes.c_ulong),
# Windows 8 and above
('CcTotalDirtyPages', ctypes.c_ulonglong),
('CcDirtyPagesThreshold', ctypes.c_ulonglong),
('ResidentAvailablePages', ctypes.c_longlong),
# Windows 10 and above
('SharedCommittedPages', ctypes.c_ulonglong)]
def __virtual__():
'''
Only works on Windows systems with WMI and WinAPI
'''
if not salt.utils.platform.is_windows():
return False, 'win_status.py: Requires Windows'
if not HAS_WMI:
return False, 'win_status.py: Requires WMI and WinAPI'
if not HAS_PSUTIL:
return False, 'win_status.py: Requires psutil'
# Namespace modules from `status.py`
global ping_master, time_
ping_master = _namespaced_function(ping_master, globals())
time_ = _namespaced_function(time_, globals())
return __virtualname__
__func_alias__ = {
'time_': 'time'
}
def cpustats():
'''
Return information about the CPU.
Returns
dict: A dictionary containing information about the CPU stats
CLI Example:
.. code-block:: bash
salt * status.cpustats
'''
# Tries to gather information similar to that returned by a Linux machine
# Avoid using WMI as there's a lot of overhead
# Time related info
user, system, idle, interrupt, dpc = psutil.cpu_times()
cpu = {'user': user,
'system': system,
'idle': idle,
'irq': interrupt,
'dpc': dpc}
# Count related info
ctx_switches, interrupts, soft_interrupts, sys_calls = psutil.cpu_stats()
intr = {'irqs': {'irqs': [],
'total': interrupts}}
soft_irq = {'softirqs': [],
'total': soft_interrupts}
return {'btime': psutil.boot_time(),
'cpu': cpu,
'ctxt': ctx_switches,
'intr': intr,
'processes': len(psutil.pids()),
'softirq': soft_irq,
'syscalls': sys_calls}
def meminfo():
'''
Return information about physical and virtual memory on the system
Returns:
dict: A dictionary of information about memory on the system
CLI Example:
.. code-block:: bash
salt * status.meminfo
'''
# Get physical memory
vm_total, vm_available, vm_percent, vm_used, vm_free = psutil.virtual_memory()
# Get swap memory
swp_total, swp_used, swp_free, swp_percent, _, _ = psutil.swap_memory()
def get_unit_value(memory):
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {}
for i, s in enumerate(symbols):
prefix[s] = 1 << (i + 1) * 10
for s in reversed(symbols):
if memory >= prefix[s]:
value = float(memory) / prefix[s]
return {'unit': s,
'value': value}
return {'unit': 'B',
'value': memory}
return {'VmallocTotal': get_unit_value(vm_total),
'VmallocUsed': get_unit_value(vm_used),
'VmallocFree': get_unit_value(vm_free),
'VmallocAvail': get_unit_value(vm_available),
'SwapTotal': get_unit_value(swp_total),
'SwapUsed': get_unit_value(swp_used),
'SwapFree': get_unit_value(swp_free)}
def vmstats():
'''
Return information about the virtual memory on the machine
Returns:
dict: A dictionary of virtual memory stats
CLI Example:
.. code-block:: bash
salt * status.vmstats
'''
# Setup the SPI Structure
spi = SYSTEM_PERFORMANCE_INFORMATION()
retlen = ctypes.c_ulong()
# 2 means to query System Performance Information and return it in a
# SYSTEM_PERFORMANCE_INFORMATION Structure
ctypes.windll.ntdll.NtQuerySystemInformation(
2, ctypes.byref(spi), ctypes.sizeof(spi), ctypes.byref(retlen))
# Return each defined field in a dict
ret = {}
for field in spi._fields_:
ret.update({field[0]: getattr(spi, field[0])})
return ret
def loadavg():
'''
Returns counter information related to the load of the machine
Returns:
dict: A dictionary of counters
CLI Example:
.. code-block:: bash
salt * status.loadavg
'''
# Counter List (obj, instance, counter)
counter_list = [
('Memory', None, 'Available Bytes'),
('Memory', None, 'Pages/sec'),
('Paging File', '*', '% Usage'),
('Processor', '*', '% Processor Time'),
('Processor', '*', 'DPCs Queued/sec'),
('Processor', '*', '% Privileged Time'),
('Processor', '*', '% User Time'),
('Processor', '*', '% DPC Time'),
('Processor', '*', '% Interrupt Time'),
('Server', None, 'Work Item Shortages'),
('Server Work Queues', '*', 'Queue Length'),
('System', None, 'Processor Queue Length'),
('System', None, 'Context Switches/sec'),
]
return salt.utils.win_pdh.get_counters(counter_list=counter_list)
def cpuload():
'''
.. versionadded:: 2015.8.0
Return the processor load as a percentage
CLI Example:
.. code-block:: bash
salt '*' status.cpuload
'''
return psutil.cpu_percent()
def diskusage(human_readable=False, path=None):
'''
.. versionadded:: 2015.8.0
Return the disk usage for this minion
human_readable : False
If ``True``, usage will be in KB/MB/GB etc.
CLI Example:
.. code-block:: bash
salt '*' status.diskusage path=c:/salt
'''
if not path:
path = 'c:/'
disk_stats = psutil.disk_usage(path)
total_val = disk_stats.total
used_val = disk_stats.used
free_val = disk_stats.free
percent = disk_stats.percent
if human_readable:
total_val = _byte_calc(total_val)
used_val = _byte_calc(used_val)
free_val = _byte_calc(free_val)
return {'total': total_val,
'used': used_val,
'free': free_val,
'percent': percent}
def procs(count=False):
'''
Return the process data
count : False
If ``True``, this function will simply return the number of processes.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' status.procs
salt '*' status.procs count
'''
with salt.utils.winapi.Com():
wmi_obj = wmi.WMI()
processes = wmi_obj.win32_process()
#this short circuit's the function to get a short simple proc count.
if count:
return len(processes)
#a propper run of the function, creating a nonsensically long out put.
process_info = {}
for proc in processes:
process_info[proc.ProcessId] = _get_process_info(proc)
return process_info
def uptime(human_readable=False):
'''
.. versionadded:: 2015.8.0
Return the system uptime for the machine
Args:
human_readable (bool):
Return uptime in human readable format if ``True``, otherwise
return seconds. Default is ``False``
.. note::
Human readable format is ``days, hours:min:sec``. Days will only
be displayed if more than 0
Returns:
str:
The uptime in seconds or human readable format depending on the
value of ``human_readable``
CLI Example:
.. code-block:: bash
salt '*' status.uptime
salt '*' status.uptime human_readable=True
'''
# Get startup time
startup_time = datetime.datetime.fromtimestamp(psutil.boot_time())
# Subtract startup time from current time to get the uptime of the system
uptime = datetime.datetime.now() - startup_time
return six.text_type(uptime) if human_readable else uptime.total_seconds()
def _get_process_info(proc):
'''
Return process information
'''
cmd = salt.utils.stringutils.to_unicode(proc.CommandLine or '')
name = salt.utils.stringutils.to_unicode(proc.Name)
info = dict(
cmd=cmd,
name=name,
**_get_process_owner(proc)
)
return info
def _get_process_owner(process):
owner = {}
domain, error_code, user = None, None, None
try:
domain, error_code, user = process.GetOwner()
owner['user'] = salt.utils.stringutils.to_unicode(user)
owner['user_domain'] = salt.utils.stringutils.to_unicode(domain)
except Exception as exc:
pass
if not error_code and all((user, domain)):
owner['user'] = salt.utils.stringutils.to_unicode(user)
owner['user_domain'] = salt.utils.stringutils.to_unicode(domain)
elif process.ProcessId in [0, 4] and error_code == 2:
# Access Denied for System Idle Process and System
owner['user'] = 'SYSTEM'
owner['user_domain'] = 'NT AUTHORITY'
else:
log.warning('Error getting owner of process; PID=\'%s\'; Error: %s',
process.ProcessId, error_code)
return owner
def _byte_calc(val):
if val < 1024:
tstr = six.text_type(val)+'B'
elif val < 1038336:
tstr = six.text_type(val/1024)+'KB'
elif val < 1073741824:
tstr = six.text_type(val/1038336)+'MB'
elif val < 1099511627776:
tstr = six.text_type(val/1073741824)+'GB'
else:
tstr = six.text_type(val/1099511627776)+'TB'
return tstr
def master(master=None, connected=True):
'''
.. versionadded:: 2015.5.0
Fire an event if the minion gets disconnected from its master. This
function is meant to be run via a scheduled job from the minion. If
master_ip is an FQDN/Hostname, is must be resolvable to a valid IPv4
address.
CLI Example:
.. code-block:: bash
salt '*' status.master
'''
def _win_remotes_on(port):
'''
Windows specific helper function.
Returns set of ipv4 host addresses of remote established connections
on local or remote tcp port.
Parses output of shell 'netstat' to get connections
PS C:> netstat -n -p TCP
Active Connections
Proto Local Address Foreign Address State
TCP 10.1.1.26:3389 10.1.1.1:4505 ESTABLISHED
TCP 10.1.1.26:56862 10.1.1.10:49155 TIME_WAIT
TCP 10.1.1.26:56868 169.254.169.254:80 CLOSE_WAIT
TCP 127.0.0.1:49197 127.0.0.1:49198 ESTABLISHED
TCP 127.0.0.1:49198 127.0.0.1:49197 ESTABLISHED
'''
remotes = set()
try:
data = subprocess.check_output(['netstat', '-n', '-p', 'TCP']) # pylint: disable=minimum-python-version
except subprocess.CalledProcessError:
log.error('Failed netstat')
raise
lines = salt.utils.stringutils.to_unicode(data).split('\n')
for line in lines:
if 'ESTABLISHED' not in line:
continue
chunks = line.split()
remote_host, remote_port = chunks[2].rsplit(':', 1)
if int(remote_port) != port:
continue
remotes.add(remote_host)
return remotes
# the default publishing port
port = 4505
master_ips = None
if master:
master_ips = _host_to_ips(master)
if not master_ips:
return
if __salt__['config.get']('publish_port') != '':
port = int(__salt__['config.get']('publish_port'))
master_connection_status = False
connected_ips = _win_remotes_on(port)
# Get connection status for master
for master_ip in master_ips:
if master_ip in connected_ips:
master_connection_status = True
break
# Connection to master is not as expected
if master_connection_status is not connected:
event = salt.utils.event.get_event('minion', opts=__opts__, listen=False)
if master_connection_status:
event.fire_event({'master': master}, salt.minion.master_event(type='connected'))
else:
event.fire_event({'master': master}, salt.minion.master_event(type='disconnected'))
return master_connection_status
|
saltstack/salt
|
salt/modules/win_status.py
|
uptime
|
python
|
def uptime(human_readable=False):
'''
.. versionadded:: 2015.8.0
Return the system uptime for the machine
Args:
human_readable (bool):
Return uptime in human readable format if ``True``, otherwise
return seconds. Default is ``False``
.. note::
Human readable format is ``days, hours:min:sec``. Days will only
be displayed if more than 0
Returns:
str:
The uptime in seconds or human readable format depending on the
value of ``human_readable``
CLI Example:
.. code-block:: bash
salt '*' status.uptime
salt '*' status.uptime human_readable=True
'''
# Get startup time
startup_time = datetime.datetime.fromtimestamp(psutil.boot_time())
# Subtract startup time from current time to get the uptime of the system
uptime = datetime.datetime.now() - startup_time
return six.text_type(uptime) if human_readable else uptime.total_seconds()
|
.. versionadded:: 2015.8.0
Return the system uptime for the machine
Args:
human_readable (bool):
Return uptime in human readable format if ``True``, otherwise
return seconds. Default is ``False``
.. note::
Human readable format is ``days, hours:min:sec``. Days will only
be displayed if more than 0
Returns:
str:
The uptime in seconds or human readable format depending on the
value of ``human_readable``
CLI Example:
.. code-block:: bash
salt '*' status.uptime
salt '*' status.uptime human_readable=True
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_status.py#L419-L453
| null |
# -*- coding: utf-8 -*-
'''
Module for returning various status data about a minion.
These data can be useful for compiling into stats later,
or for problem solving if your minion is having problems.
.. versionadded:: 0.12.0
:depends: - wmi
'''
# Import Python Libs
from __future__ import absolute_import, unicode_literals, print_function
import ctypes
import datetime
import logging
import subprocess
log = logging.getLogger(__name__)
# Import Salt Libs
import salt.utils.event
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.win_pdh
from salt.utils.network import host_to_ips as _host_to_ips
from salt.utils.functools import namespaced_function as _namespaced_function
# Import 3rd party Libs
from salt.ext import six
# These imports needed for namespaced functions
# pylint: disable=W0611
from salt.modules.status import ping_master, time_
import copy
# pylint: enable=W0611
# Import 3rd Party Libs
try:
if salt.utils.platform.is_windows():
import wmi
import salt.utils.winapi
HAS_WMI = True
else:
HAS_WMI = False
except ImportError:
HAS_WMI = False
HAS_PSUTIL = False
if salt.utils.platform.is_windows():
import psutil
HAS_PSUTIL = True
__opts__ = {}
__virtualname__ = 'status'
# Taken from https://www.geoffchappell.com/studies/windows/km/ntoskrnl/api/ex/sysinfo/performance.htm
class SYSTEM_PERFORMANCE_INFORMATION(ctypes.Structure):
_fields_ = [('IdleProcessTime', ctypes.c_int64),
('IoReadTransferCount', ctypes.c_int64),
('IoWriteTransferCount', ctypes.c_int64),
('IoOtherTransferCount', ctypes.c_int64),
('IoReadOperationCount', ctypes.c_ulong),
('IoWriteOperationCount', ctypes.c_ulong),
('IoOtherOperationCount', ctypes.c_ulong),
('AvailablePages', ctypes.c_ulong),
('CommittedPages', ctypes.c_ulong),
('CommitLimit', ctypes.c_ulong),
('PeakCommitment', ctypes.c_ulong),
('PageFaultCount', ctypes.c_ulong),
('CopyOnWriteCount', ctypes.c_ulong),
('TransitionCount', ctypes.c_ulong),
('CacheTransitionCount', ctypes.c_ulong),
('DemandZeroCount', ctypes.c_ulong),
('PageReadCount', ctypes.c_ulong),
('PageReadIoCount', ctypes.c_ulong),
('CacheReadCount', ctypes.c_ulong), # Was c_ulong ** 2
('CacheIoCount', ctypes.c_ulong),
('DirtyPagesWriteCount', ctypes.c_ulong),
('DirtyWriteIoCount', ctypes.c_ulong),
('MappedPagesWriteCount', ctypes.c_ulong),
('MappedWriteIoCount', ctypes.c_ulong),
('PagedPoolPages', ctypes.c_ulong),
('NonPagedPoolPages', ctypes.c_ulong),
('PagedPoolAllocs', ctypes.c_ulong),
('PagedPoolFrees', ctypes.c_ulong),
('NonPagedPoolAllocs', ctypes.c_ulong),
('NonPagedPoolFrees', ctypes.c_ulong),
('FreeSystemPtes', ctypes.c_ulong),
('ResidentSystemCodePage', ctypes.c_ulong),
('TotalSystemDriverPages', ctypes.c_ulong),
('TotalSystemCodePages', ctypes.c_ulong),
('NonPagedPoolLookasideHits', ctypes.c_ulong),
('PagedPoolLookasideHits', ctypes.c_ulong),
('AvailablePagedPoolPages', ctypes.c_ulong),
('ResidentSystemCachePage', ctypes.c_ulong),
('ResidentPagedPoolPage', ctypes.c_ulong),
('ResidentSystemDriverPage', ctypes.c_ulong),
('CcFastReadNoWait', ctypes.c_ulong),
('CcFastReadWait', ctypes.c_ulong),
('CcFastReadResourceMiss', ctypes.c_ulong),
('CcFastReadNotPossible', ctypes.c_ulong),
('CcFastMdlReadNoWait', ctypes.c_ulong),
('CcFastMdlReadWait', ctypes.c_ulong),
('CcFastMdlReadResourceMiss', ctypes.c_ulong),
('CcFastMdlReadNotPossible', ctypes.c_ulong),
('CcMapDataNoWait', ctypes.c_ulong),
('CcMapDataWait', ctypes.c_ulong),
('CcMapDataNoWaitMiss', ctypes.c_ulong),
('CcMapDataWaitMiss', ctypes.c_ulong),
('CcPinMappedDataCount', ctypes.c_ulong),
('CcPinReadNoWait', ctypes.c_ulong),
('CcPinReadWait', ctypes.c_ulong),
('CcPinReadNoWaitMiss', ctypes.c_ulong),
('CcPinReadWaitMiss', ctypes.c_ulong),
('CcCopyReadNoWait', ctypes.c_ulong),
('CcCopyReadWait', ctypes.c_ulong),
('CcCopyReadNoWaitMiss', ctypes.c_ulong),
('CcCopyReadWaitMiss', ctypes.c_ulong),
('CcMdlReadNoWait', ctypes.c_ulong),
('CcMdlReadWait', ctypes.c_ulong),
('CcMdlReadNoWaitMiss', ctypes.c_ulong),
('CcMdlReadWaitMiss', ctypes.c_ulong),
('CcReadAheadIos', ctypes.c_ulong),
('CcLazyWriteIos', ctypes.c_ulong),
('CcLazyWritePages', ctypes.c_ulong),
('CcDataFlushes', ctypes.c_ulong),
('CcDataPages', ctypes.c_ulong),
('ContextSwitches', ctypes.c_ulong),
('FirstLevelTbFills', ctypes.c_ulong),
('SecondLevelTbFills', ctypes.c_ulong),
('SystemCalls', ctypes.c_ulong),
# Windows 8 and above
('CcTotalDirtyPages', ctypes.c_ulonglong),
('CcDirtyPagesThreshold', ctypes.c_ulonglong),
('ResidentAvailablePages', ctypes.c_longlong),
# Windows 10 and above
('SharedCommittedPages', ctypes.c_ulonglong)]
def __virtual__():
'''
Only works on Windows systems with WMI and WinAPI
'''
if not salt.utils.platform.is_windows():
return False, 'win_status.py: Requires Windows'
if not HAS_WMI:
return False, 'win_status.py: Requires WMI and WinAPI'
if not HAS_PSUTIL:
return False, 'win_status.py: Requires psutil'
# Namespace modules from `status.py`
global ping_master, time_
ping_master = _namespaced_function(ping_master, globals())
time_ = _namespaced_function(time_, globals())
return __virtualname__
__func_alias__ = {
'time_': 'time'
}
def cpustats():
'''
Return information about the CPU.
Returns
dict: A dictionary containing information about the CPU stats
CLI Example:
.. code-block:: bash
salt * status.cpustats
'''
# Tries to gather information similar to that returned by a Linux machine
# Avoid using WMI as there's a lot of overhead
# Time related info
user, system, idle, interrupt, dpc = psutil.cpu_times()
cpu = {'user': user,
'system': system,
'idle': idle,
'irq': interrupt,
'dpc': dpc}
# Count related info
ctx_switches, interrupts, soft_interrupts, sys_calls = psutil.cpu_stats()
intr = {'irqs': {'irqs': [],
'total': interrupts}}
soft_irq = {'softirqs': [],
'total': soft_interrupts}
return {'btime': psutil.boot_time(),
'cpu': cpu,
'ctxt': ctx_switches,
'intr': intr,
'processes': len(psutil.pids()),
'softirq': soft_irq,
'syscalls': sys_calls}
def meminfo():
'''
Return information about physical and virtual memory on the system
Returns:
dict: A dictionary of information about memory on the system
CLI Example:
.. code-block:: bash
salt * status.meminfo
'''
# Get physical memory
vm_total, vm_available, vm_percent, vm_used, vm_free = psutil.virtual_memory()
# Get swap memory
swp_total, swp_used, swp_free, swp_percent, _, _ = psutil.swap_memory()
def get_unit_value(memory):
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {}
for i, s in enumerate(symbols):
prefix[s] = 1 << (i + 1) * 10
for s in reversed(symbols):
if memory >= prefix[s]:
value = float(memory) / prefix[s]
return {'unit': s,
'value': value}
return {'unit': 'B',
'value': memory}
return {'VmallocTotal': get_unit_value(vm_total),
'VmallocUsed': get_unit_value(vm_used),
'VmallocFree': get_unit_value(vm_free),
'VmallocAvail': get_unit_value(vm_available),
'SwapTotal': get_unit_value(swp_total),
'SwapUsed': get_unit_value(swp_used),
'SwapFree': get_unit_value(swp_free)}
def vmstats():
'''
Return information about the virtual memory on the machine
Returns:
dict: A dictionary of virtual memory stats
CLI Example:
.. code-block:: bash
salt * status.vmstats
'''
# Setup the SPI Structure
spi = SYSTEM_PERFORMANCE_INFORMATION()
retlen = ctypes.c_ulong()
# 2 means to query System Performance Information and return it in a
# SYSTEM_PERFORMANCE_INFORMATION Structure
ctypes.windll.ntdll.NtQuerySystemInformation(
2, ctypes.byref(spi), ctypes.sizeof(spi), ctypes.byref(retlen))
# Return each defined field in a dict
ret = {}
for field in spi._fields_:
ret.update({field[0]: getattr(spi, field[0])})
return ret
def loadavg():
'''
Returns counter information related to the load of the machine
Returns:
dict: A dictionary of counters
CLI Example:
.. code-block:: bash
salt * status.loadavg
'''
# Counter List (obj, instance, counter)
counter_list = [
('Memory', None, 'Available Bytes'),
('Memory', None, 'Pages/sec'),
('Paging File', '*', '% Usage'),
('Processor', '*', '% Processor Time'),
('Processor', '*', 'DPCs Queued/sec'),
('Processor', '*', '% Privileged Time'),
('Processor', '*', '% User Time'),
('Processor', '*', '% DPC Time'),
('Processor', '*', '% Interrupt Time'),
('Server', None, 'Work Item Shortages'),
('Server Work Queues', '*', 'Queue Length'),
('System', None, 'Processor Queue Length'),
('System', None, 'Context Switches/sec'),
]
return salt.utils.win_pdh.get_counters(counter_list=counter_list)
def cpuload():
'''
.. versionadded:: 2015.8.0
Return the processor load as a percentage
CLI Example:
.. code-block:: bash
salt '*' status.cpuload
'''
return psutil.cpu_percent()
def diskusage(human_readable=False, path=None):
'''
.. versionadded:: 2015.8.0
Return the disk usage for this minion
human_readable : False
If ``True``, usage will be in KB/MB/GB etc.
CLI Example:
.. code-block:: bash
salt '*' status.diskusage path=c:/salt
'''
if not path:
path = 'c:/'
disk_stats = psutil.disk_usage(path)
total_val = disk_stats.total
used_val = disk_stats.used
free_val = disk_stats.free
percent = disk_stats.percent
if human_readable:
total_val = _byte_calc(total_val)
used_val = _byte_calc(used_val)
free_val = _byte_calc(free_val)
return {'total': total_val,
'used': used_val,
'free': free_val,
'percent': percent}
def procs(count=False):
'''
Return the process data
count : False
If ``True``, this function will simply return the number of processes.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' status.procs
salt '*' status.procs count
'''
with salt.utils.winapi.Com():
wmi_obj = wmi.WMI()
processes = wmi_obj.win32_process()
#this short circuit's the function to get a short simple proc count.
if count:
return len(processes)
#a propper run of the function, creating a nonsensically long out put.
process_info = {}
for proc in processes:
process_info[proc.ProcessId] = _get_process_info(proc)
return process_info
def saltmem(human_readable=False):
'''
.. versionadded:: 2015.8.0
Returns the amount of memory that salt is using
human_readable : False
return the value in a nicely formatted number
CLI Example:
.. code-block:: bash
salt '*' status.saltmem
salt '*' status.saltmem human_readable=True
'''
# psutil.Process defaults to current process (`os.getpid()`)
p = psutil.Process()
# Use oneshot to get a snapshot
with p.oneshot():
mem = p.memory_info().rss
if human_readable:
return _byte_calc(mem)
return mem
def _get_process_info(proc):
'''
Return process information
'''
cmd = salt.utils.stringutils.to_unicode(proc.CommandLine or '')
name = salt.utils.stringutils.to_unicode(proc.Name)
info = dict(
cmd=cmd,
name=name,
**_get_process_owner(proc)
)
return info
def _get_process_owner(process):
owner = {}
domain, error_code, user = None, None, None
try:
domain, error_code, user = process.GetOwner()
owner['user'] = salt.utils.stringutils.to_unicode(user)
owner['user_domain'] = salt.utils.stringutils.to_unicode(domain)
except Exception as exc:
pass
if not error_code and all((user, domain)):
owner['user'] = salt.utils.stringutils.to_unicode(user)
owner['user_domain'] = salt.utils.stringutils.to_unicode(domain)
elif process.ProcessId in [0, 4] and error_code == 2:
# Access Denied for System Idle Process and System
owner['user'] = 'SYSTEM'
owner['user_domain'] = 'NT AUTHORITY'
else:
log.warning('Error getting owner of process; PID=\'%s\'; Error: %s',
process.ProcessId, error_code)
return owner
def _byte_calc(val):
if val < 1024:
tstr = six.text_type(val)+'B'
elif val < 1038336:
tstr = six.text_type(val/1024)+'KB'
elif val < 1073741824:
tstr = six.text_type(val/1038336)+'MB'
elif val < 1099511627776:
tstr = six.text_type(val/1073741824)+'GB'
else:
tstr = six.text_type(val/1099511627776)+'TB'
return tstr
def master(master=None, connected=True):
'''
.. versionadded:: 2015.5.0
Fire an event if the minion gets disconnected from its master. This
function is meant to be run via a scheduled job from the minion. If
master_ip is an FQDN/Hostname, is must be resolvable to a valid IPv4
address.
CLI Example:
.. code-block:: bash
salt '*' status.master
'''
def _win_remotes_on(port):
'''
Windows specific helper function.
Returns set of ipv4 host addresses of remote established connections
on local or remote tcp port.
Parses output of shell 'netstat' to get connections
PS C:> netstat -n -p TCP
Active Connections
Proto Local Address Foreign Address State
TCP 10.1.1.26:3389 10.1.1.1:4505 ESTABLISHED
TCP 10.1.1.26:56862 10.1.1.10:49155 TIME_WAIT
TCP 10.1.1.26:56868 169.254.169.254:80 CLOSE_WAIT
TCP 127.0.0.1:49197 127.0.0.1:49198 ESTABLISHED
TCP 127.0.0.1:49198 127.0.0.1:49197 ESTABLISHED
'''
remotes = set()
try:
data = subprocess.check_output(['netstat', '-n', '-p', 'TCP']) # pylint: disable=minimum-python-version
except subprocess.CalledProcessError:
log.error('Failed netstat')
raise
lines = salt.utils.stringutils.to_unicode(data).split('\n')
for line in lines:
if 'ESTABLISHED' not in line:
continue
chunks = line.split()
remote_host, remote_port = chunks[2].rsplit(':', 1)
if int(remote_port) != port:
continue
remotes.add(remote_host)
return remotes
# the default publishing port
port = 4505
master_ips = None
if master:
master_ips = _host_to_ips(master)
if not master_ips:
return
if __salt__['config.get']('publish_port') != '':
port = int(__salt__['config.get']('publish_port'))
master_connection_status = False
connected_ips = _win_remotes_on(port)
# Get connection status for master
for master_ip in master_ips:
if master_ip in connected_ips:
master_connection_status = True
break
# Connection to master is not as expected
if master_connection_status is not connected:
event = salt.utils.event.get_event('minion', opts=__opts__, listen=False)
if master_connection_status:
event.fire_event({'master': master}, salt.minion.master_event(type='connected'))
else:
event.fire_event({'master': master}, salt.minion.master_event(type='disconnected'))
return master_connection_status
|
saltstack/salt
|
salt/modules/win_status.py
|
_get_process_info
|
python
|
def _get_process_info(proc):
'''
Return process information
'''
cmd = salt.utils.stringutils.to_unicode(proc.CommandLine or '')
name = salt.utils.stringutils.to_unicode(proc.Name)
info = dict(
cmd=cmd,
name=name,
**_get_process_owner(proc)
)
return info
|
Return process information
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_status.py#L456-L467
|
[
"def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n",
"def _get_process_owner(process):\n owner = {}\n domain, error_code, user = None, None, None\n try:\n domain, error_code, user = process.GetOwner()\n owner['user'] = salt.utils.stringutils.to_unicode(user)\n owner['user_domain'] = salt.utils.stringutils.to_unicode(domain)\n except Exception as exc:\n pass\n if not error_code and all((user, domain)):\n owner['user'] = salt.utils.stringutils.to_unicode(user)\n owner['user_domain'] = salt.utils.stringutils.to_unicode(domain)\n elif process.ProcessId in [0, 4] and error_code == 2:\n # Access Denied for System Idle Process and System\n owner['user'] = 'SYSTEM'\n owner['user_domain'] = 'NT AUTHORITY'\n else:\n log.warning('Error getting owner of process; PID=\\'%s\\'; Error: %s',\n process.ProcessId, error_code)\n return owner\n"
] |
# -*- coding: utf-8 -*-
'''
Module for returning various status data about a minion.
These data can be useful for compiling into stats later,
or for problem solving if your minion is having problems.
.. versionadded:: 0.12.0
:depends: - wmi
'''
# Import Python Libs
from __future__ import absolute_import, unicode_literals, print_function
import ctypes
import datetime
import logging
import subprocess
log = logging.getLogger(__name__)
# Import Salt Libs
import salt.utils.event
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.win_pdh
from salt.utils.network import host_to_ips as _host_to_ips
from salt.utils.functools import namespaced_function as _namespaced_function
# Import 3rd party Libs
from salt.ext import six
# These imports needed for namespaced functions
# pylint: disable=W0611
from salt.modules.status import ping_master, time_
import copy
# pylint: enable=W0611
# Import 3rd Party Libs
try:
if salt.utils.platform.is_windows():
import wmi
import salt.utils.winapi
HAS_WMI = True
else:
HAS_WMI = False
except ImportError:
HAS_WMI = False
HAS_PSUTIL = False
if salt.utils.platform.is_windows():
import psutil
HAS_PSUTIL = True
__opts__ = {}
__virtualname__ = 'status'
# Taken from https://www.geoffchappell.com/studies/windows/km/ntoskrnl/api/ex/sysinfo/performance.htm
class SYSTEM_PERFORMANCE_INFORMATION(ctypes.Structure):
_fields_ = [('IdleProcessTime', ctypes.c_int64),
('IoReadTransferCount', ctypes.c_int64),
('IoWriteTransferCount', ctypes.c_int64),
('IoOtherTransferCount', ctypes.c_int64),
('IoReadOperationCount', ctypes.c_ulong),
('IoWriteOperationCount', ctypes.c_ulong),
('IoOtherOperationCount', ctypes.c_ulong),
('AvailablePages', ctypes.c_ulong),
('CommittedPages', ctypes.c_ulong),
('CommitLimit', ctypes.c_ulong),
('PeakCommitment', ctypes.c_ulong),
('PageFaultCount', ctypes.c_ulong),
('CopyOnWriteCount', ctypes.c_ulong),
('TransitionCount', ctypes.c_ulong),
('CacheTransitionCount', ctypes.c_ulong),
('DemandZeroCount', ctypes.c_ulong),
('PageReadCount', ctypes.c_ulong),
('PageReadIoCount', ctypes.c_ulong),
('CacheReadCount', ctypes.c_ulong), # Was c_ulong ** 2
('CacheIoCount', ctypes.c_ulong),
('DirtyPagesWriteCount', ctypes.c_ulong),
('DirtyWriteIoCount', ctypes.c_ulong),
('MappedPagesWriteCount', ctypes.c_ulong),
('MappedWriteIoCount', ctypes.c_ulong),
('PagedPoolPages', ctypes.c_ulong),
('NonPagedPoolPages', ctypes.c_ulong),
('PagedPoolAllocs', ctypes.c_ulong),
('PagedPoolFrees', ctypes.c_ulong),
('NonPagedPoolAllocs', ctypes.c_ulong),
('NonPagedPoolFrees', ctypes.c_ulong),
('FreeSystemPtes', ctypes.c_ulong),
('ResidentSystemCodePage', ctypes.c_ulong),
('TotalSystemDriverPages', ctypes.c_ulong),
('TotalSystemCodePages', ctypes.c_ulong),
('NonPagedPoolLookasideHits', ctypes.c_ulong),
('PagedPoolLookasideHits', ctypes.c_ulong),
('AvailablePagedPoolPages', ctypes.c_ulong),
('ResidentSystemCachePage', ctypes.c_ulong),
('ResidentPagedPoolPage', ctypes.c_ulong),
('ResidentSystemDriverPage', ctypes.c_ulong),
('CcFastReadNoWait', ctypes.c_ulong),
('CcFastReadWait', ctypes.c_ulong),
('CcFastReadResourceMiss', ctypes.c_ulong),
('CcFastReadNotPossible', ctypes.c_ulong),
('CcFastMdlReadNoWait', ctypes.c_ulong),
('CcFastMdlReadWait', ctypes.c_ulong),
('CcFastMdlReadResourceMiss', ctypes.c_ulong),
('CcFastMdlReadNotPossible', ctypes.c_ulong),
('CcMapDataNoWait', ctypes.c_ulong),
('CcMapDataWait', ctypes.c_ulong),
('CcMapDataNoWaitMiss', ctypes.c_ulong),
('CcMapDataWaitMiss', ctypes.c_ulong),
('CcPinMappedDataCount', ctypes.c_ulong),
('CcPinReadNoWait', ctypes.c_ulong),
('CcPinReadWait', ctypes.c_ulong),
('CcPinReadNoWaitMiss', ctypes.c_ulong),
('CcPinReadWaitMiss', ctypes.c_ulong),
('CcCopyReadNoWait', ctypes.c_ulong),
('CcCopyReadWait', ctypes.c_ulong),
('CcCopyReadNoWaitMiss', ctypes.c_ulong),
('CcCopyReadWaitMiss', ctypes.c_ulong),
('CcMdlReadNoWait', ctypes.c_ulong),
('CcMdlReadWait', ctypes.c_ulong),
('CcMdlReadNoWaitMiss', ctypes.c_ulong),
('CcMdlReadWaitMiss', ctypes.c_ulong),
('CcReadAheadIos', ctypes.c_ulong),
('CcLazyWriteIos', ctypes.c_ulong),
('CcLazyWritePages', ctypes.c_ulong),
('CcDataFlushes', ctypes.c_ulong),
('CcDataPages', ctypes.c_ulong),
('ContextSwitches', ctypes.c_ulong),
('FirstLevelTbFills', ctypes.c_ulong),
('SecondLevelTbFills', ctypes.c_ulong),
('SystemCalls', ctypes.c_ulong),
# Windows 8 and above
('CcTotalDirtyPages', ctypes.c_ulonglong),
('CcDirtyPagesThreshold', ctypes.c_ulonglong),
('ResidentAvailablePages', ctypes.c_longlong),
# Windows 10 and above
('SharedCommittedPages', ctypes.c_ulonglong)]
def __virtual__():
'''
Only works on Windows systems with WMI and WinAPI
'''
if not salt.utils.platform.is_windows():
return False, 'win_status.py: Requires Windows'
if not HAS_WMI:
return False, 'win_status.py: Requires WMI and WinAPI'
if not HAS_PSUTIL:
return False, 'win_status.py: Requires psutil'
# Namespace modules from `status.py`
global ping_master, time_
ping_master = _namespaced_function(ping_master, globals())
time_ = _namespaced_function(time_, globals())
return __virtualname__
__func_alias__ = {
'time_': 'time'
}
def cpustats():
'''
Return information about the CPU.
Returns
dict: A dictionary containing information about the CPU stats
CLI Example:
.. code-block:: bash
salt * status.cpustats
'''
# Tries to gather information similar to that returned by a Linux machine
# Avoid using WMI as there's a lot of overhead
# Time related info
user, system, idle, interrupt, dpc = psutil.cpu_times()
cpu = {'user': user,
'system': system,
'idle': idle,
'irq': interrupt,
'dpc': dpc}
# Count related info
ctx_switches, interrupts, soft_interrupts, sys_calls = psutil.cpu_stats()
intr = {'irqs': {'irqs': [],
'total': interrupts}}
soft_irq = {'softirqs': [],
'total': soft_interrupts}
return {'btime': psutil.boot_time(),
'cpu': cpu,
'ctxt': ctx_switches,
'intr': intr,
'processes': len(psutil.pids()),
'softirq': soft_irq,
'syscalls': sys_calls}
def meminfo():
'''
Return information about physical and virtual memory on the system
Returns:
dict: A dictionary of information about memory on the system
CLI Example:
.. code-block:: bash
salt * status.meminfo
'''
# Get physical memory
vm_total, vm_available, vm_percent, vm_used, vm_free = psutil.virtual_memory()
# Get swap memory
swp_total, swp_used, swp_free, swp_percent, _, _ = psutil.swap_memory()
def get_unit_value(memory):
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {}
for i, s in enumerate(symbols):
prefix[s] = 1 << (i + 1) * 10
for s in reversed(symbols):
if memory >= prefix[s]:
value = float(memory) / prefix[s]
return {'unit': s,
'value': value}
return {'unit': 'B',
'value': memory}
return {'VmallocTotal': get_unit_value(vm_total),
'VmallocUsed': get_unit_value(vm_used),
'VmallocFree': get_unit_value(vm_free),
'VmallocAvail': get_unit_value(vm_available),
'SwapTotal': get_unit_value(swp_total),
'SwapUsed': get_unit_value(swp_used),
'SwapFree': get_unit_value(swp_free)}
def vmstats():
'''
Return information about the virtual memory on the machine
Returns:
dict: A dictionary of virtual memory stats
CLI Example:
.. code-block:: bash
salt * status.vmstats
'''
# Setup the SPI Structure
spi = SYSTEM_PERFORMANCE_INFORMATION()
retlen = ctypes.c_ulong()
# 2 means to query System Performance Information and return it in a
# SYSTEM_PERFORMANCE_INFORMATION Structure
ctypes.windll.ntdll.NtQuerySystemInformation(
2, ctypes.byref(spi), ctypes.sizeof(spi), ctypes.byref(retlen))
# Return each defined field in a dict
ret = {}
for field in spi._fields_:
ret.update({field[0]: getattr(spi, field[0])})
return ret
def loadavg():
'''
Returns counter information related to the load of the machine
Returns:
dict: A dictionary of counters
CLI Example:
.. code-block:: bash
salt * status.loadavg
'''
# Counter List (obj, instance, counter)
counter_list = [
('Memory', None, 'Available Bytes'),
('Memory', None, 'Pages/sec'),
('Paging File', '*', '% Usage'),
('Processor', '*', '% Processor Time'),
('Processor', '*', 'DPCs Queued/sec'),
('Processor', '*', '% Privileged Time'),
('Processor', '*', '% User Time'),
('Processor', '*', '% DPC Time'),
('Processor', '*', '% Interrupt Time'),
('Server', None, 'Work Item Shortages'),
('Server Work Queues', '*', 'Queue Length'),
('System', None, 'Processor Queue Length'),
('System', None, 'Context Switches/sec'),
]
return salt.utils.win_pdh.get_counters(counter_list=counter_list)
def cpuload():
'''
.. versionadded:: 2015.8.0
Return the processor load as a percentage
CLI Example:
.. code-block:: bash
salt '*' status.cpuload
'''
return psutil.cpu_percent()
def diskusage(human_readable=False, path=None):
'''
.. versionadded:: 2015.8.0
Return the disk usage for this minion
human_readable : False
If ``True``, usage will be in KB/MB/GB etc.
CLI Example:
.. code-block:: bash
salt '*' status.diskusage path=c:/salt
'''
if not path:
path = 'c:/'
disk_stats = psutil.disk_usage(path)
total_val = disk_stats.total
used_val = disk_stats.used
free_val = disk_stats.free
percent = disk_stats.percent
if human_readable:
total_val = _byte_calc(total_val)
used_val = _byte_calc(used_val)
free_val = _byte_calc(free_val)
return {'total': total_val,
'used': used_val,
'free': free_val,
'percent': percent}
def procs(count=False):
'''
Return the process data
count : False
If ``True``, this function will simply return the number of processes.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' status.procs
salt '*' status.procs count
'''
with salt.utils.winapi.Com():
wmi_obj = wmi.WMI()
processes = wmi_obj.win32_process()
#this short circuit's the function to get a short simple proc count.
if count:
return len(processes)
#a propper run of the function, creating a nonsensically long out put.
process_info = {}
for proc in processes:
process_info[proc.ProcessId] = _get_process_info(proc)
return process_info
def saltmem(human_readable=False):
'''
.. versionadded:: 2015.8.0
Returns the amount of memory that salt is using
human_readable : False
return the value in a nicely formatted number
CLI Example:
.. code-block:: bash
salt '*' status.saltmem
salt '*' status.saltmem human_readable=True
'''
# psutil.Process defaults to current process (`os.getpid()`)
p = psutil.Process()
# Use oneshot to get a snapshot
with p.oneshot():
mem = p.memory_info().rss
if human_readable:
return _byte_calc(mem)
return mem
def uptime(human_readable=False):
'''
.. versionadded:: 2015.8.0
Return the system uptime for the machine
Args:
human_readable (bool):
Return uptime in human readable format if ``True``, otherwise
return seconds. Default is ``False``
.. note::
Human readable format is ``days, hours:min:sec``. Days will only
be displayed if more than 0
Returns:
str:
The uptime in seconds or human readable format depending on the
value of ``human_readable``
CLI Example:
.. code-block:: bash
salt '*' status.uptime
salt '*' status.uptime human_readable=True
'''
# Get startup time
startup_time = datetime.datetime.fromtimestamp(psutil.boot_time())
# Subtract startup time from current time to get the uptime of the system
uptime = datetime.datetime.now() - startup_time
return six.text_type(uptime) if human_readable else uptime.total_seconds()
def _get_process_owner(process):
owner = {}
domain, error_code, user = None, None, None
try:
domain, error_code, user = process.GetOwner()
owner['user'] = salt.utils.stringutils.to_unicode(user)
owner['user_domain'] = salt.utils.stringutils.to_unicode(domain)
except Exception as exc:
pass
if not error_code and all((user, domain)):
owner['user'] = salt.utils.stringutils.to_unicode(user)
owner['user_domain'] = salt.utils.stringutils.to_unicode(domain)
elif process.ProcessId in [0, 4] and error_code == 2:
# Access Denied for System Idle Process and System
owner['user'] = 'SYSTEM'
owner['user_domain'] = 'NT AUTHORITY'
else:
log.warning('Error getting owner of process; PID=\'%s\'; Error: %s',
process.ProcessId, error_code)
return owner
def _byte_calc(val):
if val < 1024:
tstr = six.text_type(val)+'B'
elif val < 1038336:
tstr = six.text_type(val/1024)+'KB'
elif val < 1073741824:
tstr = six.text_type(val/1038336)+'MB'
elif val < 1099511627776:
tstr = six.text_type(val/1073741824)+'GB'
else:
tstr = six.text_type(val/1099511627776)+'TB'
return tstr
def master(master=None, connected=True):
'''
.. versionadded:: 2015.5.0
Fire an event if the minion gets disconnected from its master. This
function is meant to be run via a scheduled job from the minion. If
master_ip is an FQDN/Hostname, is must be resolvable to a valid IPv4
address.
CLI Example:
.. code-block:: bash
salt '*' status.master
'''
def _win_remotes_on(port):
'''
Windows specific helper function.
Returns set of ipv4 host addresses of remote established connections
on local or remote tcp port.
Parses output of shell 'netstat' to get connections
PS C:> netstat -n -p TCP
Active Connections
Proto Local Address Foreign Address State
TCP 10.1.1.26:3389 10.1.1.1:4505 ESTABLISHED
TCP 10.1.1.26:56862 10.1.1.10:49155 TIME_WAIT
TCP 10.1.1.26:56868 169.254.169.254:80 CLOSE_WAIT
TCP 127.0.0.1:49197 127.0.0.1:49198 ESTABLISHED
TCP 127.0.0.1:49198 127.0.0.1:49197 ESTABLISHED
'''
remotes = set()
try:
data = subprocess.check_output(['netstat', '-n', '-p', 'TCP']) # pylint: disable=minimum-python-version
except subprocess.CalledProcessError:
log.error('Failed netstat')
raise
lines = salt.utils.stringutils.to_unicode(data).split('\n')
for line in lines:
if 'ESTABLISHED' not in line:
continue
chunks = line.split()
remote_host, remote_port = chunks[2].rsplit(':', 1)
if int(remote_port) != port:
continue
remotes.add(remote_host)
return remotes
# the default publishing port
port = 4505
master_ips = None
if master:
master_ips = _host_to_ips(master)
if not master_ips:
return
if __salt__['config.get']('publish_port') != '':
port = int(__salt__['config.get']('publish_port'))
master_connection_status = False
connected_ips = _win_remotes_on(port)
# Get connection status for master
for master_ip in master_ips:
if master_ip in connected_ips:
master_connection_status = True
break
# Connection to master is not as expected
if master_connection_status is not connected:
event = salt.utils.event.get_event('minion', opts=__opts__, listen=False)
if master_connection_status:
event.fire_event({'master': master}, salt.minion.master_event(type='connected'))
else:
event.fire_event({'master': master}, salt.minion.master_event(type='disconnected'))
return master_connection_status
|
saltstack/salt
|
salt/modules/win_status.py
|
master
|
python
|
def master(master=None, connected=True):
'''
.. versionadded:: 2015.5.0
Fire an event if the minion gets disconnected from its master. This
function is meant to be run via a scheduled job from the minion. If
master_ip is an FQDN/Hostname, is must be resolvable to a valid IPv4
address.
CLI Example:
.. code-block:: bash
salt '*' status.master
'''
def _win_remotes_on(port):
'''
Windows specific helper function.
Returns set of ipv4 host addresses of remote established connections
on local or remote tcp port.
Parses output of shell 'netstat' to get connections
PS C:> netstat -n -p TCP
Active Connections
Proto Local Address Foreign Address State
TCP 10.1.1.26:3389 10.1.1.1:4505 ESTABLISHED
TCP 10.1.1.26:56862 10.1.1.10:49155 TIME_WAIT
TCP 10.1.1.26:56868 169.254.169.254:80 CLOSE_WAIT
TCP 127.0.0.1:49197 127.0.0.1:49198 ESTABLISHED
TCP 127.0.0.1:49198 127.0.0.1:49197 ESTABLISHED
'''
remotes = set()
try:
data = subprocess.check_output(['netstat', '-n', '-p', 'TCP']) # pylint: disable=minimum-python-version
except subprocess.CalledProcessError:
log.error('Failed netstat')
raise
lines = salt.utils.stringutils.to_unicode(data).split('\n')
for line in lines:
if 'ESTABLISHED' not in line:
continue
chunks = line.split()
remote_host, remote_port = chunks[2].rsplit(':', 1)
if int(remote_port) != port:
continue
remotes.add(remote_host)
return remotes
# the default publishing port
port = 4505
master_ips = None
if master:
master_ips = _host_to_ips(master)
if not master_ips:
return
if __salt__['config.get']('publish_port') != '':
port = int(__salt__['config.get']('publish_port'))
master_connection_status = False
connected_ips = _win_remotes_on(port)
# Get connection status for master
for master_ip in master_ips:
if master_ip in connected_ips:
master_connection_status = True
break
# Connection to master is not as expected
if master_connection_status is not connected:
event = salt.utils.event.get_event('minion', opts=__opts__, listen=False)
if master_connection_status:
event.fire_event({'master': master}, salt.minion.master_event(type='connected'))
else:
event.fire_event({'master': master}, salt.minion.master_event(type='disconnected'))
return master_connection_status
|
.. versionadded:: 2015.5.0
Fire an event if the minion gets disconnected from its master. This
function is meant to be run via a scheduled job from the minion. If
master_ip is an FQDN/Hostname, is must be resolvable to a valid IPv4
address.
CLI Example:
.. code-block:: bash
salt '*' status.master
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_status.py#L506-L589
|
[
"def get_event(\n node, sock_dir=None, transport='zeromq',\n opts=None, listen=True, io_loop=None, keep_loop=False, raise_errors=False):\n '''\n Return an event object suitable for the named transport\n\n :param IOLoop io_loop: Pass in an io_loop if you want asynchronous\n operation for obtaining events. Eg use of\n set_event_handler() API. Otherwise, operation\n will be synchronous.\n '''\n sock_dir = sock_dir or opts['sock_dir']\n # TODO: AIO core is separate from transport\n if node == 'master':\n return MasterEvent(sock_dir,\n opts,\n listen=listen,\n io_loop=io_loop,\n keep_loop=keep_loop,\n raise_errors=raise_errors)\n return SaltEvent(node,\n sock_dir,\n opts,\n listen=listen,\n io_loop=io_loop,\n keep_loop=keep_loop,\n raise_errors=raise_errors)\n",
"def host_to_ips(host):\n '''\n Returns a list of IP addresses of a given hostname or None if not found.\n '''\n ips = []\n try:\n for family, socktype, proto, canonname, sockaddr in socket.getaddrinfo(\n host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM):\n if family == socket.AF_INET:\n ip, port = sockaddr\n elif family == socket.AF_INET6:\n ip, port, flow_info, scope_id = sockaddr\n ips.append(ip)\n if not ips:\n ips = None\n except Exception:\n ips = None\n return ips\n",
"def master_event(type, master=None):\n '''\n Centralized master event function which will return event type based on event_map\n '''\n event_map = {'connected': '__master_connected',\n 'disconnected': '__master_disconnected',\n 'failback': '__master_failback',\n 'alive': '__master_alive'}\n\n if type == 'alive' and master is not None:\n return '{0}_{1}'.format(event_map.get(type), master)\n\n return event_map.get(type, None)\n",
"def _win_remotes_on(port):\n '''\n Windows specific helper function.\n Returns set of ipv4 host addresses of remote established connections\n on local or remote tcp port.\n\n Parses output of shell 'netstat' to get connections\n\n PS C:> netstat -n -p TCP\n\n Active Connections\n\n Proto Local Address Foreign Address State\n TCP 10.1.1.26:3389 10.1.1.1:4505 ESTABLISHED\n TCP 10.1.1.26:56862 10.1.1.10:49155 TIME_WAIT\n TCP 10.1.1.26:56868 169.254.169.254:80 CLOSE_WAIT\n TCP 127.0.0.1:49197 127.0.0.1:49198 ESTABLISHED\n TCP 127.0.0.1:49198 127.0.0.1:49197 ESTABLISHED\n '''\n remotes = set()\n try:\n data = subprocess.check_output(['netstat', '-n', '-p', 'TCP']) # pylint: disable=minimum-python-version\n except subprocess.CalledProcessError:\n log.error('Failed netstat')\n raise\n\n lines = salt.utils.stringutils.to_unicode(data).split('\\n')\n for line in lines:\n if 'ESTABLISHED' not in line:\n continue\n chunks = line.split()\n remote_host, remote_port = chunks[2].rsplit(':', 1)\n if int(remote_port) != port:\n continue\n remotes.add(remote_host)\n return remotes\n",
"def fire_event(self, data, tag, timeout=1000):\n '''\n Send a single event into the publisher with payload dict \"data\" and\n event identifier \"tag\"\n\n The default is 1000 ms\n '''\n if not six.text_type(tag): # no empty tags allowed\n raise ValueError('Empty tag.')\n\n if not isinstance(data, MutableMapping): # data must be dict\n raise ValueError(\n 'Dict object expected, not \\'{0}\\'.'.format(data)\n )\n\n if not self.cpush:\n if timeout is not None:\n timeout_s = float(timeout) / 1000\n else:\n timeout_s = None\n if not self.connect_pull(timeout=timeout_s):\n return False\n\n data['_stamp'] = datetime.datetime.utcnow().isoformat()\n\n tagend = TAGEND\n if six.PY2:\n dump_data = self.serial.dumps(data)\n else:\n # Since the pack / unpack logic here is for local events only,\n # it is safe to change the wire protocol. The mechanism\n # that sends events from minion to master is outside this\n # file.\n dump_data = self.serial.dumps(data, use_bin_type=True)\n\n serialized_data = salt.utils.dicttrim.trim_dict(\n dump_data,\n self.opts['max_event_size'],\n is_msgpacked=True,\n use_bin_type=six.PY3\n )\n log.debug('Sending event: tag = %s; data = %s', tag, data)\n event = b''.join([\n salt.utils.stringutils.to_bytes(tag),\n salt.utils.stringutils.to_bytes(tagend),\n serialized_data])\n msg = salt.utils.stringutils.to_bytes(event, 'utf-8')\n if self._run_io_loop_sync:\n with salt.utils.asynchronous.current_ioloop(self.io_loop):\n try:\n self.io_loop.run_sync(lambda: self.pusher.send(msg))\n except Exception as ex:\n log.debug(ex)\n raise\n else:\n self.io_loop.spawn_callback(self.pusher.send, msg)\n return True\n"
] |
# -*- coding: utf-8 -*-
'''
Module for returning various status data about a minion.
These data can be useful for compiling into stats later,
or for problem solving if your minion is having problems.
.. versionadded:: 0.12.0
:depends: - wmi
'''
# Import Python Libs
from __future__ import absolute_import, unicode_literals, print_function
import ctypes
import datetime
import logging
import subprocess
log = logging.getLogger(__name__)
# Import Salt Libs
import salt.utils.event
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.win_pdh
from salt.utils.network import host_to_ips as _host_to_ips
from salt.utils.functools import namespaced_function as _namespaced_function
# Import 3rd party Libs
from salt.ext import six
# These imports needed for namespaced functions
# pylint: disable=W0611
from salt.modules.status import ping_master, time_
import copy
# pylint: enable=W0611
# Import 3rd Party Libs
try:
if salt.utils.platform.is_windows():
import wmi
import salt.utils.winapi
HAS_WMI = True
else:
HAS_WMI = False
except ImportError:
HAS_WMI = False
HAS_PSUTIL = False
if salt.utils.platform.is_windows():
import psutil
HAS_PSUTIL = True
__opts__ = {}
__virtualname__ = 'status'
# Taken from https://www.geoffchappell.com/studies/windows/km/ntoskrnl/api/ex/sysinfo/performance.htm
class SYSTEM_PERFORMANCE_INFORMATION(ctypes.Structure):
_fields_ = [('IdleProcessTime', ctypes.c_int64),
('IoReadTransferCount', ctypes.c_int64),
('IoWriteTransferCount', ctypes.c_int64),
('IoOtherTransferCount', ctypes.c_int64),
('IoReadOperationCount', ctypes.c_ulong),
('IoWriteOperationCount', ctypes.c_ulong),
('IoOtherOperationCount', ctypes.c_ulong),
('AvailablePages', ctypes.c_ulong),
('CommittedPages', ctypes.c_ulong),
('CommitLimit', ctypes.c_ulong),
('PeakCommitment', ctypes.c_ulong),
('PageFaultCount', ctypes.c_ulong),
('CopyOnWriteCount', ctypes.c_ulong),
('TransitionCount', ctypes.c_ulong),
('CacheTransitionCount', ctypes.c_ulong),
('DemandZeroCount', ctypes.c_ulong),
('PageReadCount', ctypes.c_ulong),
('PageReadIoCount', ctypes.c_ulong),
('CacheReadCount', ctypes.c_ulong), # Was c_ulong ** 2
('CacheIoCount', ctypes.c_ulong),
('DirtyPagesWriteCount', ctypes.c_ulong),
('DirtyWriteIoCount', ctypes.c_ulong),
('MappedPagesWriteCount', ctypes.c_ulong),
('MappedWriteIoCount', ctypes.c_ulong),
('PagedPoolPages', ctypes.c_ulong),
('NonPagedPoolPages', ctypes.c_ulong),
('PagedPoolAllocs', ctypes.c_ulong),
('PagedPoolFrees', ctypes.c_ulong),
('NonPagedPoolAllocs', ctypes.c_ulong),
('NonPagedPoolFrees', ctypes.c_ulong),
('FreeSystemPtes', ctypes.c_ulong),
('ResidentSystemCodePage', ctypes.c_ulong),
('TotalSystemDriverPages', ctypes.c_ulong),
('TotalSystemCodePages', ctypes.c_ulong),
('NonPagedPoolLookasideHits', ctypes.c_ulong),
('PagedPoolLookasideHits', ctypes.c_ulong),
('AvailablePagedPoolPages', ctypes.c_ulong),
('ResidentSystemCachePage', ctypes.c_ulong),
('ResidentPagedPoolPage', ctypes.c_ulong),
('ResidentSystemDriverPage', ctypes.c_ulong),
('CcFastReadNoWait', ctypes.c_ulong),
('CcFastReadWait', ctypes.c_ulong),
('CcFastReadResourceMiss', ctypes.c_ulong),
('CcFastReadNotPossible', ctypes.c_ulong),
('CcFastMdlReadNoWait', ctypes.c_ulong),
('CcFastMdlReadWait', ctypes.c_ulong),
('CcFastMdlReadResourceMiss', ctypes.c_ulong),
('CcFastMdlReadNotPossible', ctypes.c_ulong),
('CcMapDataNoWait', ctypes.c_ulong),
('CcMapDataWait', ctypes.c_ulong),
('CcMapDataNoWaitMiss', ctypes.c_ulong),
('CcMapDataWaitMiss', ctypes.c_ulong),
('CcPinMappedDataCount', ctypes.c_ulong),
('CcPinReadNoWait', ctypes.c_ulong),
('CcPinReadWait', ctypes.c_ulong),
('CcPinReadNoWaitMiss', ctypes.c_ulong),
('CcPinReadWaitMiss', ctypes.c_ulong),
('CcCopyReadNoWait', ctypes.c_ulong),
('CcCopyReadWait', ctypes.c_ulong),
('CcCopyReadNoWaitMiss', ctypes.c_ulong),
('CcCopyReadWaitMiss', ctypes.c_ulong),
('CcMdlReadNoWait', ctypes.c_ulong),
('CcMdlReadWait', ctypes.c_ulong),
('CcMdlReadNoWaitMiss', ctypes.c_ulong),
('CcMdlReadWaitMiss', ctypes.c_ulong),
('CcReadAheadIos', ctypes.c_ulong),
('CcLazyWriteIos', ctypes.c_ulong),
('CcLazyWritePages', ctypes.c_ulong),
('CcDataFlushes', ctypes.c_ulong),
('CcDataPages', ctypes.c_ulong),
('ContextSwitches', ctypes.c_ulong),
('FirstLevelTbFills', ctypes.c_ulong),
('SecondLevelTbFills', ctypes.c_ulong),
('SystemCalls', ctypes.c_ulong),
# Windows 8 and above
('CcTotalDirtyPages', ctypes.c_ulonglong),
('CcDirtyPagesThreshold', ctypes.c_ulonglong),
('ResidentAvailablePages', ctypes.c_longlong),
# Windows 10 and above
('SharedCommittedPages', ctypes.c_ulonglong)]
def __virtual__():
'''
Only works on Windows systems with WMI and WinAPI
'''
if not salt.utils.platform.is_windows():
return False, 'win_status.py: Requires Windows'
if not HAS_WMI:
return False, 'win_status.py: Requires WMI and WinAPI'
if not HAS_PSUTIL:
return False, 'win_status.py: Requires psutil'
# Namespace modules from `status.py`
global ping_master, time_
ping_master = _namespaced_function(ping_master, globals())
time_ = _namespaced_function(time_, globals())
return __virtualname__
__func_alias__ = {
'time_': 'time'
}
def cpustats():
'''
Return information about the CPU.
Returns
dict: A dictionary containing information about the CPU stats
CLI Example:
.. code-block:: bash
salt * status.cpustats
'''
# Tries to gather information similar to that returned by a Linux machine
# Avoid using WMI as there's a lot of overhead
# Time related info
user, system, idle, interrupt, dpc = psutil.cpu_times()
cpu = {'user': user,
'system': system,
'idle': idle,
'irq': interrupt,
'dpc': dpc}
# Count related info
ctx_switches, interrupts, soft_interrupts, sys_calls = psutil.cpu_stats()
intr = {'irqs': {'irqs': [],
'total': interrupts}}
soft_irq = {'softirqs': [],
'total': soft_interrupts}
return {'btime': psutil.boot_time(),
'cpu': cpu,
'ctxt': ctx_switches,
'intr': intr,
'processes': len(psutil.pids()),
'softirq': soft_irq,
'syscalls': sys_calls}
def meminfo():
'''
Return information about physical and virtual memory on the system
Returns:
dict: A dictionary of information about memory on the system
CLI Example:
.. code-block:: bash
salt * status.meminfo
'''
# Get physical memory
vm_total, vm_available, vm_percent, vm_used, vm_free = psutil.virtual_memory()
# Get swap memory
swp_total, swp_used, swp_free, swp_percent, _, _ = psutil.swap_memory()
def get_unit_value(memory):
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {}
for i, s in enumerate(symbols):
prefix[s] = 1 << (i + 1) * 10
for s in reversed(symbols):
if memory >= prefix[s]:
value = float(memory) / prefix[s]
return {'unit': s,
'value': value}
return {'unit': 'B',
'value': memory}
return {'VmallocTotal': get_unit_value(vm_total),
'VmallocUsed': get_unit_value(vm_used),
'VmallocFree': get_unit_value(vm_free),
'VmallocAvail': get_unit_value(vm_available),
'SwapTotal': get_unit_value(swp_total),
'SwapUsed': get_unit_value(swp_used),
'SwapFree': get_unit_value(swp_free)}
def vmstats():
'''
Return information about the virtual memory on the machine
Returns:
dict: A dictionary of virtual memory stats
CLI Example:
.. code-block:: bash
salt * status.vmstats
'''
# Setup the SPI Structure
spi = SYSTEM_PERFORMANCE_INFORMATION()
retlen = ctypes.c_ulong()
# 2 means to query System Performance Information and return it in a
# SYSTEM_PERFORMANCE_INFORMATION Structure
ctypes.windll.ntdll.NtQuerySystemInformation(
2, ctypes.byref(spi), ctypes.sizeof(spi), ctypes.byref(retlen))
# Return each defined field in a dict
ret = {}
for field in spi._fields_:
ret.update({field[0]: getattr(spi, field[0])})
return ret
def loadavg():
'''
Returns counter information related to the load of the machine
Returns:
dict: A dictionary of counters
CLI Example:
.. code-block:: bash
salt * status.loadavg
'''
# Counter List (obj, instance, counter)
counter_list = [
('Memory', None, 'Available Bytes'),
('Memory', None, 'Pages/sec'),
('Paging File', '*', '% Usage'),
('Processor', '*', '% Processor Time'),
('Processor', '*', 'DPCs Queued/sec'),
('Processor', '*', '% Privileged Time'),
('Processor', '*', '% User Time'),
('Processor', '*', '% DPC Time'),
('Processor', '*', '% Interrupt Time'),
('Server', None, 'Work Item Shortages'),
('Server Work Queues', '*', 'Queue Length'),
('System', None, 'Processor Queue Length'),
('System', None, 'Context Switches/sec'),
]
return salt.utils.win_pdh.get_counters(counter_list=counter_list)
def cpuload():
'''
.. versionadded:: 2015.8.0
Return the processor load as a percentage
CLI Example:
.. code-block:: bash
salt '*' status.cpuload
'''
return psutil.cpu_percent()
def diskusage(human_readable=False, path=None):
'''
.. versionadded:: 2015.8.0
Return the disk usage for this minion
human_readable : False
If ``True``, usage will be in KB/MB/GB etc.
CLI Example:
.. code-block:: bash
salt '*' status.diskusage path=c:/salt
'''
if not path:
path = 'c:/'
disk_stats = psutil.disk_usage(path)
total_val = disk_stats.total
used_val = disk_stats.used
free_val = disk_stats.free
percent = disk_stats.percent
if human_readable:
total_val = _byte_calc(total_val)
used_val = _byte_calc(used_val)
free_val = _byte_calc(free_val)
return {'total': total_val,
'used': used_val,
'free': free_val,
'percent': percent}
def procs(count=False):
'''
Return the process data
count : False
If ``True``, this function will simply return the number of processes.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' status.procs
salt '*' status.procs count
'''
with salt.utils.winapi.Com():
wmi_obj = wmi.WMI()
processes = wmi_obj.win32_process()
#this short circuit's the function to get a short simple proc count.
if count:
return len(processes)
#a propper run of the function, creating a nonsensically long out put.
process_info = {}
for proc in processes:
process_info[proc.ProcessId] = _get_process_info(proc)
return process_info
def saltmem(human_readable=False):
'''
.. versionadded:: 2015.8.0
Returns the amount of memory that salt is using
human_readable : False
return the value in a nicely formatted number
CLI Example:
.. code-block:: bash
salt '*' status.saltmem
salt '*' status.saltmem human_readable=True
'''
# psutil.Process defaults to current process (`os.getpid()`)
p = psutil.Process()
# Use oneshot to get a snapshot
with p.oneshot():
mem = p.memory_info().rss
if human_readable:
return _byte_calc(mem)
return mem
def uptime(human_readable=False):
'''
.. versionadded:: 2015.8.0
Return the system uptime for the machine
Args:
human_readable (bool):
Return uptime in human readable format if ``True``, otherwise
return seconds. Default is ``False``
.. note::
Human readable format is ``days, hours:min:sec``. Days will only
be displayed if more than 0
Returns:
str:
The uptime in seconds or human readable format depending on the
value of ``human_readable``
CLI Example:
.. code-block:: bash
salt '*' status.uptime
salt '*' status.uptime human_readable=True
'''
# Get startup time
startup_time = datetime.datetime.fromtimestamp(psutil.boot_time())
# Subtract startup time from current time to get the uptime of the system
uptime = datetime.datetime.now() - startup_time
return six.text_type(uptime) if human_readable else uptime.total_seconds()
def _get_process_info(proc):
'''
Return process information
'''
cmd = salt.utils.stringutils.to_unicode(proc.CommandLine or '')
name = salt.utils.stringutils.to_unicode(proc.Name)
info = dict(
cmd=cmd,
name=name,
**_get_process_owner(proc)
)
return info
def _get_process_owner(process):
owner = {}
domain, error_code, user = None, None, None
try:
domain, error_code, user = process.GetOwner()
owner['user'] = salt.utils.stringutils.to_unicode(user)
owner['user_domain'] = salt.utils.stringutils.to_unicode(domain)
except Exception as exc:
pass
if not error_code and all((user, domain)):
owner['user'] = salt.utils.stringutils.to_unicode(user)
owner['user_domain'] = salt.utils.stringutils.to_unicode(domain)
elif process.ProcessId in [0, 4] and error_code == 2:
# Access Denied for System Idle Process and System
owner['user'] = 'SYSTEM'
owner['user_domain'] = 'NT AUTHORITY'
else:
log.warning('Error getting owner of process; PID=\'%s\'; Error: %s',
process.ProcessId, error_code)
return owner
def _byte_calc(val):
if val < 1024:
tstr = six.text_type(val)+'B'
elif val < 1038336:
tstr = six.text_type(val/1024)+'KB'
elif val < 1073741824:
tstr = six.text_type(val/1038336)+'MB'
elif val < 1099511627776:
tstr = six.text_type(val/1073741824)+'GB'
else:
tstr = six.text_type(val/1099511627776)+'TB'
return tstr
|
saltstack/salt
|
salt/modules/poudriere.py
|
_check_config_exists
|
python
|
def _check_config_exists(config_file=None):
'''
Verify the config file is present
'''
if config_file is None:
config_file = _config_file()
if not os.path.isfile(config_file):
return False
return True
|
Verify the config file is present
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/poudriere.py#L43-L51
|
[
"def _config_file():\n '''\n Return the config file location to use\n '''\n return __salt__['config.option']('poudriere.config')\n"
] |
# -*- coding: utf-8 -*-
'''
Support for poudriere
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import os
import logging
# Import salt libs
import salt.utils.files
import salt.utils.path
import salt.utils.stringutils
log = logging.getLogger(__name__)
def __virtual__():
'''
Module load on freebsd only and if poudriere installed
'''
if __grains__['os'] == 'FreeBSD' and salt.utils.path.which('poudriere'):
return 'poudriere'
else:
return (False, 'The poudriere execution module failed to load: only available on FreeBSD with the poudriere binary in the path.')
def _config_file():
'''
Return the config file location to use
'''
return __salt__['config.option']('poudriere.config')
def _config_dir():
'''
Return the configuration directory to use
'''
return __salt__['config.option']('poudriere.config_dir')
def is_jail(name):
'''
Return True if jail exists False if not
CLI Example:
.. code-block:: bash
salt '*' poudriere.is_jail <jail name>
'''
jails = list_jails()
for jail in jails:
if jail.split()[0] == name:
return True
return False
def make_pkgng_aware(jname):
'''
Make jail ``jname`` pkgng aware
CLI Example:
.. code-block:: bash
salt '*' poudriere.make_pkgng_aware <jail name>
'''
ret = {'changes': {}}
cdir = _config_dir()
# ensure cdir is there
if not os.path.isdir(cdir):
os.makedirs(cdir)
if os.path.isdir(cdir):
ret['changes'] = 'Created poudriere make file dir {0}'.format(cdir)
else:
return 'Could not create or find required directory {0}'.format(
cdir)
# Added args to file
__salt__['file.write']('{0}-make.conf'.format(os.path.join(cdir, jname)), 'WITH_PKGNG=yes')
if os.path.isfile(os.path.join(cdir, jname) + '-make.conf'):
ret['changes'] = 'Created {0}'.format(
os.path.join(cdir, '{0}-make.conf'.format(jname))
)
return ret
else:
return 'Looks like file {0} could not be created'.format(
os.path.join(cdir, jname + '-make.conf')
)
def parse_config(config_file=None):
'''
Returns a dict of poudriere main configuration definitions
CLI Example:
.. code-block:: bash
salt '*' poudriere.parse_config
'''
if config_file is None:
config_file = _config_file()
ret = {}
if _check_config_exists(config_file):
with salt.utils.files.fopen(config_file) as ifile:
for line in ifile:
key, val = salt.utils.stringutils.to_unicode(line).split('=')
ret[key] = val
return ret
return 'Could not find {0} on file system'.format(config_file)
def version():
'''
Return poudriere version
CLI Example:
.. code-block:: bash
salt '*' poudriere.version
'''
cmd = "poudriere version"
return __salt__['cmd.run'](cmd)
def list_jails():
'''
Return a list of current jails managed by poudriere
CLI Example:
.. code-block:: bash
salt '*' poudriere.list_jails
'''
_check_config_exists()
cmd = 'poudriere jails -l'
res = __salt__['cmd.run'](cmd)
return res.splitlines()
def list_ports():
'''
Return a list of current port trees managed by poudriere
CLI Example:
.. code-block:: bash
salt '*' poudriere.list_ports
'''
_check_config_exists()
cmd = 'poudriere ports -l'
res = __salt__['cmd.run'](cmd).splitlines()
return res
def create_jail(name, arch, version="9.0-RELEASE"):
'''
Creates a new poudriere jail if one does not exist
*NOTE* creating a new jail will take some time the master is not hanging
CLI Example:
.. code-block:: bash
salt '*' poudriere.create_jail 90amd64 amd64
'''
# Config file must be on system to create a poudriere jail
_check_config_exists()
# Check if the jail is there
if is_jail(name):
return '{0} already exists'.format(name)
cmd = 'poudriere jails -c -j {0} -v {1} -a {2}'.format(name, version, arch)
__salt__['cmd.run'](cmd)
# Make jail pkgng aware
make_pkgng_aware(name)
# Make sure the jail was created
if is_jail(name):
return 'Created jail {0}'.format(name)
return 'Issue creating jail {0}'.format(name)
def update_jail(name):
'''
Run freebsd-update on `name` poudriere jail
CLI Example:
.. code-block:: bash
salt '*' poudriere.update_jail freebsd:10:x86:64
'''
if is_jail(name):
cmd = 'poudriere jail -u -j {0}'.format(name)
ret = __salt__['cmd.run'](cmd)
return ret
else:
return 'Could not find jail {0}'.format(name)
def delete_jail(name):
'''
Deletes poudriere jail with `name`
CLI Example:
.. code-block:: bash
salt '*' poudriere.delete_jail 90amd64
'''
if is_jail(name):
cmd = 'poudriere jail -d -j {0}'.format(name)
__salt__['cmd.run'](cmd)
# Make sure jail is gone
if is_jail(name):
return 'Looks like there was an issue deleteing jail \
{0}'.format(name)
else:
# Could not find jail.
return 'Looks like jail {0} has not been created'.format(name)
# clean up pkgng make info in config dir
make_file = os.path.join(_config_dir(), '{0}-make.conf'.format(name))
if os.path.isfile(make_file):
try:
os.remove(make_file)
except (IOError, OSError):
return ('Deleted jail "{0}" but was unable to remove jail make '
'file').format(name)
__salt__['file.remove'](make_file)
return 'Deleted jail {0}'.format(name)
def create_ports_tree():
'''
Not working need to run portfetch non interactive
'''
_check_config_exists()
cmd = 'poudriere ports -c'
ret = __salt__['cmd.run'](cmd)
return ret
def update_ports_tree(ports_tree):
'''
Updates the ports tree, either the default or the `ports_tree` specified
CLI Example:
.. code-block:: bash
salt '*' poudriere.update_ports_tree staging
'''
_check_config_exists()
if ports_tree:
cmd = 'poudriere ports -u -p {0}'.format(ports_tree)
else:
cmd = 'poudriere ports -u'
ret = __salt__['cmd.run'](cmd)
return ret
def bulk_build(jail, pkg_file, keep=False):
'''
Run bulk build on poudriere server.
Return number of pkg builds, failures, and errors, on error dump to CLI
CLI Example:
.. code-block:: bash
salt -N buildbox_group poudriere.bulk_build 90amd64 /root/pkg_list
'''
# make sure `pkg file` and jail is on file system
if not os.path.isfile(pkg_file):
return 'Could not find file {0} on filesystem'.format(pkg_file)
if not is_jail(jail):
return 'Could not find jail {0}'.format(jail)
# Generate command
if keep:
cmd = 'poudriere bulk -k -f {0} -j {1}'.format(pkg_file, jail)
else:
cmd = 'poudriere bulk -f {0} -j {1}'.format(pkg_file, jail)
# Bulk build this can take some time, depending on pkg_file ... hours
res = __salt__['cmd.run'](cmd)
lines = res.splitlines()
for line in lines:
if "packages built" in line:
return line
return ('There may have been an issue building packages dumping output: '
'{0}').format(res)
|
saltstack/salt
|
salt/modules/poudriere.py
|
is_jail
|
python
|
def is_jail(name):
'''
Return True if jail exists False if not
CLI Example:
.. code-block:: bash
salt '*' poudriere.is_jail <jail name>
'''
jails = list_jails()
for jail in jails:
if jail.split()[0] == name:
return True
return False
|
Return True if jail exists False if not
CLI Example:
.. code-block:: bash
salt '*' poudriere.is_jail <jail name>
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/poudriere.py#L54-L68
|
[
"def list_jails():\n '''\n Return a list of current jails managed by poudriere\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' poudriere.list_jails\n '''\n _check_config_exists()\n cmd = 'poudriere jails -l'\n res = __salt__['cmd.run'](cmd)\n return res.splitlines()\n"
] |
# -*- coding: utf-8 -*-
'''
Support for poudriere
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import os
import logging
# Import salt libs
import salt.utils.files
import salt.utils.path
import salt.utils.stringutils
log = logging.getLogger(__name__)
def __virtual__():
'''
Module load on freebsd only and if poudriere installed
'''
if __grains__['os'] == 'FreeBSD' and salt.utils.path.which('poudriere'):
return 'poudriere'
else:
return (False, 'The poudriere execution module failed to load: only available on FreeBSD with the poudriere binary in the path.')
def _config_file():
'''
Return the config file location to use
'''
return __salt__['config.option']('poudriere.config')
def _config_dir():
'''
Return the configuration directory to use
'''
return __salt__['config.option']('poudriere.config_dir')
def _check_config_exists(config_file=None):
'''
Verify the config file is present
'''
if config_file is None:
config_file = _config_file()
if not os.path.isfile(config_file):
return False
return True
def make_pkgng_aware(jname):
'''
Make jail ``jname`` pkgng aware
CLI Example:
.. code-block:: bash
salt '*' poudriere.make_pkgng_aware <jail name>
'''
ret = {'changes': {}}
cdir = _config_dir()
# ensure cdir is there
if not os.path.isdir(cdir):
os.makedirs(cdir)
if os.path.isdir(cdir):
ret['changes'] = 'Created poudriere make file dir {0}'.format(cdir)
else:
return 'Could not create or find required directory {0}'.format(
cdir)
# Added args to file
__salt__['file.write']('{0}-make.conf'.format(os.path.join(cdir, jname)), 'WITH_PKGNG=yes')
if os.path.isfile(os.path.join(cdir, jname) + '-make.conf'):
ret['changes'] = 'Created {0}'.format(
os.path.join(cdir, '{0}-make.conf'.format(jname))
)
return ret
else:
return 'Looks like file {0} could not be created'.format(
os.path.join(cdir, jname + '-make.conf')
)
def parse_config(config_file=None):
'''
Returns a dict of poudriere main configuration definitions
CLI Example:
.. code-block:: bash
salt '*' poudriere.parse_config
'''
if config_file is None:
config_file = _config_file()
ret = {}
if _check_config_exists(config_file):
with salt.utils.files.fopen(config_file) as ifile:
for line in ifile:
key, val = salt.utils.stringutils.to_unicode(line).split('=')
ret[key] = val
return ret
return 'Could not find {0} on file system'.format(config_file)
def version():
'''
Return poudriere version
CLI Example:
.. code-block:: bash
salt '*' poudriere.version
'''
cmd = "poudriere version"
return __salt__['cmd.run'](cmd)
def list_jails():
'''
Return a list of current jails managed by poudriere
CLI Example:
.. code-block:: bash
salt '*' poudriere.list_jails
'''
_check_config_exists()
cmd = 'poudriere jails -l'
res = __salt__['cmd.run'](cmd)
return res.splitlines()
def list_ports():
'''
Return a list of current port trees managed by poudriere
CLI Example:
.. code-block:: bash
salt '*' poudriere.list_ports
'''
_check_config_exists()
cmd = 'poudriere ports -l'
res = __salt__['cmd.run'](cmd).splitlines()
return res
def create_jail(name, arch, version="9.0-RELEASE"):
'''
Creates a new poudriere jail if one does not exist
*NOTE* creating a new jail will take some time the master is not hanging
CLI Example:
.. code-block:: bash
salt '*' poudriere.create_jail 90amd64 amd64
'''
# Config file must be on system to create a poudriere jail
_check_config_exists()
# Check if the jail is there
if is_jail(name):
return '{0} already exists'.format(name)
cmd = 'poudriere jails -c -j {0} -v {1} -a {2}'.format(name, version, arch)
__salt__['cmd.run'](cmd)
# Make jail pkgng aware
make_pkgng_aware(name)
# Make sure the jail was created
if is_jail(name):
return 'Created jail {0}'.format(name)
return 'Issue creating jail {0}'.format(name)
def update_jail(name):
'''
Run freebsd-update on `name` poudriere jail
CLI Example:
.. code-block:: bash
salt '*' poudriere.update_jail freebsd:10:x86:64
'''
if is_jail(name):
cmd = 'poudriere jail -u -j {0}'.format(name)
ret = __salt__['cmd.run'](cmd)
return ret
else:
return 'Could not find jail {0}'.format(name)
def delete_jail(name):
'''
Deletes poudriere jail with `name`
CLI Example:
.. code-block:: bash
salt '*' poudriere.delete_jail 90amd64
'''
if is_jail(name):
cmd = 'poudriere jail -d -j {0}'.format(name)
__salt__['cmd.run'](cmd)
# Make sure jail is gone
if is_jail(name):
return 'Looks like there was an issue deleteing jail \
{0}'.format(name)
else:
# Could not find jail.
return 'Looks like jail {0} has not been created'.format(name)
# clean up pkgng make info in config dir
make_file = os.path.join(_config_dir(), '{0}-make.conf'.format(name))
if os.path.isfile(make_file):
try:
os.remove(make_file)
except (IOError, OSError):
return ('Deleted jail "{0}" but was unable to remove jail make '
'file').format(name)
__salt__['file.remove'](make_file)
return 'Deleted jail {0}'.format(name)
def create_ports_tree():
'''
Not working need to run portfetch non interactive
'''
_check_config_exists()
cmd = 'poudriere ports -c'
ret = __salt__['cmd.run'](cmd)
return ret
def update_ports_tree(ports_tree):
'''
Updates the ports tree, either the default or the `ports_tree` specified
CLI Example:
.. code-block:: bash
salt '*' poudriere.update_ports_tree staging
'''
_check_config_exists()
if ports_tree:
cmd = 'poudriere ports -u -p {0}'.format(ports_tree)
else:
cmd = 'poudriere ports -u'
ret = __salt__['cmd.run'](cmd)
return ret
def bulk_build(jail, pkg_file, keep=False):
'''
Run bulk build on poudriere server.
Return number of pkg builds, failures, and errors, on error dump to CLI
CLI Example:
.. code-block:: bash
salt -N buildbox_group poudriere.bulk_build 90amd64 /root/pkg_list
'''
# make sure `pkg file` and jail is on file system
if not os.path.isfile(pkg_file):
return 'Could not find file {0} on filesystem'.format(pkg_file)
if not is_jail(jail):
return 'Could not find jail {0}'.format(jail)
# Generate command
if keep:
cmd = 'poudriere bulk -k -f {0} -j {1}'.format(pkg_file, jail)
else:
cmd = 'poudriere bulk -f {0} -j {1}'.format(pkg_file, jail)
# Bulk build this can take some time, depending on pkg_file ... hours
res = __salt__['cmd.run'](cmd)
lines = res.splitlines()
for line in lines:
if "packages built" in line:
return line
return ('There may have been an issue building packages dumping output: '
'{0}').format(res)
|
saltstack/salt
|
salt/modules/poudriere.py
|
make_pkgng_aware
|
python
|
def make_pkgng_aware(jname):
'''
Make jail ``jname`` pkgng aware
CLI Example:
.. code-block:: bash
salt '*' poudriere.make_pkgng_aware <jail name>
'''
ret = {'changes': {}}
cdir = _config_dir()
# ensure cdir is there
if not os.path.isdir(cdir):
os.makedirs(cdir)
if os.path.isdir(cdir):
ret['changes'] = 'Created poudriere make file dir {0}'.format(cdir)
else:
return 'Could not create or find required directory {0}'.format(
cdir)
# Added args to file
__salt__['file.write']('{0}-make.conf'.format(os.path.join(cdir, jname)), 'WITH_PKGNG=yes')
if os.path.isfile(os.path.join(cdir, jname) + '-make.conf'):
ret['changes'] = 'Created {0}'.format(
os.path.join(cdir, '{0}-make.conf'.format(jname))
)
return ret
else:
return 'Looks like file {0} could not be created'.format(
os.path.join(cdir, jname + '-make.conf')
)
|
Make jail ``jname`` pkgng aware
CLI Example:
.. code-block:: bash
salt '*' poudriere.make_pkgng_aware <jail name>
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/poudriere.py#L71-L103
|
[
"def _config_dir():\n '''\n Return the configuration directory to use\n '''\n return __salt__['config.option']('poudriere.config_dir')\n"
] |
# -*- coding: utf-8 -*-
'''
Support for poudriere
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import os
import logging
# Import salt libs
import salt.utils.files
import salt.utils.path
import salt.utils.stringutils
log = logging.getLogger(__name__)
def __virtual__():
'''
Module load on freebsd only and if poudriere installed
'''
if __grains__['os'] == 'FreeBSD' and salt.utils.path.which('poudriere'):
return 'poudriere'
else:
return (False, 'The poudriere execution module failed to load: only available on FreeBSD with the poudriere binary in the path.')
def _config_file():
'''
Return the config file location to use
'''
return __salt__['config.option']('poudriere.config')
def _config_dir():
'''
Return the configuration directory to use
'''
return __salt__['config.option']('poudriere.config_dir')
def _check_config_exists(config_file=None):
'''
Verify the config file is present
'''
if config_file is None:
config_file = _config_file()
if not os.path.isfile(config_file):
return False
return True
def is_jail(name):
'''
Return True if jail exists False if not
CLI Example:
.. code-block:: bash
salt '*' poudriere.is_jail <jail name>
'''
jails = list_jails()
for jail in jails:
if jail.split()[0] == name:
return True
return False
def parse_config(config_file=None):
'''
Returns a dict of poudriere main configuration definitions
CLI Example:
.. code-block:: bash
salt '*' poudriere.parse_config
'''
if config_file is None:
config_file = _config_file()
ret = {}
if _check_config_exists(config_file):
with salt.utils.files.fopen(config_file) as ifile:
for line in ifile:
key, val = salt.utils.stringutils.to_unicode(line).split('=')
ret[key] = val
return ret
return 'Could not find {0} on file system'.format(config_file)
def version():
'''
Return poudriere version
CLI Example:
.. code-block:: bash
salt '*' poudriere.version
'''
cmd = "poudriere version"
return __salt__['cmd.run'](cmd)
def list_jails():
'''
Return a list of current jails managed by poudriere
CLI Example:
.. code-block:: bash
salt '*' poudriere.list_jails
'''
_check_config_exists()
cmd = 'poudriere jails -l'
res = __salt__['cmd.run'](cmd)
return res.splitlines()
def list_ports():
'''
Return a list of current port trees managed by poudriere
CLI Example:
.. code-block:: bash
salt '*' poudriere.list_ports
'''
_check_config_exists()
cmd = 'poudriere ports -l'
res = __salt__['cmd.run'](cmd).splitlines()
return res
def create_jail(name, arch, version="9.0-RELEASE"):
'''
Creates a new poudriere jail if one does not exist
*NOTE* creating a new jail will take some time the master is not hanging
CLI Example:
.. code-block:: bash
salt '*' poudriere.create_jail 90amd64 amd64
'''
# Config file must be on system to create a poudriere jail
_check_config_exists()
# Check if the jail is there
if is_jail(name):
return '{0} already exists'.format(name)
cmd = 'poudriere jails -c -j {0} -v {1} -a {2}'.format(name, version, arch)
__salt__['cmd.run'](cmd)
# Make jail pkgng aware
make_pkgng_aware(name)
# Make sure the jail was created
if is_jail(name):
return 'Created jail {0}'.format(name)
return 'Issue creating jail {0}'.format(name)
def update_jail(name):
'''
Run freebsd-update on `name` poudriere jail
CLI Example:
.. code-block:: bash
salt '*' poudriere.update_jail freebsd:10:x86:64
'''
if is_jail(name):
cmd = 'poudriere jail -u -j {0}'.format(name)
ret = __salt__['cmd.run'](cmd)
return ret
else:
return 'Could not find jail {0}'.format(name)
def delete_jail(name):
'''
Deletes poudriere jail with `name`
CLI Example:
.. code-block:: bash
salt '*' poudriere.delete_jail 90amd64
'''
if is_jail(name):
cmd = 'poudriere jail -d -j {0}'.format(name)
__salt__['cmd.run'](cmd)
# Make sure jail is gone
if is_jail(name):
return 'Looks like there was an issue deleteing jail \
{0}'.format(name)
else:
# Could not find jail.
return 'Looks like jail {0} has not been created'.format(name)
# clean up pkgng make info in config dir
make_file = os.path.join(_config_dir(), '{0}-make.conf'.format(name))
if os.path.isfile(make_file):
try:
os.remove(make_file)
except (IOError, OSError):
return ('Deleted jail "{0}" but was unable to remove jail make '
'file').format(name)
__salt__['file.remove'](make_file)
return 'Deleted jail {0}'.format(name)
def create_ports_tree():
'''
Not working need to run portfetch non interactive
'''
_check_config_exists()
cmd = 'poudriere ports -c'
ret = __salt__['cmd.run'](cmd)
return ret
def update_ports_tree(ports_tree):
'''
Updates the ports tree, either the default or the `ports_tree` specified
CLI Example:
.. code-block:: bash
salt '*' poudriere.update_ports_tree staging
'''
_check_config_exists()
if ports_tree:
cmd = 'poudriere ports -u -p {0}'.format(ports_tree)
else:
cmd = 'poudriere ports -u'
ret = __salt__['cmd.run'](cmd)
return ret
def bulk_build(jail, pkg_file, keep=False):
'''
Run bulk build on poudriere server.
Return number of pkg builds, failures, and errors, on error dump to CLI
CLI Example:
.. code-block:: bash
salt -N buildbox_group poudriere.bulk_build 90amd64 /root/pkg_list
'''
# make sure `pkg file` and jail is on file system
if not os.path.isfile(pkg_file):
return 'Could not find file {0} on filesystem'.format(pkg_file)
if not is_jail(jail):
return 'Could not find jail {0}'.format(jail)
# Generate command
if keep:
cmd = 'poudriere bulk -k -f {0} -j {1}'.format(pkg_file, jail)
else:
cmd = 'poudriere bulk -f {0} -j {1}'.format(pkg_file, jail)
# Bulk build this can take some time, depending on pkg_file ... hours
res = __salt__['cmd.run'](cmd)
lines = res.splitlines()
for line in lines:
if "packages built" in line:
return line
return ('There may have been an issue building packages dumping output: '
'{0}').format(res)
|
saltstack/salt
|
salt/modules/poudriere.py
|
parse_config
|
python
|
def parse_config(config_file=None):
'''
Returns a dict of poudriere main configuration definitions
CLI Example:
.. code-block:: bash
salt '*' poudriere.parse_config
'''
if config_file is None:
config_file = _config_file()
ret = {}
if _check_config_exists(config_file):
with salt.utils.files.fopen(config_file) as ifile:
for line in ifile:
key, val = salt.utils.stringutils.to_unicode(line).split('=')
ret[key] = val
return ret
return 'Could not find {0} on file system'.format(config_file)
|
Returns a dict of poudriere main configuration definitions
CLI Example:
.. code-block:: bash
salt '*' poudriere.parse_config
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/poudriere.py#L106-L126
|
[
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n",
"def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n",
"def _config_file():\n '''\n Return the config file location to use\n '''\n return __salt__['config.option']('poudriere.config')\n",
"def _check_config_exists(config_file=None):\n '''\n Verify the config file is present\n '''\n if config_file is None:\n config_file = _config_file()\n if not os.path.isfile(config_file):\n return False\n return True\n"
] |
# -*- coding: utf-8 -*-
'''
Support for poudriere
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import os
import logging
# Import salt libs
import salt.utils.files
import salt.utils.path
import salt.utils.stringutils
log = logging.getLogger(__name__)
def __virtual__():
'''
Module load on freebsd only and if poudriere installed
'''
if __grains__['os'] == 'FreeBSD' and salt.utils.path.which('poudriere'):
return 'poudriere'
else:
return (False, 'The poudriere execution module failed to load: only available on FreeBSD with the poudriere binary in the path.')
def _config_file():
'''
Return the config file location to use
'''
return __salt__['config.option']('poudriere.config')
def _config_dir():
'''
Return the configuration directory to use
'''
return __salt__['config.option']('poudriere.config_dir')
def _check_config_exists(config_file=None):
'''
Verify the config file is present
'''
if config_file is None:
config_file = _config_file()
if not os.path.isfile(config_file):
return False
return True
def is_jail(name):
'''
Return True if jail exists False if not
CLI Example:
.. code-block:: bash
salt '*' poudriere.is_jail <jail name>
'''
jails = list_jails()
for jail in jails:
if jail.split()[0] == name:
return True
return False
def make_pkgng_aware(jname):
'''
Make jail ``jname`` pkgng aware
CLI Example:
.. code-block:: bash
salt '*' poudriere.make_pkgng_aware <jail name>
'''
ret = {'changes': {}}
cdir = _config_dir()
# ensure cdir is there
if not os.path.isdir(cdir):
os.makedirs(cdir)
if os.path.isdir(cdir):
ret['changes'] = 'Created poudriere make file dir {0}'.format(cdir)
else:
return 'Could not create or find required directory {0}'.format(
cdir)
# Added args to file
__salt__['file.write']('{0}-make.conf'.format(os.path.join(cdir, jname)), 'WITH_PKGNG=yes')
if os.path.isfile(os.path.join(cdir, jname) + '-make.conf'):
ret['changes'] = 'Created {0}'.format(
os.path.join(cdir, '{0}-make.conf'.format(jname))
)
return ret
else:
return 'Looks like file {0} could not be created'.format(
os.path.join(cdir, jname + '-make.conf')
)
def version():
'''
Return poudriere version
CLI Example:
.. code-block:: bash
salt '*' poudriere.version
'''
cmd = "poudriere version"
return __salt__['cmd.run'](cmd)
def list_jails():
'''
Return a list of current jails managed by poudriere
CLI Example:
.. code-block:: bash
salt '*' poudriere.list_jails
'''
_check_config_exists()
cmd = 'poudriere jails -l'
res = __salt__['cmd.run'](cmd)
return res.splitlines()
def list_ports():
'''
Return a list of current port trees managed by poudriere
CLI Example:
.. code-block:: bash
salt '*' poudriere.list_ports
'''
_check_config_exists()
cmd = 'poudriere ports -l'
res = __salt__['cmd.run'](cmd).splitlines()
return res
def create_jail(name, arch, version="9.0-RELEASE"):
'''
Creates a new poudriere jail if one does not exist
*NOTE* creating a new jail will take some time the master is not hanging
CLI Example:
.. code-block:: bash
salt '*' poudriere.create_jail 90amd64 amd64
'''
# Config file must be on system to create a poudriere jail
_check_config_exists()
# Check if the jail is there
if is_jail(name):
return '{0} already exists'.format(name)
cmd = 'poudriere jails -c -j {0} -v {1} -a {2}'.format(name, version, arch)
__salt__['cmd.run'](cmd)
# Make jail pkgng aware
make_pkgng_aware(name)
# Make sure the jail was created
if is_jail(name):
return 'Created jail {0}'.format(name)
return 'Issue creating jail {0}'.format(name)
def update_jail(name):
'''
Run freebsd-update on `name` poudriere jail
CLI Example:
.. code-block:: bash
salt '*' poudriere.update_jail freebsd:10:x86:64
'''
if is_jail(name):
cmd = 'poudriere jail -u -j {0}'.format(name)
ret = __salt__['cmd.run'](cmd)
return ret
else:
return 'Could not find jail {0}'.format(name)
def delete_jail(name):
'''
Deletes poudriere jail with `name`
CLI Example:
.. code-block:: bash
salt '*' poudriere.delete_jail 90amd64
'''
if is_jail(name):
cmd = 'poudriere jail -d -j {0}'.format(name)
__salt__['cmd.run'](cmd)
# Make sure jail is gone
if is_jail(name):
return 'Looks like there was an issue deleteing jail \
{0}'.format(name)
else:
# Could not find jail.
return 'Looks like jail {0} has not been created'.format(name)
# clean up pkgng make info in config dir
make_file = os.path.join(_config_dir(), '{0}-make.conf'.format(name))
if os.path.isfile(make_file):
try:
os.remove(make_file)
except (IOError, OSError):
return ('Deleted jail "{0}" but was unable to remove jail make '
'file').format(name)
__salt__['file.remove'](make_file)
return 'Deleted jail {0}'.format(name)
def create_ports_tree():
'''
Not working need to run portfetch non interactive
'''
_check_config_exists()
cmd = 'poudriere ports -c'
ret = __salt__['cmd.run'](cmd)
return ret
def update_ports_tree(ports_tree):
'''
Updates the ports tree, either the default or the `ports_tree` specified
CLI Example:
.. code-block:: bash
salt '*' poudriere.update_ports_tree staging
'''
_check_config_exists()
if ports_tree:
cmd = 'poudriere ports -u -p {0}'.format(ports_tree)
else:
cmd = 'poudriere ports -u'
ret = __salt__['cmd.run'](cmd)
return ret
def bulk_build(jail, pkg_file, keep=False):
'''
Run bulk build on poudriere server.
Return number of pkg builds, failures, and errors, on error dump to CLI
CLI Example:
.. code-block:: bash
salt -N buildbox_group poudriere.bulk_build 90amd64 /root/pkg_list
'''
# make sure `pkg file` and jail is on file system
if not os.path.isfile(pkg_file):
return 'Could not find file {0} on filesystem'.format(pkg_file)
if not is_jail(jail):
return 'Could not find jail {0}'.format(jail)
# Generate command
if keep:
cmd = 'poudriere bulk -k -f {0} -j {1}'.format(pkg_file, jail)
else:
cmd = 'poudriere bulk -f {0} -j {1}'.format(pkg_file, jail)
# Bulk build this can take some time, depending on pkg_file ... hours
res = __salt__['cmd.run'](cmd)
lines = res.splitlines()
for line in lines:
if "packages built" in line:
return line
return ('There may have been an issue building packages dumping output: '
'{0}').format(res)
|
saltstack/salt
|
salt/modules/poudriere.py
|
create_jail
|
python
|
def create_jail(name, arch, version="9.0-RELEASE"):
'''
Creates a new poudriere jail if one does not exist
*NOTE* creating a new jail will take some time the master is not hanging
CLI Example:
.. code-block:: bash
salt '*' poudriere.create_jail 90amd64 amd64
'''
# Config file must be on system to create a poudriere jail
_check_config_exists()
# Check if the jail is there
if is_jail(name):
return '{0} already exists'.format(name)
cmd = 'poudriere jails -c -j {0} -v {1} -a {2}'.format(name, version, arch)
__salt__['cmd.run'](cmd)
# Make jail pkgng aware
make_pkgng_aware(name)
# Make sure the jail was created
if is_jail(name):
return 'Created jail {0}'.format(name)
return 'Issue creating jail {0}'.format(name)
|
Creates a new poudriere jail if one does not exist
*NOTE* creating a new jail will take some time the master is not hanging
CLI Example:
.. code-block:: bash
salt '*' poudriere.create_jail 90amd64 amd64
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/poudriere.py#L175-L204
|
[
"def _check_config_exists(config_file=None):\n '''\n Verify the config file is present\n '''\n if config_file is None:\n config_file = _config_file()\n if not os.path.isfile(config_file):\n return False\n return True\n",
"def is_jail(name):\n '''\n Return True if jail exists False if not\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' poudriere.is_jail <jail name>\n '''\n jails = list_jails()\n for jail in jails:\n if jail.split()[0] == name:\n return True\n return False\n",
"def make_pkgng_aware(jname):\n '''\n Make jail ``jname`` pkgng aware\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' poudriere.make_pkgng_aware <jail name>\n '''\n ret = {'changes': {}}\n cdir = _config_dir()\n # ensure cdir is there\n if not os.path.isdir(cdir):\n os.makedirs(cdir)\n if os.path.isdir(cdir):\n ret['changes'] = 'Created poudriere make file dir {0}'.format(cdir)\n else:\n return 'Could not create or find required directory {0}'.format(\n cdir)\n\n # Added args to file\n __salt__['file.write']('{0}-make.conf'.format(os.path.join(cdir, jname)), 'WITH_PKGNG=yes')\n\n if os.path.isfile(os.path.join(cdir, jname) + '-make.conf'):\n ret['changes'] = 'Created {0}'.format(\n os.path.join(cdir, '{0}-make.conf'.format(jname))\n )\n return ret\n else:\n return 'Looks like file {0} could not be created'.format(\n os.path.join(cdir, jname + '-make.conf')\n )\n"
] |
# -*- coding: utf-8 -*-
'''
Support for poudriere
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import os
import logging
# Import salt libs
import salt.utils.files
import salt.utils.path
import salt.utils.stringutils
log = logging.getLogger(__name__)
def __virtual__():
'''
Module load on freebsd only and if poudriere installed
'''
if __grains__['os'] == 'FreeBSD' and salt.utils.path.which('poudriere'):
return 'poudriere'
else:
return (False, 'The poudriere execution module failed to load: only available on FreeBSD with the poudriere binary in the path.')
def _config_file():
'''
Return the config file location to use
'''
return __salt__['config.option']('poudriere.config')
def _config_dir():
'''
Return the configuration directory to use
'''
return __salt__['config.option']('poudriere.config_dir')
def _check_config_exists(config_file=None):
'''
Verify the config file is present
'''
if config_file is None:
config_file = _config_file()
if not os.path.isfile(config_file):
return False
return True
def is_jail(name):
'''
Return True if jail exists False if not
CLI Example:
.. code-block:: bash
salt '*' poudriere.is_jail <jail name>
'''
jails = list_jails()
for jail in jails:
if jail.split()[0] == name:
return True
return False
def make_pkgng_aware(jname):
'''
Make jail ``jname`` pkgng aware
CLI Example:
.. code-block:: bash
salt '*' poudriere.make_pkgng_aware <jail name>
'''
ret = {'changes': {}}
cdir = _config_dir()
# ensure cdir is there
if not os.path.isdir(cdir):
os.makedirs(cdir)
if os.path.isdir(cdir):
ret['changes'] = 'Created poudriere make file dir {0}'.format(cdir)
else:
return 'Could not create or find required directory {0}'.format(
cdir)
# Added args to file
__salt__['file.write']('{0}-make.conf'.format(os.path.join(cdir, jname)), 'WITH_PKGNG=yes')
if os.path.isfile(os.path.join(cdir, jname) + '-make.conf'):
ret['changes'] = 'Created {0}'.format(
os.path.join(cdir, '{0}-make.conf'.format(jname))
)
return ret
else:
return 'Looks like file {0} could not be created'.format(
os.path.join(cdir, jname + '-make.conf')
)
def parse_config(config_file=None):
'''
Returns a dict of poudriere main configuration definitions
CLI Example:
.. code-block:: bash
salt '*' poudriere.parse_config
'''
if config_file is None:
config_file = _config_file()
ret = {}
if _check_config_exists(config_file):
with salt.utils.files.fopen(config_file) as ifile:
for line in ifile:
key, val = salt.utils.stringutils.to_unicode(line).split('=')
ret[key] = val
return ret
return 'Could not find {0} on file system'.format(config_file)
def version():
'''
Return poudriere version
CLI Example:
.. code-block:: bash
salt '*' poudriere.version
'''
cmd = "poudriere version"
return __salt__['cmd.run'](cmd)
def list_jails():
'''
Return a list of current jails managed by poudriere
CLI Example:
.. code-block:: bash
salt '*' poudriere.list_jails
'''
_check_config_exists()
cmd = 'poudriere jails -l'
res = __salt__['cmd.run'](cmd)
return res.splitlines()
def list_ports():
'''
Return a list of current port trees managed by poudriere
CLI Example:
.. code-block:: bash
salt '*' poudriere.list_ports
'''
_check_config_exists()
cmd = 'poudriere ports -l'
res = __salt__['cmd.run'](cmd).splitlines()
return res
def update_jail(name):
'''
Run freebsd-update on `name` poudriere jail
CLI Example:
.. code-block:: bash
salt '*' poudriere.update_jail freebsd:10:x86:64
'''
if is_jail(name):
cmd = 'poudriere jail -u -j {0}'.format(name)
ret = __salt__['cmd.run'](cmd)
return ret
else:
return 'Could not find jail {0}'.format(name)
def delete_jail(name):
'''
Deletes poudriere jail with `name`
CLI Example:
.. code-block:: bash
salt '*' poudriere.delete_jail 90amd64
'''
if is_jail(name):
cmd = 'poudriere jail -d -j {0}'.format(name)
__salt__['cmd.run'](cmd)
# Make sure jail is gone
if is_jail(name):
return 'Looks like there was an issue deleteing jail \
{0}'.format(name)
else:
# Could not find jail.
return 'Looks like jail {0} has not been created'.format(name)
# clean up pkgng make info in config dir
make_file = os.path.join(_config_dir(), '{0}-make.conf'.format(name))
if os.path.isfile(make_file):
try:
os.remove(make_file)
except (IOError, OSError):
return ('Deleted jail "{0}" but was unable to remove jail make '
'file').format(name)
__salt__['file.remove'](make_file)
return 'Deleted jail {0}'.format(name)
def create_ports_tree():
'''
Not working need to run portfetch non interactive
'''
_check_config_exists()
cmd = 'poudriere ports -c'
ret = __salt__['cmd.run'](cmd)
return ret
def update_ports_tree(ports_tree):
'''
Updates the ports tree, either the default or the `ports_tree` specified
CLI Example:
.. code-block:: bash
salt '*' poudriere.update_ports_tree staging
'''
_check_config_exists()
if ports_tree:
cmd = 'poudriere ports -u -p {0}'.format(ports_tree)
else:
cmd = 'poudriere ports -u'
ret = __salt__['cmd.run'](cmd)
return ret
def bulk_build(jail, pkg_file, keep=False):
'''
Run bulk build on poudriere server.
Return number of pkg builds, failures, and errors, on error dump to CLI
CLI Example:
.. code-block:: bash
salt -N buildbox_group poudriere.bulk_build 90amd64 /root/pkg_list
'''
# make sure `pkg file` and jail is on file system
if not os.path.isfile(pkg_file):
return 'Could not find file {0} on filesystem'.format(pkg_file)
if not is_jail(jail):
return 'Could not find jail {0}'.format(jail)
# Generate command
if keep:
cmd = 'poudriere bulk -k -f {0} -j {1}'.format(pkg_file, jail)
else:
cmd = 'poudriere bulk -f {0} -j {1}'.format(pkg_file, jail)
# Bulk build this can take some time, depending on pkg_file ... hours
res = __salt__['cmd.run'](cmd)
lines = res.splitlines()
for line in lines:
if "packages built" in line:
return line
return ('There may have been an issue building packages dumping output: '
'{0}').format(res)
|
saltstack/salt
|
salt/modules/poudriere.py
|
update_jail
|
python
|
def update_jail(name):
'''
Run freebsd-update on `name` poudriere jail
CLI Example:
.. code-block:: bash
salt '*' poudriere.update_jail freebsd:10:x86:64
'''
if is_jail(name):
cmd = 'poudriere jail -u -j {0}'.format(name)
ret = __salt__['cmd.run'](cmd)
return ret
else:
return 'Could not find jail {0}'.format(name)
|
Run freebsd-update on `name` poudriere jail
CLI Example:
.. code-block:: bash
salt '*' poudriere.update_jail freebsd:10:x86:64
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/poudriere.py#L207-L222
|
[
"def is_jail(name):\n '''\n Return True if jail exists False if not\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' poudriere.is_jail <jail name>\n '''\n jails = list_jails()\n for jail in jails:\n if jail.split()[0] == name:\n return True\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Support for poudriere
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import os
import logging
# Import salt libs
import salt.utils.files
import salt.utils.path
import salt.utils.stringutils
log = logging.getLogger(__name__)
def __virtual__():
'''
Module load on freebsd only and if poudriere installed
'''
if __grains__['os'] == 'FreeBSD' and salt.utils.path.which('poudriere'):
return 'poudriere'
else:
return (False, 'The poudriere execution module failed to load: only available on FreeBSD with the poudriere binary in the path.')
def _config_file():
'''
Return the config file location to use
'''
return __salt__['config.option']('poudriere.config')
def _config_dir():
'''
Return the configuration directory to use
'''
return __salt__['config.option']('poudriere.config_dir')
def _check_config_exists(config_file=None):
'''
Verify the config file is present
'''
if config_file is None:
config_file = _config_file()
if not os.path.isfile(config_file):
return False
return True
def is_jail(name):
'''
Return True if jail exists False if not
CLI Example:
.. code-block:: bash
salt '*' poudriere.is_jail <jail name>
'''
jails = list_jails()
for jail in jails:
if jail.split()[0] == name:
return True
return False
def make_pkgng_aware(jname):
'''
Make jail ``jname`` pkgng aware
CLI Example:
.. code-block:: bash
salt '*' poudriere.make_pkgng_aware <jail name>
'''
ret = {'changes': {}}
cdir = _config_dir()
# ensure cdir is there
if not os.path.isdir(cdir):
os.makedirs(cdir)
if os.path.isdir(cdir):
ret['changes'] = 'Created poudriere make file dir {0}'.format(cdir)
else:
return 'Could not create or find required directory {0}'.format(
cdir)
# Added args to file
__salt__['file.write']('{0}-make.conf'.format(os.path.join(cdir, jname)), 'WITH_PKGNG=yes')
if os.path.isfile(os.path.join(cdir, jname) + '-make.conf'):
ret['changes'] = 'Created {0}'.format(
os.path.join(cdir, '{0}-make.conf'.format(jname))
)
return ret
else:
return 'Looks like file {0} could not be created'.format(
os.path.join(cdir, jname + '-make.conf')
)
def parse_config(config_file=None):
'''
Returns a dict of poudriere main configuration definitions
CLI Example:
.. code-block:: bash
salt '*' poudriere.parse_config
'''
if config_file is None:
config_file = _config_file()
ret = {}
if _check_config_exists(config_file):
with salt.utils.files.fopen(config_file) as ifile:
for line in ifile:
key, val = salt.utils.stringutils.to_unicode(line).split('=')
ret[key] = val
return ret
return 'Could not find {0} on file system'.format(config_file)
def version():
'''
Return poudriere version
CLI Example:
.. code-block:: bash
salt '*' poudriere.version
'''
cmd = "poudriere version"
return __salt__['cmd.run'](cmd)
def list_jails():
'''
Return a list of current jails managed by poudriere
CLI Example:
.. code-block:: bash
salt '*' poudriere.list_jails
'''
_check_config_exists()
cmd = 'poudriere jails -l'
res = __salt__['cmd.run'](cmd)
return res.splitlines()
def list_ports():
'''
Return a list of current port trees managed by poudriere
CLI Example:
.. code-block:: bash
salt '*' poudriere.list_ports
'''
_check_config_exists()
cmd = 'poudriere ports -l'
res = __salt__['cmd.run'](cmd).splitlines()
return res
def create_jail(name, arch, version="9.0-RELEASE"):
'''
Creates a new poudriere jail if one does not exist
*NOTE* creating a new jail will take some time the master is not hanging
CLI Example:
.. code-block:: bash
salt '*' poudriere.create_jail 90amd64 amd64
'''
# Config file must be on system to create a poudriere jail
_check_config_exists()
# Check if the jail is there
if is_jail(name):
return '{0} already exists'.format(name)
cmd = 'poudriere jails -c -j {0} -v {1} -a {2}'.format(name, version, arch)
__salt__['cmd.run'](cmd)
# Make jail pkgng aware
make_pkgng_aware(name)
# Make sure the jail was created
if is_jail(name):
return 'Created jail {0}'.format(name)
return 'Issue creating jail {0}'.format(name)
def delete_jail(name):
'''
Deletes poudriere jail with `name`
CLI Example:
.. code-block:: bash
salt '*' poudriere.delete_jail 90amd64
'''
if is_jail(name):
cmd = 'poudriere jail -d -j {0}'.format(name)
__salt__['cmd.run'](cmd)
# Make sure jail is gone
if is_jail(name):
return 'Looks like there was an issue deleteing jail \
{0}'.format(name)
else:
# Could not find jail.
return 'Looks like jail {0} has not been created'.format(name)
# clean up pkgng make info in config dir
make_file = os.path.join(_config_dir(), '{0}-make.conf'.format(name))
if os.path.isfile(make_file):
try:
os.remove(make_file)
except (IOError, OSError):
return ('Deleted jail "{0}" but was unable to remove jail make '
'file').format(name)
__salt__['file.remove'](make_file)
return 'Deleted jail {0}'.format(name)
def create_ports_tree():
'''
Not working need to run portfetch non interactive
'''
_check_config_exists()
cmd = 'poudriere ports -c'
ret = __salt__['cmd.run'](cmd)
return ret
def update_ports_tree(ports_tree):
'''
Updates the ports tree, either the default or the `ports_tree` specified
CLI Example:
.. code-block:: bash
salt '*' poudriere.update_ports_tree staging
'''
_check_config_exists()
if ports_tree:
cmd = 'poudriere ports -u -p {0}'.format(ports_tree)
else:
cmd = 'poudriere ports -u'
ret = __salt__['cmd.run'](cmd)
return ret
def bulk_build(jail, pkg_file, keep=False):
'''
Run bulk build on poudriere server.
Return number of pkg builds, failures, and errors, on error dump to CLI
CLI Example:
.. code-block:: bash
salt -N buildbox_group poudriere.bulk_build 90amd64 /root/pkg_list
'''
# make sure `pkg file` and jail is on file system
if not os.path.isfile(pkg_file):
return 'Could not find file {0} on filesystem'.format(pkg_file)
if not is_jail(jail):
return 'Could not find jail {0}'.format(jail)
# Generate command
if keep:
cmd = 'poudriere bulk -k -f {0} -j {1}'.format(pkg_file, jail)
else:
cmd = 'poudriere bulk -f {0} -j {1}'.format(pkg_file, jail)
# Bulk build this can take some time, depending on pkg_file ... hours
res = __salt__['cmd.run'](cmd)
lines = res.splitlines()
for line in lines:
if "packages built" in line:
return line
return ('There may have been an issue building packages dumping output: '
'{0}').format(res)
|
saltstack/salt
|
salt/modules/poudriere.py
|
delete_jail
|
python
|
def delete_jail(name):
'''
Deletes poudriere jail with `name`
CLI Example:
.. code-block:: bash
salt '*' poudriere.delete_jail 90amd64
'''
if is_jail(name):
cmd = 'poudriere jail -d -j {0}'.format(name)
__salt__['cmd.run'](cmd)
# Make sure jail is gone
if is_jail(name):
return 'Looks like there was an issue deleteing jail \
{0}'.format(name)
else:
# Could not find jail.
return 'Looks like jail {0} has not been created'.format(name)
# clean up pkgng make info in config dir
make_file = os.path.join(_config_dir(), '{0}-make.conf'.format(name))
if os.path.isfile(make_file):
try:
os.remove(make_file)
except (IOError, OSError):
return ('Deleted jail "{0}" but was unable to remove jail make '
'file').format(name)
__salt__['file.remove'](make_file)
return 'Deleted jail {0}'.format(name)
|
Deletes poudriere jail with `name`
CLI Example:
.. code-block:: bash
salt '*' poudriere.delete_jail 90amd64
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/poudriere.py#L225-L257
|
[
"def is_jail(name):\n '''\n Return True if jail exists False if not\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' poudriere.is_jail <jail name>\n '''\n jails = list_jails()\n for jail in jails:\n if jail.split()[0] == name:\n return True\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Support for poudriere
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import os
import logging
# Import salt libs
import salt.utils.files
import salt.utils.path
import salt.utils.stringutils
log = logging.getLogger(__name__)
def __virtual__():
'''
Module load on freebsd only and if poudriere installed
'''
if __grains__['os'] == 'FreeBSD' and salt.utils.path.which('poudriere'):
return 'poudriere'
else:
return (False, 'The poudriere execution module failed to load: only available on FreeBSD with the poudriere binary in the path.')
def _config_file():
'''
Return the config file location to use
'''
return __salt__['config.option']('poudriere.config')
def _config_dir():
'''
Return the configuration directory to use
'''
return __salt__['config.option']('poudriere.config_dir')
def _check_config_exists(config_file=None):
'''
Verify the config file is present
'''
if config_file is None:
config_file = _config_file()
if not os.path.isfile(config_file):
return False
return True
def is_jail(name):
'''
Return True if jail exists False if not
CLI Example:
.. code-block:: bash
salt '*' poudriere.is_jail <jail name>
'''
jails = list_jails()
for jail in jails:
if jail.split()[0] == name:
return True
return False
def make_pkgng_aware(jname):
'''
Make jail ``jname`` pkgng aware
CLI Example:
.. code-block:: bash
salt '*' poudriere.make_pkgng_aware <jail name>
'''
ret = {'changes': {}}
cdir = _config_dir()
# ensure cdir is there
if not os.path.isdir(cdir):
os.makedirs(cdir)
if os.path.isdir(cdir):
ret['changes'] = 'Created poudriere make file dir {0}'.format(cdir)
else:
return 'Could not create or find required directory {0}'.format(
cdir)
# Added args to file
__salt__['file.write']('{0}-make.conf'.format(os.path.join(cdir, jname)), 'WITH_PKGNG=yes')
if os.path.isfile(os.path.join(cdir, jname) + '-make.conf'):
ret['changes'] = 'Created {0}'.format(
os.path.join(cdir, '{0}-make.conf'.format(jname))
)
return ret
else:
return 'Looks like file {0} could not be created'.format(
os.path.join(cdir, jname + '-make.conf')
)
def parse_config(config_file=None):
'''
Returns a dict of poudriere main configuration definitions
CLI Example:
.. code-block:: bash
salt '*' poudriere.parse_config
'''
if config_file is None:
config_file = _config_file()
ret = {}
if _check_config_exists(config_file):
with salt.utils.files.fopen(config_file) as ifile:
for line in ifile:
key, val = salt.utils.stringutils.to_unicode(line).split('=')
ret[key] = val
return ret
return 'Could not find {0} on file system'.format(config_file)
def version():
'''
Return poudriere version
CLI Example:
.. code-block:: bash
salt '*' poudriere.version
'''
cmd = "poudriere version"
return __salt__['cmd.run'](cmd)
def list_jails():
'''
Return a list of current jails managed by poudriere
CLI Example:
.. code-block:: bash
salt '*' poudriere.list_jails
'''
_check_config_exists()
cmd = 'poudriere jails -l'
res = __salt__['cmd.run'](cmd)
return res.splitlines()
def list_ports():
'''
Return a list of current port trees managed by poudriere
CLI Example:
.. code-block:: bash
salt '*' poudriere.list_ports
'''
_check_config_exists()
cmd = 'poudriere ports -l'
res = __salt__['cmd.run'](cmd).splitlines()
return res
def create_jail(name, arch, version="9.0-RELEASE"):
'''
Creates a new poudriere jail if one does not exist
*NOTE* creating a new jail will take some time the master is not hanging
CLI Example:
.. code-block:: bash
salt '*' poudriere.create_jail 90amd64 amd64
'''
# Config file must be on system to create a poudriere jail
_check_config_exists()
# Check if the jail is there
if is_jail(name):
return '{0} already exists'.format(name)
cmd = 'poudriere jails -c -j {0} -v {1} -a {2}'.format(name, version, arch)
__salt__['cmd.run'](cmd)
# Make jail pkgng aware
make_pkgng_aware(name)
# Make sure the jail was created
if is_jail(name):
return 'Created jail {0}'.format(name)
return 'Issue creating jail {0}'.format(name)
def update_jail(name):
'''
Run freebsd-update on `name` poudriere jail
CLI Example:
.. code-block:: bash
salt '*' poudriere.update_jail freebsd:10:x86:64
'''
if is_jail(name):
cmd = 'poudriere jail -u -j {0}'.format(name)
ret = __salt__['cmd.run'](cmd)
return ret
else:
return 'Could not find jail {0}'.format(name)
def create_ports_tree():
'''
Not working need to run portfetch non interactive
'''
_check_config_exists()
cmd = 'poudriere ports -c'
ret = __salt__['cmd.run'](cmd)
return ret
def update_ports_tree(ports_tree):
'''
Updates the ports tree, either the default or the `ports_tree` specified
CLI Example:
.. code-block:: bash
salt '*' poudriere.update_ports_tree staging
'''
_check_config_exists()
if ports_tree:
cmd = 'poudriere ports -u -p {0}'.format(ports_tree)
else:
cmd = 'poudriere ports -u'
ret = __salt__['cmd.run'](cmd)
return ret
def bulk_build(jail, pkg_file, keep=False):
'''
Run bulk build on poudriere server.
Return number of pkg builds, failures, and errors, on error dump to CLI
CLI Example:
.. code-block:: bash
salt -N buildbox_group poudriere.bulk_build 90amd64 /root/pkg_list
'''
# make sure `pkg file` and jail is on file system
if not os.path.isfile(pkg_file):
return 'Could not find file {0} on filesystem'.format(pkg_file)
if not is_jail(jail):
return 'Could not find jail {0}'.format(jail)
# Generate command
if keep:
cmd = 'poudriere bulk -k -f {0} -j {1}'.format(pkg_file, jail)
else:
cmd = 'poudriere bulk -f {0} -j {1}'.format(pkg_file, jail)
# Bulk build this can take some time, depending on pkg_file ... hours
res = __salt__['cmd.run'](cmd)
lines = res.splitlines()
for line in lines:
if "packages built" in line:
return line
return ('There may have been an issue building packages dumping output: '
'{0}').format(res)
|
saltstack/salt
|
salt/modules/poudriere.py
|
update_ports_tree
|
python
|
def update_ports_tree(ports_tree):
'''
Updates the ports tree, either the default or the `ports_tree` specified
CLI Example:
.. code-block:: bash
salt '*' poudriere.update_ports_tree staging
'''
_check_config_exists()
if ports_tree:
cmd = 'poudriere ports -u -p {0}'.format(ports_tree)
else:
cmd = 'poudriere ports -u'
ret = __salt__['cmd.run'](cmd)
return ret
|
Updates the ports tree, either the default or the `ports_tree` specified
CLI Example:
.. code-block:: bash
salt '*' poudriere.update_ports_tree staging
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/poudriere.py#L270-L286
|
[
"def _check_config_exists(config_file=None):\n '''\n Verify the config file is present\n '''\n if config_file is None:\n config_file = _config_file()\n if not os.path.isfile(config_file):\n return False\n return True\n"
] |
# -*- coding: utf-8 -*-
'''
Support for poudriere
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import os
import logging
# Import salt libs
import salt.utils.files
import salt.utils.path
import salt.utils.stringutils
log = logging.getLogger(__name__)
def __virtual__():
'''
Module load on freebsd only and if poudriere installed
'''
if __grains__['os'] == 'FreeBSD' and salt.utils.path.which('poudriere'):
return 'poudriere'
else:
return (False, 'The poudriere execution module failed to load: only available on FreeBSD with the poudriere binary in the path.')
def _config_file():
'''
Return the config file location to use
'''
return __salt__['config.option']('poudriere.config')
def _config_dir():
'''
Return the configuration directory to use
'''
return __salt__['config.option']('poudriere.config_dir')
def _check_config_exists(config_file=None):
'''
Verify the config file is present
'''
if config_file is None:
config_file = _config_file()
if not os.path.isfile(config_file):
return False
return True
def is_jail(name):
'''
Return True if jail exists False if not
CLI Example:
.. code-block:: bash
salt '*' poudriere.is_jail <jail name>
'''
jails = list_jails()
for jail in jails:
if jail.split()[0] == name:
return True
return False
def make_pkgng_aware(jname):
'''
Make jail ``jname`` pkgng aware
CLI Example:
.. code-block:: bash
salt '*' poudriere.make_pkgng_aware <jail name>
'''
ret = {'changes': {}}
cdir = _config_dir()
# ensure cdir is there
if not os.path.isdir(cdir):
os.makedirs(cdir)
if os.path.isdir(cdir):
ret['changes'] = 'Created poudriere make file dir {0}'.format(cdir)
else:
return 'Could not create or find required directory {0}'.format(
cdir)
# Added args to file
__salt__['file.write']('{0}-make.conf'.format(os.path.join(cdir, jname)), 'WITH_PKGNG=yes')
if os.path.isfile(os.path.join(cdir, jname) + '-make.conf'):
ret['changes'] = 'Created {0}'.format(
os.path.join(cdir, '{0}-make.conf'.format(jname))
)
return ret
else:
return 'Looks like file {0} could not be created'.format(
os.path.join(cdir, jname + '-make.conf')
)
def parse_config(config_file=None):
'''
Returns a dict of poudriere main configuration definitions
CLI Example:
.. code-block:: bash
salt '*' poudriere.parse_config
'''
if config_file is None:
config_file = _config_file()
ret = {}
if _check_config_exists(config_file):
with salt.utils.files.fopen(config_file) as ifile:
for line in ifile:
key, val = salt.utils.stringutils.to_unicode(line).split('=')
ret[key] = val
return ret
return 'Could not find {0} on file system'.format(config_file)
def version():
'''
Return poudriere version
CLI Example:
.. code-block:: bash
salt '*' poudriere.version
'''
cmd = "poudriere version"
return __salt__['cmd.run'](cmd)
def list_jails():
'''
Return a list of current jails managed by poudriere
CLI Example:
.. code-block:: bash
salt '*' poudriere.list_jails
'''
_check_config_exists()
cmd = 'poudriere jails -l'
res = __salt__['cmd.run'](cmd)
return res.splitlines()
def list_ports():
'''
Return a list of current port trees managed by poudriere
CLI Example:
.. code-block:: bash
salt '*' poudriere.list_ports
'''
_check_config_exists()
cmd = 'poudriere ports -l'
res = __salt__['cmd.run'](cmd).splitlines()
return res
def create_jail(name, arch, version="9.0-RELEASE"):
'''
Creates a new poudriere jail if one does not exist
*NOTE* creating a new jail will take some time the master is not hanging
CLI Example:
.. code-block:: bash
salt '*' poudriere.create_jail 90amd64 amd64
'''
# Config file must be on system to create a poudriere jail
_check_config_exists()
# Check if the jail is there
if is_jail(name):
return '{0} already exists'.format(name)
cmd = 'poudriere jails -c -j {0} -v {1} -a {2}'.format(name, version, arch)
__salt__['cmd.run'](cmd)
# Make jail pkgng aware
make_pkgng_aware(name)
# Make sure the jail was created
if is_jail(name):
return 'Created jail {0}'.format(name)
return 'Issue creating jail {0}'.format(name)
def update_jail(name):
'''
Run freebsd-update on `name` poudriere jail
CLI Example:
.. code-block:: bash
salt '*' poudriere.update_jail freebsd:10:x86:64
'''
if is_jail(name):
cmd = 'poudriere jail -u -j {0}'.format(name)
ret = __salt__['cmd.run'](cmd)
return ret
else:
return 'Could not find jail {0}'.format(name)
def delete_jail(name):
'''
Deletes poudriere jail with `name`
CLI Example:
.. code-block:: bash
salt '*' poudriere.delete_jail 90amd64
'''
if is_jail(name):
cmd = 'poudriere jail -d -j {0}'.format(name)
__salt__['cmd.run'](cmd)
# Make sure jail is gone
if is_jail(name):
return 'Looks like there was an issue deleteing jail \
{0}'.format(name)
else:
# Could not find jail.
return 'Looks like jail {0} has not been created'.format(name)
# clean up pkgng make info in config dir
make_file = os.path.join(_config_dir(), '{0}-make.conf'.format(name))
if os.path.isfile(make_file):
try:
os.remove(make_file)
except (IOError, OSError):
return ('Deleted jail "{0}" but was unable to remove jail make '
'file').format(name)
__salt__['file.remove'](make_file)
return 'Deleted jail {0}'.format(name)
def create_ports_tree():
'''
Not working need to run portfetch non interactive
'''
_check_config_exists()
cmd = 'poudriere ports -c'
ret = __salt__['cmd.run'](cmd)
return ret
def bulk_build(jail, pkg_file, keep=False):
'''
Run bulk build on poudriere server.
Return number of pkg builds, failures, and errors, on error dump to CLI
CLI Example:
.. code-block:: bash
salt -N buildbox_group poudriere.bulk_build 90amd64 /root/pkg_list
'''
# make sure `pkg file` and jail is on file system
if not os.path.isfile(pkg_file):
return 'Could not find file {0} on filesystem'.format(pkg_file)
if not is_jail(jail):
return 'Could not find jail {0}'.format(jail)
# Generate command
if keep:
cmd = 'poudriere bulk -k -f {0} -j {1}'.format(pkg_file, jail)
else:
cmd = 'poudriere bulk -f {0} -j {1}'.format(pkg_file, jail)
# Bulk build this can take some time, depending on pkg_file ... hours
res = __salt__['cmd.run'](cmd)
lines = res.splitlines()
for line in lines:
if "packages built" in line:
return line
return ('There may have been an issue building packages dumping output: '
'{0}').format(res)
|
saltstack/salt
|
salt/modules/poudriere.py
|
bulk_build
|
python
|
def bulk_build(jail, pkg_file, keep=False):
'''
Run bulk build on poudriere server.
Return number of pkg builds, failures, and errors, on error dump to CLI
CLI Example:
.. code-block:: bash
salt -N buildbox_group poudriere.bulk_build 90amd64 /root/pkg_list
'''
# make sure `pkg file` and jail is on file system
if not os.path.isfile(pkg_file):
return 'Could not find file {0} on filesystem'.format(pkg_file)
if not is_jail(jail):
return 'Could not find jail {0}'.format(jail)
# Generate command
if keep:
cmd = 'poudriere bulk -k -f {0} -j {1}'.format(pkg_file, jail)
else:
cmd = 'poudriere bulk -f {0} -j {1}'.format(pkg_file, jail)
# Bulk build this can take some time, depending on pkg_file ... hours
res = __salt__['cmd.run'](cmd)
lines = res.splitlines()
for line in lines:
if "packages built" in line:
return line
return ('There may have been an issue building packages dumping output: '
'{0}').format(res)
|
Run bulk build on poudriere server.
Return number of pkg builds, failures, and errors, on error dump to CLI
CLI Example:
.. code-block:: bash
salt -N buildbox_group poudriere.bulk_build 90amd64 /root/pkg_list
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/poudriere.py#L289-L321
|
[
"def is_jail(name):\n '''\n Return True if jail exists False if not\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' poudriere.is_jail <jail name>\n '''\n jails = list_jails()\n for jail in jails:\n if jail.split()[0] == name:\n return True\n return False\n"
] |
# -*- coding: utf-8 -*-
'''
Support for poudriere
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import os
import logging
# Import salt libs
import salt.utils.files
import salt.utils.path
import salt.utils.stringutils
log = logging.getLogger(__name__)
def __virtual__():
'''
Module load on freebsd only and if poudriere installed
'''
if __grains__['os'] == 'FreeBSD' and salt.utils.path.which('poudriere'):
return 'poudriere'
else:
return (False, 'The poudriere execution module failed to load: only available on FreeBSD with the poudriere binary in the path.')
def _config_file():
'''
Return the config file location to use
'''
return __salt__['config.option']('poudriere.config')
def _config_dir():
'''
Return the configuration directory to use
'''
return __salt__['config.option']('poudriere.config_dir')
def _check_config_exists(config_file=None):
'''
Verify the config file is present
'''
if config_file is None:
config_file = _config_file()
if not os.path.isfile(config_file):
return False
return True
def is_jail(name):
'''
Return True if jail exists False if not
CLI Example:
.. code-block:: bash
salt '*' poudriere.is_jail <jail name>
'''
jails = list_jails()
for jail in jails:
if jail.split()[0] == name:
return True
return False
def make_pkgng_aware(jname):
'''
Make jail ``jname`` pkgng aware
CLI Example:
.. code-block:: bash
salt '*' poudriere.make_pkgng_aware <jail name>
'''
ret = {'changes': {}}
cdir = _config_dir()
# ensure cdir is there
if not os.path.isdir(cdir):
os.makedirs(cdir)
if os.path.isdir(cdir):
ret['changes'] = 'Created poudriere make file dir {0}'.format(cdir)
else:
return 'Could not create or find required directory {0}'.format(
cdir)
# Added args to file
__salt__['file.write']('{0}-make.conf'.format(os.path.join(cdir, jname)), 'WITH_PKGNG=yes')
if os.path.isfile(os.path.join(cdir, jname) + '-make.conf'):
ret['changes'] = 'Created {0}'.format(
os.path.join(cdir, '{0}-make.conf'.format(jname))
)
return ret
else:
return 'Looks like file {0} could not be created'.format(
os.path.join(cdir, jname + '-make.conf')
)
def parse_config(config_file=None):
'''
Returns a dict of poudriere main configuration definitions
CLI Example:
.. code-block:: bash
salt '*' poudriere.parse_config
'''
if config_file is None:
config_file = _config_file()
ret = {}
if _check_config_exists(config_file):
with salt.utils.files.fopen(config_file) as ifile:
for line in ifile:
key, val = salt.utils.stringutils.to_unicode(line).split('=')
ret[key] = val
return ret
return 'Could not find {0} on file system'.format(config_file)
def version():
'''
Return poudriere version
CLI Example:
.. code-block:: bash
salt '*' poudriere.version
'''
cmd = "poudriere version"
return __salt__['cmd.run'](cmd)
def list_jails():
'''
Return a list of current jails managed by poudriere
CLI Example:
.. code-block:: bash
salt '*' poudriere.list_jails
'''
_check_config_exists()
cmd = 'poudriere jails -l'
res = __salt__['cmd.run'](cmd)
return res.splitlines()
def list_ports():
'''
Return a list of current port trees managed by poudriere
CLI Example:
.. code-block:: bash
salt '*' poudriere.list_ports
'''
_check_config_exists()
cmd = 'poudriere ports -l'
res = __salt__['cmd.run'](cmd).splitlines()
return res
def create_jail(name, arch, version="9.0-RELEASE"):
'''
Creates a new poudriere jail if one does not exist
*NOTE* creating a new jail will take some time the master is not hanging
CLI Example:
.. code-block:: bash
salt '*' poudriere.create_jail 90amd64 amd64
'''
# Config file must be on system to create a poudriere jail
_check_config_exists()
# Check if the jail is there
if is_jail(name):
return '{0} already exists'.format(name)
cmd = 'poudriere jails -c -j {0} -v {1} -a {2}'.format(name, version, arch)
__salt__['cmd.run'](cmd)
# Make jail pkgng aware
make_pkgng_aware(name)
# Make sure the jail was created
if is_jail(name):
return 'Created jail {0}'.format(name)
return 'Issue creating jail {0}'.format(name)
def update_jail(name):
'''
Run freebsd-update on `name` poudriere jail
CLI Example:
.. code-block:: bash
salt '*' poudriere.update_jail freebsd:10:x86:64
'''
if is_jail(name):
cmd = 'poudriere jail -u -j {0}'.format(name)
ret = __salt__['cmd.run'](cmd)
return ret
else:
return 'Could not find jail {0}'.format(name)
def delete_jail(name):
'''
Deletes poudriere jail with `name`
CLI Example:
.. code-block:: bash
salt '*' poudriere.delete_jail 90amd64
'''
if is_jail(name):
cmd = 'poudriere jail -d -j {0}'.format(name)
__salt__['cmd.run'](cmd)
# Make sure jail is gone
if is_jail(name):
return 'Looks like there was an issue deleteing jail \
{0}'.format(name)
else:
# Could not find jail.
return 'Looks like jail {0} has not been created'.format(name)
# clean up pkgng make info in config dir
make_file = os.path.join(_config_dir(), '{0}-make.conf'.format(name))
if os.path.isfile(make_file):
try:
os.remove(make_file)
except (IOError, OSError):
return ('Deleted jail "{0}" but was unable to remove jail make '
'file').format(name)
__salt__['file.remove'](make_file)
return 'Deleted jail {0}'.format(name)
def create_ports_tree():
'''
Not working need to run portfetch non interactive
'''
_check_config_exists()
cmd = 'poudriere ports -c'
ret = __salt__['cmd.run'](cmd)
return ret
def update_ports_tree(ports_tree):
'''
Updates the ports tree, either the default or the `ports_tree` specified
CLI Example:
.. code-block:: bash
salt '*' poudriere.update_ports_tree staging
'''
_check_config_exists()
if ports_tree:
cmd = 'poudriere ports -u -p {0}'.format(ports_tree)
else:
cmd = 'poudriere ports -u'
ret = __salt__['cmd.run'](cmd)
return ret
|
saltstack/salt
|
salt/modules/opkg.py
|
_update_nilrt_restart_state
|
python
|
def _update_nilrt_restart_state():
'''
NILRT systems determine whether to reboot after various package operations
including but not limited to kernel module installs/removals by checking
specific file md5sums & timestamps. These files are touched/modified by
the post-install/post-remove functions of their respective packages.
The opkg module uses this function to store/update those file timestamps
and checksums to be used later by the restartcheck module.
'''
__salt__['cmd.shell']('stat -c %Y /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.timestamp'
.format(NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.md5sum'
.format(NILRT_RESTARTCHECK_STATE_PATH))
# We can't assume nisysapi.ini always exists like modules.dep
nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'
if os.path.exists(nisysapi_path):
__salt__['cmd.shell']('stat -c %Y {0} >{1}/nisysapi.ini.timestamp'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0} >{1}/nisysapi.ini.md5sum'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
# Expert plugin files get added to a conf.d dir, so keep track of the total
# no. of files, their timestamps and content hashes
nisysapi_conf_d_path = "/usr/lib/{0}/nisysapi/conf.d/experts/".format(
'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'
)
if os.path.exists(nisysapi_conf_d_path):
with salt.utils.files.fopen('{0}/sysapi.conf.d.count'.format(
NILRT_RESTARTCHECK_STATE_PATH), 'w') as fcount:
fcount.write(str(len(os.listdir(nisysapi_conf_d_path))))
for fexpert in os.listdir(nisysapi_conf_d_path):
__salt__['cmd.shell']('stat -c %Y {0}/{1} >{2}/{1}.timestamp'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0}/{1} >{2}/{1}.md5sum'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
|
NILRT systems determine whether to reboot after various package operations
including but not limited to kernel module installs/removals by checking
specific file md5sums & timestamps. These files are touched/modified by
the post-install/post-remove functions of their respective packages.
The opkg module uses this function to store/update those file timestamps
and checksums to be used later by the restartcheck module.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/opkg.py#L63-L106
| null |
# -*- coding: utf-8 -*-
'''
Support for Opkg
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
.. versionadded: 2016.3.0
.. note::
For version comparison support on opkg < 0.3.4, the ``opkg-utils`` package
must be installed.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import os
import re
import logging
import errno
# Import salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.itertools
import salt.utils.path
import salt.utils.pkg
import salt.utils.stringutils
import salt.utils.versions
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import shlex_quote as _cmd_quote # pylint: disable=import-error
from salt.ext.six.moves import map # pylint: disable=import-error,redefined-builtin
REPO_REGEXP = r'^#?\s*(src|src/gz)\s+([^\s<>]+|"[^<>]+")\s+[^\s<>]+'
OPKG_CONFDIR = '/etc/opkg'
ATTR_MAP = {
'Architecture': 'arch',
'Homepage': 'url',
'Installed-Time': 'install_date_time_t',
'Maintainer': 'packager',
'Package': 'name',
'Section': 'group'
}
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
NILRT_RESTARTCHECK_STATE_PATH = '/var/lib/salt/restartcheck_state'
def _get_restartcheck_result(errors):
'''
Return restartcheck result and append errors (if any) to ``errors``
'''
rs_result = __salt__['restartcheck.restartcheck'](verbose=False)
if isinstance(rs_result, dict) and 'comment' in rs_result:
errors.append(rs_result['comment'])
return rs_result
def _process_restartcheck_result(rs_result, **kwargs):
'''
Check restartcheck output to see if system/service restarts were requested
and take appropriate action.
'''
if 'No packages seem to need to be restarted' in rs_result:
return
reboot_required = False
for rstr in rs_result:
if 'System restart required' in rstr:
_update_nilrt_restart_state()
__salt__['system.set_reboot_required_witnessed']()
reboot_required = True
if kwargs.get('always_restart_services', True) or not reboot_required:
for rstr in rs_result:
if 'System restart required' not in rstr:
service = os.path.join('/etc/init.d', rstr)
if os.path.exists(service):
__salt__['cmd.run']([service, 'restart'])
def __virtual__():
'''
Confirm this module is on a nilrt based system
'''
if __grains__.get('os_family') == 'NILinuxRT':
try:
os.makedirs(NILRT_RESTARTCHECK_STATE_PATH)
except OSError as exc:
if exc.errno != errno.EEXIST:
return False, 'Error creating {0} (-{1}): {2}'.format(
NILRT_RESTARTCHECK_STATE_PATH,
exc.errno,
exc.strerror)
# populate state dir if empty
if not os.listdir(NILRT_RESTARTCHECK_STATE_PATH):
_update_nilrt_restart_state()
return __virtualname__
if os.path.isdir(OPKG_CONFDIR):
return __virtualname__
return False, "Module opkg only works on OpenEmbedded based systems"
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
if not names:
return ''
ret = {}
for name in names:
ret[name] = ''
# Refresh before looking for the latest version available
if refresh:
refresh_db()
cmd = ['opkg', 'list-upgradable']
out = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
try:
name, _oldversion, newversion = line.split(' - ')
if name in names:
ret[name] = newversion
except ValueError:
pass
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = latest_version
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(failhard=False, **kwargs): # pylint: disable=unused-argument
'''
Updates the opkg database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
failhard
If False, return results of failed lines as ``False`` for the package
database that encountered the error.
If True, raise an error with a list of the package databases that
encountered errors.
.. versionadded:: 2018.3.0
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
error_repos = []
cmd = ['opkg', 'update']
# opkg returns a non-zero retcode when there is a failure to refresh
# from one or more repos. Due to this, ignore the retcode.
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True,
redirect_stderr=True)
out = call['stdout']
prev_line = ''
for line in salt.utils.itertools.split(out, '\n'):
if 'Inflating' in line:
key = line.strip().split()[1][:-1]
ret[key] = True
elif 'Updated source' in line:
# Use the previous line.
key = prev_line.strip().split()[1][:-1]
ret[key] = True
elif 'Failed to download' in line:
key = line.strip().split()[5].split(',')[0]
ret[key] = False
error_repos.append(key)
prev_line = line
if failhard and error_repos:
raise CommandExecutionError(
'Error getting repos: {0}'.format(', '.join(error_repos))
)
# On a non-zero exit code where no failed repos were found, raise an
# exception because this appears to be a different kind of error.
if call['retcode'] != 0 and not error_repos:
raise CommandExecutionError(out)
return ret
def _is_testmode(**kwargs):
'''
Returns whether a test mode (noaction) operation was requested.
'''
return bool(kwargs.get('test') or __opts__.get('test'))
def _append_noaction_if_testmode(cmd, **kwargs):
'''
Adds the --noaction flag to the command if it's running in the test mode.
'''
if _is_testmode(**kwargs):
cmd.append('--noaction')
def _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall):
'''
Builds a list of install commands to be executed in sequence in order to process
each of the to_install, to_downgrade, and to_reinstall lists.
'''
cmds = []
if to_install:
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(to_install)
cmds.append(cmd)
if to_downgrade:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-downgrade')
cmd.extend(to_downgrade)
cmds.append(cmd)
if to_reinstall:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-reinstall')
cmd.extend(to_reinstall)
cmds.append(cmd)
return cmds
def _parse_reported_packages_from_install_output(output):
'''
Parses the output of "opkg install" to determine what packages would have been
installed by an operation run with the --noaction flag.
We are looking for lines like:
Installing <package> (<version>) on <target>
or
Upgrading <package> from <oldVersion> to <version> on root
'''
reported_pkgs = {}
install_pattern = re.compile(r'Installing\s(?P<package>.*?)\s\((?P<version>.*?)\)\son\s(?P<target>.*?)')
upgrade_pattern = re.compile(r'Upgrading\s(?P<package>.*?)\sfrom\s(?P<oldVersion>.*?)\sto\s(?P<version>.*?)\son\s(?P<target>.*?)')
for line in salt.utils.itertools.split(output, '\n'):
match = install_pattern.match(line)
if match is None:
match = upgrade_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = match.group('version')
return reported_pkgs
def _execute_install_command(cmd, parse_output, errors, parsed_packages):
'''
Executes a command for the install operation.
If the command fails, its error output will be appended to the errors list.
If the command succeeds and parse_output is true, updated packages will be appended
to the parsed_packages dictionary.
'''
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors.append(out['stderr'])
else:
errors.append(out['stdout'])
elif parse_output:
parsed_packages.update(_parse_reported_packages_from_install_output(out['stdout']))
def install(name=None,
refresh=False,
pkgs=None,
sources=None,
reinstall=False,
**kwargs):
'''
Install the passed package, add refresh=True to update the opkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionadded:: 2017.7.0
reinstall : False
Specifying reinstall=True will use ``opkg install --force-reinstall``
rather than simply ``opkg install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``opkg
install --force-reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2017.7.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of IPK packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
install_recommends
Whether to install the packages marked as recommended. Default is True.
only_upgrade
Only upgrade the packages (disallow downgrades), if they are already
installed. Default is False.
.. versionadded:: 2017.7.0
always_restart_services
Whether to restart services even if a reboot is required. Default is True.
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
refreshdb = salt.utils.data.is_true(refresh)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
cmd_prefix = ['opkg', 'install']
to_install = []
to_reinstall = []
to_downgrade = []
_append_noaction_if_testmode(cmd_prefix, **kwargs)
if not pkg_params:
return {}
elif pkg_type == 'file':
if reinstall:
cmd_prefix.append('--force-reinstall')
if not kwargs.get('only_upgrade', False):
cmd_prefix.append('--force-downgrade')
to_install.extend(pkg_params)
elif pkg_type == 'repository':
if not kwargs.get('install_recommends', True):
cmd_prefix.append('--no-install-recommends')
for pkgname, pkgversion in six.iteritems(pkg_params):
if (name and pkgs is None and kwargs.get('version') and
len(pkg_params) == 1):
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
version_num = pkgversion
if version_num is None:
# Don't allow downgrades if the version
# number is not specified.
if reinstall and pkgname in old:
to_reinstall.append(pkgname)
else:
to_install.append(pkgname)
else:
pkgstr = '{0}={1}'.format(pkgname, version_num)
cver = old.get(pkgname, '')
if reinstall and cver and salt.utils.versions.compare(
ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall.append(pkgstr)
elif not cver or salt.utils.versions.compare(
ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
to_install.append(pkgstr)
else:
if not kwargs.get('only_upgrade', False):
to_downgrade.append(pkgstr)
else:
# This should cause the command to fail.
to_install.append(pkgstr)
cmds = _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall)
if not cmds:
return {}
if refreshdb:
refresh_db()
errors = []
is_testmode = _is_testmode(**kwargs)
test_packages = {}
for cmd in cmds:
_execute_install_command(cmd, is_testmode, errors, test_packages)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if is_testmode:
new = copy.deepcopy(new)
new.update(test_packages)
ret = salt.utils.data.compare_dicts(old, new)
if pkg_type == 'file' and reinstall:
# For file-based packages, prepare 'to_reinstall' to have a list
# of all the package names that may have been reinstalled.
# This way, we could include reinstalled packages in 'ret'.
for pkgfile in to_install:
# Convert from file name to package name.
cmd = ['opkg', 'info', pkgfile]
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] == 0:
# Just need the package name.
pkginfo_dict = _process_info_installed_output(
out['stdout'], []
)
if pkginfo_dict:
to_reinstall.append(list(pkginfo_dict.keys())[0])
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def _parse_reported_packages_from_remove_output(output):
'''
Parses the output of "opkg remove" to determine what packages would have been
removed by an operation run with the --noaction flag.
We are looking for lines like
Removing <package> (<version>) from <Target>...
'''
reported_pkgs = {}
remove_pattern = re.compile(r'Removing\s(?P<package>.*?)\s\((?P<version>.*?)\)\sfrom\s(?P<target>.*?)...')
for line in salt.utils.itertools.split(output, '\n'):
match = remove_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = ''
return reported_pkgs
def remove(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Remove packages using ``opkg remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
remove_dependencies
Remove package and all dependencies
.. versionadded:: 2019.2.0
auto_remove_deps
Remove packages that were installed automatically to satisfy dependencies
.. versionadded:: 2019.2.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
salt '*' pkg.remove pkgs='["foo", "bar"]' remove_dependencies=True auto_remove_deps=True
'''
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 {}
cmd = ['opkg', 'remove']
_append_noaction_if_testmode(cmd, **kwargs)
if kwargs.get('remove_dependencies', False):
cmd.append('--force-removal-of-dependent-packages')
if kwargs.get('auto_remove_deps', False):
cmd.append('--autoremove')
cmd.extend(targets)
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors = [out['stderr']]
else:
errors = [out['stdout']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if _is_testmode(**kwargs):
reportedPkgs = _parse_reported_packages_from_remove_output(out['stdout'])
new = {k: v for k, v in new.items() if k not in reportedPkgs}
ret = salt.utils.data.compare_dicts(old, new)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def purge(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Package purges are not supported by opkg, this function is identical to
:mod:`pkg.remove <salt.modules.opkg.remove>`.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name, pkgs=pkgs)
def upgrade(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
Upgrades all packages via ``opkg upgrade``
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
errors = []
if salt.utils.data.is_true(refresh):
refresh_db()
old = list_pkgs()
cmd = ['opkg', 'upgrade']
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
errors.append(result)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif state != 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = _set_state(target, 'hold')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif state == 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret['comment'] = ('Package {0} is set not to be held.'
.format(target))
else:
result = _set_state(target, 'ok')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def _get_state(pkg):
'''
View package state from the opkg database
Return the state of pkg
'''
cmd = ['opkg', 'status']
cmd.append(pkg)
out = __salt__['cmd.run'](cmd, python_shell=False)
state_flag = ''
for line in salt.utils.itertools.split(out, '\n'):
if line.startswith('Status'):
_status, _state_want, state_flag, _state_status = line.split()
return state_flag
def _set_state(pkg, state):
'''
Change package state on the opkg database
The state can be any of:
- hold
- noprune
- user
- ok
- installed
- unpacked
This command is commonly used to mark a specific package to be held from
being upgraded, that is, to be kept at a certain version.
Returns a dict containing the package name, and the new and old
versions.
'''
ret = {}
valid_states = ('hold', 'noprune', 'user', 'ok', 'installed', 'unpacked')
if state not in valid_states:
raise SaltInvocationError('Invalid state: {0}'.format(state))
oldstate = _get_state(pkg)
cmd = ['opkg', 'flag']
cmd.append(state)
cmd.append(pkg)
_out = __salt__['cmd.run'](cmd, python_shell=False)
# Missing return value check due to opkg issue 160
ret[pkg] = {'old': oldstate,
'new': state}
return ret
def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
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
cmd = ['opkg', 'list-installed']
ret = {}
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
# This is a continuation of package description
if not line or line[0] == ' ':
continue
# This contains package name, version, and description.
# Extract the first two.
pkg_name, pkg_version = line.split(' - ', 2)[:2]
__salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version)
__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 list_upgrades(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
List all available package upgrades.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
ret = {}
if salt.utils.data.is_true(refresh):
refresh_db()
cmd = ['opkg', 'list-upgradable']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
if 'stdout' in call:
comment += call['stdout']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
name, _oldversion, newversion = line.split(' - ')
ret[name] = newversion
return ret
def _convert_to_standard_attr(attr):
'''
Helper function for _process_info_installed_output()
Converts an opkg attribute name to a standard attribute
name which is used across 'pkg' modules.
'''
ret_attr = ATTR_MAP.get(attr, None)
if ret_attr is None:
# All others convert to lowercase
return attr.lower()
return ret_attr
def _process_info_installed_output(out, filter_attrs):
'''
Helper function for info_installed()
Processes stdout output from a single invocation of
'opkg status'.
'''
ret = {}
name = None
attrs = {}
attr = None
for line in salt.utils.itertools.split(out, '\n'):
if line and line[0] == ' ':
# This is a continuation of the last attr
if filter_attrs is None or attr in filter_attrs:
line = line.strip()
if attrs[attr]:
# If attr is empty, don't add leading newline
attrs[attr] += '\n'
attrs[attr] += line
continue
line = line.strip()
if not line:
# Separator between different packages
if name:
ret[name] = attrs
name = None
attrs = {}
attr = None
continue
key, value = line.split(':', 1)
value = value.lstrip()
attr = _convert_to_standard_attr(key)
if attr == 'name':
name = value
elif filter_attrs is None or attr in filter_attrs:
attrs[attr] = value
if name:
ret[name] = attrs
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
.. versionadded:: 2017.7.0
:param names:
Names of the packages to get information about. If none are specified,
will return information for all installed packages.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
arch, conffiles, conflicts, depends, description, filename, group,
install_date_time_t, md5sum, packager, provides, recommends,
replaces, size, source, suggests, url, version
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed
salt '*' pkg.info_installed attr=version,packager
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> attr=version,packager
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,packager
'''
attr = kwargs.pop('attr', None)
if attr is None:
filter_attrs = None
elif isinstance(attr, six.string_types):
filter_attrs = set(attr.split(','))
else:
filter_attrs = set(attr)
ret = {}
if names:
# Specific list of names of installed packages
for name in names:
cmd = ['opkg', 'status', name]
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
else:
# All installed packages
cmd = ['opkg', 'status']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
return ret
def upgrade_available(name, **kwargs): # pylint: disable=unused-argument
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs): # pylint: disable=unused-argument
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2016.3.4
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0' '0.2.4.1-0'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] if ignore_epoch else six.text_type(x)
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
output = __salt__['cmd.run_stdout'](['opkg', '--version'],
output_loglevel='trace',
python_shell=False)
opkg_version = output.split(' ')[2].strip()
if salt.utils.versions.LooseVersion(opkg_version) >= \
salt.utils.versions.LooseVersion('0.3.4'):
cmd_compare = ['opkg', 'compare-versions']
elif salt.utils.path.which('opkg-compare-versions'):
cmd_compare = ['opkg-compare-versions']
else:
log.warning('Unable to find a compare-versions utility installed. Either upgrade opkg to '
'version > 0.3.4 (preferred) or install the older opkg-compare-versions script.')
return None
for oper, ret in (("<<", -1), ("=", 0), (">>", 1)):
cmd = cmd_compare[:]
cmd.append(_cmd_quote(pkg1))
cmd.append(oper)
cmd.append(_cmd_quote(pkg2))
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
ignore_retcode=True,
python_shell=False)
if retcode == 0:
return ret
return None
def _set_repo_option(repo, option):
'''
Set the option to repo
'''
if not option:
return
opt = option.split('=')
if len(opt) != 2:
return
if opt[0] == 'trusted':
repo['trusted'] = opt[1] == 'yes'
else:
repo[opt[0]] = opt[1]
def _set_repo_options(repo, options):
'''
Set the options to the repo.
'''
delimiters = "[", "]"
pattern = '|'.join(map(re.escape, delimiters))
for option in options:
splitted = re.split(pattern, option)
for opt in splitted:
_set_repo_option(repo, opt)
def _create_repo(line, filename):
'''
Create repo
'''
repo = {}
if line.startswith('#'):
repo['enabled'] = False
line = line[1:]
else:
repo['enabled'] = True
cols = salt.utils.args.shlex_split(line.strip())
repo['compressed'] = not cols[0] in 'src'
repo['name'] = cols[1]
repo['uri'] = cols[2]
repo['file'] = os.path.join(OPKG_CONFDIR, filename)
if len(cols) > 3:
_set_repo_options(repo, cols[3:])
return repo
def _read_repos(conf_file, repos, filename, regex):
'''
Read repos from configuration file
'''
for line in conf_file:
line = salt.utils.stringutils.to_unicode(line)
if not regex.search(line):
continue
repo = _create_repo(line, filename)
# do not store duplicated uri's
if repo['uri'] not in repos:
repos[repo['uri']] = [repo]
def list_repos(**kwargs): # pylint: disable=unused-argument
'''
Lists all repos on ``/etc/opkg/*.conf``
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos = {}
regex = re.compile(REPO_REGEXP)
for filename in os.listdir(OPKG_CONFDIR):
if not filename.endswith(".conf"):
continue
with salt.utils.files.fopen(os.path.join(OPKG_CONFDIR, filename)) as conf_file:
_read_repos(conf_file, repos, filename, regex)
return repos
def get_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Display a repo from the ``/etc/opkg/*.conf``
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo repo
'''
repos = list_repos()
if repos:
for source in six.itervalues(repos):
for sub in source:
if sub['name'] == repo:
return sub
return {}
def _del_repo_from_file(repo, filepath):
'''
Remove a repo from filepath
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
regex = re.compile(REPO_REGEXP)
for line in fhandle:
line = salt.utils.stringutils.to_unicode(line)
if regex.search(line):
if line.startswith('#'):
line = line[1:]
cols = salt.utils.args.shlex_split(line.strip())
if repo != cols[1]:
output.append(salt.utils.stringutils.to_str(line))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def _set_trusted_option_if_needed(repostr, trusted):
'''
Set trusted option to repo if needed
'''
if trusted is True:
repostr += ' [trusted=yes]'
elif trusted is False:
repostr += ' [trusted=no]'
return repostr
def _add_new_repo(repo, properties):
'''
Add a new repo entry
'''
repostr = '# ' if not properties.get('enabled') else ''
repostr += 'src/gz ' if properties.get('compressed') else 'src '
if ' ' in repo:
repostr += '"' + repo + '" '
else:
repostr += repo + ' '
repostr += properties.get('uri')
repostr = _set_trusted_option_if_needed(repostr, properties.get('trusted'))
repostr += '\n'
conffile = os.path.join(OPKG_CONFDIR, repo + '.conf')
with salt.utils.files.fopen(conffile, 'a') as fhandle:
fhandle.write(salt.utils.stringutils.to_str(repostr))
def _mod_repo_in_file(repo, repostr, filepath):
'''
Replace a repo entry in filepath with repostr
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
for line in fhandle:
cols = salt.utils.args.shlex_split(
salt.utils.stringutils.to_unicode(line).strip()
)
if repo not in cols:
output.append(line)
else:
output.append(salt.utils.stringutils.to_str(repostr + '\n'))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def del_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Delete a repo from ``/etc/opkg/*.conf``
If the file does not contain any other repo configuration, the file itself
will be deleted.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo repo
'''
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
repos = list_repos()
if repos:
deleted_from = dict()
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
deleted_from[source['file']] = 0
_del_repo_from_file(repo, source['file'])
if deleted_from:
ret = ''
for repository in repos:
source = repos[repository][0]
if source['file'] in deleted_from:
deleted_from[source['file']] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 1 and os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.\n')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
if refresh:
refresh_db()
return ret
return "Repo {0} doesn't exist in the opkg repo lists".format(repo)
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as uri is defined.
The following options are available to modify a repo definition:
repo
alias by which opkg refers to the repo.
uri
the URI to the repo.
compressed
defines (True or False) if the index file is compressed
enabled
enable or disable (True or False) repository
but do not remove if disabled.
refresh
enable or disable (True or False) auto-refresh of the repositories
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo repo uri=http://new/uri
salt '*' pkg.mod_repo repo enabled=False
'''
repos = list_repos()
found = False
uri = ''
if 'uri' in kwargs:
uri = kwargs['uri']
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
found = True
repostr = ''
if 'enabled' in kwargs and not kwargs['enabled']:
repostr += '# '
if 'compressed' in kwargs:
repostr += 'src/gz ' if kwargs['compressed'] else 'src'
else:
repostr += 'src/gz' if source['compressed'] else 'src'
repo_alias = kwargs['alias'] if 'alias' in kwargs else repo
if ' ' in repo_alias:
repostr += ' "{0}"'.format(repo_alias)
else:
repostr += ' {0}'.format(repo_alias)
repostr += ' {0}'.format(kwargs['uri'] if 'uri' in kwargs else source['uri'])
trusted = kwargs.get('trusted')
repostr = _set_trusted_option_if_needed(repostr, trusted) if trusted is not None else \
_set_trusted_option_if_needed(repostr, source.get('trusted'))
_mod_repo_in_file(repo, repostr, source['file'])
elif uri and source['uri'] == uri:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(uri, source['name']))
if not found:
# Need to add a new repo
if 'uri' not in kwargs:
raise CommandExecutionError(
'Repository \'{0}\' not found and no URI passed to create one.'.format(repo))
properties = {'uri': kwargs['uri']}
# If compressed is not defined, assume True
properties['compressed'] = kwargs['compressed'] if 'compressed' in kwargs else True
# If enabled is not defined, assume True
properties['enabled'] = kwargs['enabled'] if 'enabled' in kwargs else True
properties['trusted'] = kwargs.get('trusted')
_add_new_repo(repo, properties)
if 'refresh' in kwargs:
refresh_db()
def file_list(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
output = file_dict(*packages)
files = []
for package in list(output['packages'].values()):
files.extend(package)
return {'errors': output['errors'], 'files': files}
def file_dict(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
errors = []
ret = {}
cmd_files = ['opkg', 'files']
if not packages:
packages = list(list_pkgs().keys())
for package in packages:
files = []
cmd = cmd_files[:]
cmd.append(package)
out = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
for line in out['stdout'].splitlines():
if line.startswith('/'):
files.append(line)
elif line.startswith(' * '):
errors.append(line[3:])
break
else:
continue
if files:
ret[package] = files
return {'errors': errors, 'packages': ret}
def owner(*paths, **kwargs): # pylint: disable=unused-argument
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.opkg.version`, if a single
path is passed, a string will be returned, and if multiple paths are passed,
a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
cmd_search = ['opkg', 'search']
for path in paths:
cmd = cmd_search[:]
cmd.append(path)
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
if output:
ret[path] = output.split(' - ')[0].strip()
else:
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def version_clean(version):
'''
Clean the version string removing extra data.
There's nothing do to here for nipkg.py, therefore it will always
return the given version.
'''
return version
def check_extra_requirements(pkgname, pkgver):
'''
Check if the installed package already has the given requirements.
There's nothing do to here for nipkg.py, therefore it will always
return True.
'''
return True
|
saltstack/salt
|
salt/modules/opkg.py
|
_get_restartcheck_result
|
python
|
def _get_restartcheck_result(errors):
'''
Return restartcheck result and append errors (if any) to ``errors``
'''
rs_result = __salt__['restartcheck.restartcheck'](verbose=False)
if isinstance(rs_result, dict) and 'comment' in rs_result:
errors.append(rs_result['comment'])
return rs_result
|
Return restartcheck result and append errors (if any) to ``errors``
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/opkg.py#L109-L116
| null |
# -*- coding: utf-8 -*-
'''
Support for Opkg
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
.. versionadded: 2016.3.0
.. note::
For version comparison support on opkg < 0.3.4, the ``opkg-utils`` package
must be installed.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import os
import re
import logging
import errno
# Import salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.itertools
import salt.utils.path
import salt.utils.pkg
import salt.utils.stringutils
import salt.utils.versions
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import shlex_quote as _cmd_quote # pylint: disable=import-error
from salt.ext.six.moves import map # pylint: disable=import-error,redefined-builtin
REPO_REGEXP = r'^#?\s*(src|src/gz)\s+([^\s<>]+|"[^<>]+")\s+[^\s<>]+'
OPKG_CONFDIR = '/etc/opkg'
ATTR_MAP = {
'Architecture': 'arch',
'Homepage': 'url',
'Installed-Time': 'install_date_time_t',
'Maintainer': 'packager',
'Package': 'name',
'Section': 'group'
}
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
NILRT_RESTARTCHECK_STATE_PATH = '/var/lib/salt/restartcheck_state'
def _update_nilrt_restart_state():
'''
NILRT systems determine whether to reboot after various package operations
including but not limited to kernel module installs/removals by checking
specific file md5sums & timestamps. These files are touched/modified by
the post-install/post-remove functions of their respective packages.
The opkg module uses this function to store/update those file timestamps
and checksums to be used later by the restartcheck module.
'''
__salt__['cmd.shell']('stat -c %Y /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.timestamp'
.format(NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.md5sum'
.format(NILRT_RESTARTCHECK_STATE_PATH))
# We can't assume nisysapi.ini always exists like modules.dep
nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'
if os.path.exists(nisysapi_path):
__salt__['cmd.shell']('stat -c %Y {0} >{1}/nisysapi.ini.timestamp'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0} >{1}/nisysapi.ini.md5sum'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
# Expert plugin files get added to a conf.d dir, so keep track of the total
# no. of files, their timestamps and content hashes
nisysapi_conf_d_path = "/usr/lib/{0}/nisysapi/conf.d/experts/".format(
'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'
)
if os.path.exists(nisysapi_conf_d_path):
with salt.utils.files.fopen('{0}/sysapi.conf.d.count'.format(
NILRT_RESTARTCHECK_STATE_PATH), 'w') as fcount:
fcount.write(str(len(os.listdir(nisysapi_conf_d_path))))
for fexpert in os.listdir(nisysapi_conf_d_path):
__salt__['cmd.shell']('stat -c %Y {0}/{1} >{2}/{1}.timestamp'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0}/{1} >{2}/{1}.md5sum'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
def _process_restartcheck_result(rs_result, **kwargs):
'''
Check restartcheck output to see if system/service restarts were requested
and take appropriate action.
'''
if 'No packages seem to need to be restarted' in rs_result:
return
reboot_required = False
for rstr in rs_result:
if 'System restart required' in rstr:
_update_nilrt_restart_state()
__salt__['system.set_reboot_required_witnessed']()
reboot_required = True
if kwargs.get('always_restart_services', True) or not reboot_required:
for rstr in rs_result:
if 'System restart required' not in rstr:
service = os.path.join('/etc/init.d', rstr)
if os.path.exists(service):
__salt__['cmd.run']([service, 'restart'])
def __virtual__():
'''
Confirm this module is on a nilrt based system
'''
if __grains__.get('os_family') == 'NILinuxRT':
try:
os.makedirs(NILRT_RESTARTCHECK_STATE_PATH)
except OSError as exc:
if exc.errno != errno.EEXIST:
return False, 'Error creating {0} (-{1}): {2}'.format(
NILRT_RESTARTCHECK_STATE_PATH,
exc.errno,
exc.strerror)
# populate state dir if empty
if not os.listdir(NILRT_RESTARTCHECK_STATE_PATH):
_update_nilrt_restart_state()
return __virtualname__
if os.path.isdir(OPKG_CONFDIR):
return __virtualname__
return False, "Module opkg only works on OpenEmbedded based systems"
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
if not names:
return ''
ret = {}
for name in names:
ret[name] = ''
# Refresh before looking for the latest version available
if refresh:
refresh_db()
cmd = ['opkg', 'list-upgradable']
out = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
try:
name, _oldversion, newversion = line.split(' - ')
if name in names:
ret[name] = newversion
except ValueError:
pass
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = latest_version
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(failhard=False, **kwargs): # pylint: disable=unused-argument
'''
Updates the opkg database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
failhard
If False, return results of failed lines as ``False`` for the package
database that encountered the error.
If True, raise an error with a list of the package databases that
encountered errors.
.. versionadded:: 2018.3.0
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
error_repos = []
cmd = ['opkg', 'update']
# opkg returns a non-zero retcode when there is a failure to refresh
# from one or more repos. Due to this, ignore the retcode.
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True,
redirect_stderr=True)
out = call['stdout']
prev_line = ''
for line in salt.utils.itertools.split(out, '\n'):
if 'Inflating' in line:
key = line.strip().split()[1][:-1]
ret[key] = True
elif 'Updated source' in line:
# Use the previous line.
key = prev_line.strip().split()[1][:-1]
ret[key] = True
elif 'Failed to download' in line:
key = line.strip().split()[5].split(',')[0]
ret[key] = False
error_repos.append(key)
prev_line = line
if failhard and error_repos:
raise CommandExecutionError(
'Error getting repos: {0}'.format(', '.join(error_repos))
)
# On a non-zero exit code where no failed repos were found, raise an
# exception because this appears to be a different kind of error.
if call['retcode'] != 0 and not error_repos:
raise CommandExecutionError(out)
return ret
def _is_testmode(**kwargs):
'''
Returns whether a test mode (noaction) operation was requested.
'''
return bool(kwargs.get('test') or __opts__.get('test'))
def _append_noaction_if_testmode(cmd, **kwargs):
'''
Adds the --noaction flag to the command if it's running in the test mode.
'''
if _is_testmode(**kwargs):
cmd.append('--noaction')
def _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall):
'''
Builds a list of install commands to be executed in sequence in order to process
each of the to_install, to_downgrade, and to_reinstall lists.
'''
cmds = []
if to_install:
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(to_install)
cmds.append(cmd)
if to_downgrade:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-downgrade')
cmd.extend(to_downgrade)
cmds.append(cmd)
if to_reinstall:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-reinstall')
cmd.extend(to_reinstall)
cmds.append(cmd)
return cmds
def _parse_reported_packages_from_install_output(output):
'''
Parses the output of "opkg install" to determine what packages would have been
installed by an operation run with the --noaction flag.
We are looking for lines like:
Installing <package> (<version>) on <target>
or
Upgrading <package> from <oldVersion> to <version> on root
'''
reported_pkgs = {}
install_pattern = re.compile(r'Installing\s(?P<package>.*?)\s\((?P<version>.*?)\)\son\s(?P<target>.*?)')
upgrade_pattern = re.compile(r'Upgrading\s(?P<package>.*?)\sfrom\s(?P<oldVersion>.*?)\sto\s(?P<version>.*?)\son\s(?P<target>.*?)')
for line in salt.utils.itertools.split(output, '\n'):
match = install_pattern.match(line)
if match is None:
match = upgrade_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = match.group('version')
return reported_pkgs
def _execute_install_command(cmd, parse_output, errors, parsed_packages):
'''
Executes a command for the install operation.
If the command fails, its error output will be appended to the errors list.
If the command succeeds and parse_output is true, updated packages will be appended
to the parsed_packages dictionary.
'''
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors.append(out['stderr'])
else:
errors.append(out['stdout'])
elif parse_output:
parsed_packages.update(_parse_reported_packages_from_install_output(out['stdout']))
def install(name=None,
refresh=False,
pkgs=None,
sources=None,
reinstall=False,
**kwargs):
'''
Install the passed package, add refresh=True to update the opkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionadded:: 2017.7.0
reinstall : False
Specifying reinstall=True will use ``opkg install --force-reinstall``
rather than simply ``opkg install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``opkg
install --force-reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2017.7.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of IPK packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
install_recommends
Whether to install the packages marked as recommended. Default is True.
only_upgrade
Only upgrade the packages (disallow downgrades), if they are already
installed. Default is False.
.. versionadded:: 2017.7.0
always_restart_services
Whether to restart services even if a reboot is required. Default is True.
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
refreshdb = salt.utils.data.is_true(refresh)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
cmd_prefix = ['opkg', 'install']
to_install = []
to_reinstall = []
to_downgrade = []
_append_noaction_if_testmode(cmd_prefix, **kwargs)
if not pkg_params:
return {}
elif pkg_type == 'file':
if reinstall:
cmd_prefix.append('--force-reinstall')
if not kwargs.get('only_upgrade', False):
cmd_prefix.append('--force-downgrade')
to_install.extend(pkg_params)
elif pkg_type == 'repository':
if not kwargs.get('install_recommends', True):
cmd_prefix.append('--no-install-recommends')
for pkgname, pkgversion in six.iteritems(pkg_params):
if (name and pkgs is None and kwargs.get('version') and
len(pkg_params) == 1):
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
version_num = pkgversion
if version_num is None:
# Don't allow downgrades if the version
# number is not specified.
if reinstall and pkgname in old:
to_reinstall.append(pkgname)
else:
to_install.append(pkgname)
else:
pkgstr = '{0}={1}'.format(pkgname, version_num)
cver = old.get(pkgname, '')
if reinstall and cver and salt.utils.versions.compare(
ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall.append(pkgstr)
elif not cver or salt.utils.versions.compare(
ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
to_install.append(pkgstr)
else:
if not kwargs.get('only_upgrade', False):
to_downgrade.append(pkgstr)
else:
# This should cause the command to fail.
to_install.append(pkgstr)
cmds = _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall)
if not cmds:
return {}
if refreshdb:
refresh_db()
errors = []
is_testmode = _is_testmode(**kwargs)
test_packages = {}
for cmd in cmds:
_execute_install_command(cmd, is_testmode, errors, test_packages)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if is_testmode:
new = copy.deepcopy(new)
new.update(test_packages)
ret = salt.utils.data.compare_dicts(old, new)
if pkg_type == 'file' and reinstall:
# For file-based packages, prepare 'to_reinstall' to have a list
# of all the package names that may have been reinstalled.
# This way, we could include reinstalled packages in 'ret'.
for pkgfile in to_install:
# Convert from file name to package name.
cmd = ['opkg', 'info', pkgfile]
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] == 0:
# Just need the package name.
pkginfo_dict = _process_info_installed_output(
out['stdout'], []
)
if pkginfo_dict:
to_reinstall.append(list(pkginfo_dict.keys())[0])
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def _parse_reported_packages_from_remove_output(output):
'''
Parses the output of "opkg remove" to determine what packages would have been
removed by an operation run with the --noaction flag.
We are looking for lines like
Removing <package> (<version>) from <Target>...
'''
reported_pkgs = {}
remove_pattern = re.compile(r'Removing\s(?P<package>.*?)\s\((?P<version>.*?)\)\sfrom\s(?P<target>.*?)...')
for line in salt.utils.itertools.split(output, '\n'):
match = remove_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = ''
return reported_pkgs
def remove(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Remove packages using ``opkg remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
remove_dependencies
Remove package and all dependencies
.. versionadded:: 2019.2.0
auto_remove_deps
Remove packages that were installed automatically to satisfy dependencies
.. versionadded:: 2019.2.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
salt '*' pkg.remove pkgs='["foo", "bar"]' remove_dependencies=True auto_remove_deps=True
'''
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 {}
cmd = ['opkg', 'remove']
_append_noaction_if_testmode(cmd, **kwargs)
if kwargs.get('remove_dependencies', False):
cmd.append('--force-removal-of-dependent-packages')
if kwargs.get('auto_remove_deps', False):
cmd.append('--autoremove')
cmd.extend(targets)
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors = [out['stderr']]
else:
errors = [out['stdout']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if _is_testmode(**kwargs):
reportedPkgs = _parse_reported_packages_from_remove_output(out['stdout'])
new = {k: v for k, v in new.items() if k not in reportedPkgs}
ret = salt.utils.data.compare_dicts(old, new)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def purge(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Package purges are not supported by opkg, this function is identical to
:mod:`pkg.remove <salt.modules.opkg.remove>`.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name, pkgs=pkgs)
def upgrade(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
Upgrades all packages via ``opkg upgrade``
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
errors = []
if salt.utils.data.is_true(refresh):
refresh_db()
old = list_pkgs()
cmd = ['opkg', 'upgrade']
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
errors.append(result)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif state != 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = _set_state(target, 'hold')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif state == 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret['comment'] = ('Package {0} is set not to be held.'
.format(target))
else:
result = _set_state(target, 'ok')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def _get_state(pkg):
'''
View package state from the opkg database
Return the state of pkg
'''
cmd = ['opkg', 'status']
cmd.append(pkg)
out = __salt__['cmd.run'](cmd, python_shell=False)
state_flag = ''
for line in salt.utils.itertools.split(out, '\n'):
if line.startswith('Status'):
_status, _state_want, state_flag, _state_status = line.split()
return state_flag
def _set_state(pkg, state):
'''
Change package state on the opkg database
The state can be any of:
- hold
- noprune
- user
- ok
- installed
- unpacked
This command is commonly used to mark a specific package to be held from
being upgraded, that is, to be kept at a certain version.
Returns a dict containing the package name, and the new and old
versions.
'''
ret = {}
valid_states = ('hold', 'noprune', 'user', 'ok', 'installed', 'unpacked')
if state not in valid_states:
raise SaltInvocationError('Invalid state: {0}'.format(state))
oldstate = _get_state(pkg)
cmd = ['opkg', 'flag']
cmd.append(state)
cmd.append(pkg)
_out = __salt__['cmd.run'](cmd, python_shell=False)
# Missing return value check due to opkg issue 160
ret[pkg] = {'old': oldstate,
'new': state}
return ret
def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
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
cmd = ['opkg', 'list-installed']
ret = {}
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
# This is a continuation of package description
if not line or line[0] == ' ':
continue
# This contains package name, version, and description.
# Extract the first two.
pkg_name, pkg_version = line.split(' - ', 2)[:2]
__salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version)
__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 list_upgrades(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
List all available package upgrades.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
ret = {}
if salt.utils.data.is_true(refresh):
refresh_db()
cmd = ['opkg', 'list-upgradable']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
if 'stdout' in call:
comment += call['stdout']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
name, _oldversion, newversion = line.split(' - ')
ret[name] = newversion
return ret
def _convert_to_standard_attr(attr):
'''
Helper function for _process_info_installed_output()
Converts an opkg attribute name to a standard attribute
name which is used across 'pkg' modules.
'''
ret_attr = ATTR_MAP.get(attr, None)
if ret_attr is None:
# All others convert to lowercase
return attr.lower()
return ret_attr
def _process_info_installed_output(out, filter_attrs):
'''
Helper function for info_installed()
Processes stdout output from a single invocation of
'opkg status'.
'''
ret = {}
name = None
attrs = {}
attr = None
for line in salt.utils.itertools.split(out, '\n'):
if line and line[0] == ' ':
# This is a continuation of the last attr
if filter_attrs is None or attr in filter_attrs:
line = line.strip()
if attrs[attr]:
# If attr is empty, don't add leading newline
attrs[attr] += '\n'
attrs[attr] += line
continue
line = line.strip()
if not line:
# Separator between different packages
if name:
ret[name] = attrs
name = None
attrs = {}
attr = None
continue
key, value = line.split(':', 1)
value = value.lstrip()
attr = _convert_to_standard_attr(key)
if attr == 'name':
name = value
elif filter_attrs is None or attr in filter_attrs:
attrs[attr] = value
if name:
ret[name] = attrs
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
.. versionadded:: 2017.7.0
:param names:
Names of the packages to get information about. If none are specified,
will return information for all installed packages.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
arch, conffiles, conflicts, depends, description, filename, group,
install_date_time_t, md5sum, packager, provides, recommends,
replaces, size, source, suggests, url, version
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed
salt '*' pkg.info_installed attr=version,packager
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> attr=version,packager
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,packager
'''
attr = kwargs.pop('attr', None)
if attr is None:
filter_attrs = None
elif isinstance(attr, six.string_types):
filter_attrs = set(attr.split(','))
else:
filter_attrs = set(attr)
ret = {}
if names:
# Specific list of names of installed packages
for name in names:
cmd = ['opkg', 'status', name]
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
else:
# All installed packages
cmd = ['opkg', 'status']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
return ret
def upgrade_available(name, **kwargs): # pylint: disable=unused-argument
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs): # pylint: disable=unused-argument
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2016.3.4
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0' '0.2.4.1-0'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] if ignore_epoch else six.text_type(x)
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
output = __salt__['cmd.run_stdout'](['opkg', '--version'],
output_loglevel='trace',
python_shell=False)
opkg_version = output.split(' ')[2].strip()
if salt.utils.versions.LooseVersion(opkg_version) >= \
salt.utils.versions.LooseVersion('0.3.4'):
cmd_compare = ['opkg', 'compare-versions']
elif salt.utils.path.which('opkg-compare-versions'):
cmd_compare = ['opkg-compare-versions']
else:
log.warning('Unable to find a compare-versions utility installed. Either upgrade opkg to '
'version > 0.3.4 (preferred) or install the older opkg-compare-versions script.')
return None
for oper, ret in (("<<", -1), ("=", 0), (">>", 1)):
cmd = cmd_compare[:]
cmd.append(_cmd_quote(pkg1))
cmd.append(oper)
cmd.append(_cmd_quote(pkg2))
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
ignore_retcode=True,
python_shell=False)
if retcode == 0:
return ret
return None
def _set_repo_option(repo, option):
'''
Set the option to repo
'''
if not option:
return
opt = option.split('=')
if len(opt) != 2:
return
if opt[0] == 'trusted':
repo['trusted'] = opt[1] == 'yes'
else:
repo[opt[0]] = opt[1]
def _set_repo_options(repo, options):
'''
Set the options to the repo.
'''
delimiters = "[", "]"
pattern = '|'.join(map(re.escape, delimiters))
for option in options:
splitted = re.split(pattern, option)
for opt in splitted:
_set_repo_option(repo, opt)
def _create_repo(line, filename):
'''
Create repo
'''
repo = {}
if line.startswith('#'):
repo['enabled'] = False
line = line[1:]
else:
repo['enabled'] = True
cols = salt.utils.args.shlex_split(line.strip())
repo['compressed'] = not cols[0] in 'src'
repo['name'] = cols[1]
repo['uri'] = cols[2]
repo['file'] = os.path.join(OPKG_CONFDIR, filename)
if len(cols) > 3:
_set_repo_options(repo, cols[3:])
return repo
def _read_repos(conf_file, repos, filename, regex):
'''
Read repos from configuration file
'''
for line in conf_file:
line = salt.utils.stringutils.to_unicode(line)
if not regex.search(line):
continue
repo = _create_repo(line, filename)
# do not store duplicated uri's
if repo['uri'] not in repos:
repos[repo['uri']] = [repo]
def list_repos(**kwargs): # pylint: disable=unused-argument
'''
Lists all repos on ``/etc/opkg/*.conf``
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos = {}
regex = re.compile(REPO_REGEXP)
for filename in os.listdir(OPKG_CONFDIR):
if not filename.endswith(".conf"):
continue
with salt.utils.files.fopen(os.path.join(OPKG_CONFDIR, filename)) as conf_file:
_read_repos(conf_file, repos, filename, regex)
return repos
def get_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Display a repo from the ``/etc/opkg/*.conf``
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo repo
'''
repos = list_repos()
if repos:
for source in six.itervalues(repos):
for sub in source:
if sub['name'] == repo:
return sub
return {}
def _del_repo_from_file(repo, filepath):
'''
Remove a repo from filepath
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
regex = re.compile(REPO_REGEXP)
for line in fhandle:
line = salt.utils.stringutils.to_unicode(line)
if regex.search(line):
if line.startswith('#'):
line = line[1:]
cols = salt.utils.args.shlex_split(line.strip())
if repo != cols[1]:
output.append(salt.utils.stringutils.to_str(line))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def _set_trusted_option_if_needed(repostr, trusted):
'''
Set trusted option to repo if needed
'''
if trusted is True:
repostr += ' [trusted=yes]'
elif trusted is False:
repostr += ' [trusted=no]'
return repostr
def _add_new_repo(repo, properties):
'''
Add a new repo entry
'''
repostr = '# ' if not properties.get('enabled') else ''
repostr += 'src/gz ' if properties.get('compressed') else 'src '
if ' ' in repo:
repostr += '"' + repo + '" '
else:
repostr += repo + ' '
repostr += properties.get('uri')
repostr = _set_trusted_option_if_needed(repostr, properties.get('trusted'))
repostr += '\n'
conffile = os.path.join(OPKG_CONFDIR, repo + '.conf')
with salt.utils.files.fopen(conffile, 'a') as fhandle:
fhandle.write(salt.utils.stringutils.to_str(repostr))
def _mod_repo_in_file(repo, repostr, filepath):
'''
Replace a repo entry in filepath with repostr
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
for line in fhandle:
cols = salt.utils.args.shlex_split(
salt.utils.stringutils.to_unicode(line).strip()
)
if repo not in cols:
output.append(line)
else:
output.append(salt.utils.stringutils.to_str(repostr + '\n'))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def del_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Delete a repo from ``/etc/opkg/*.conf``
If the file does not contain any other repo configuration, the file itself
will be deleted.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo repo
'''
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
repos = list_repos()
if repos:
deleted_from = dict()
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
deleted_from[source['file']] = 0
_del_repo_from_file(repo, source['file'])
if deleted_from:
ret = ''
for repository in repos:
source = repos[repository][0]
if source['file'] in deleted_from:
deleted_from[source['file']] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 1 and os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.\n')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
if refresh:
refresh_db()
return ret
return "Repo {0} doesn't exist in the opkg repo lists".format(repo)
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as uri is defined.
The following options are available to modify a repo definition:
repo
alias by which opkg refers to the repo.
uri
the URI to the repo.
compressed
defines (True or False) if the index file is compressed
enabled
enable or disable (True or False) repository
but do not remove if disabled.
refresh
enable or disable (True or False) auto-refresh of the repositories
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo repo uri=http://new/uri
salt '*' pkg.mod_repo repo enabled=False
'''
repos = list_repos()
found = False
uri = ''
if 'uri' in kwargs:
uri = kwargs['uri']
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
found = True
repostr = ''
if 'enabled' in kwargs and not kwargs['enabled']:
repostr += '# '
if 'compressed' in kwargs:
repostr += 'src/gz ' if kwargs['compressed'] else 'src'
else:
repostr += 'src/gz' if source['compressed'] else 'src'
repo_alias = kwargs['alias'] if 'alias' in kwargs else repo
if ' ' in repo_alias:
repostr += ' "{0}"'.format(repo_alias)
else:
repostr += ' {0}'.format(repo_alias)
repostr += ' {0}'.format(kwargs['uri'] if 'uri' in kwargs else source['uri'])
trusted = kwargs.get('trusted')
repostr = _set_trusted_option_if_needed(repostr, trusted) if trusted is not None else \
_set_trusted_option_if_needed(repostr, source.get('trusted'))
_mod_repo_in_file(repo, repostr, source['file'])
elif uri and source['uri'] == uri:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(uri, source['name']))
if not found:
# Need to add a new repo
if 'uri' not in kwargs:
raise CommandExecutionError(
'Repository \'{0}\' not found and no URI passed to create one.'.format(repo))
properties = {'uri': kwargs['uri']}
# If compressed is not defined, assume True
properties['compressed'] = kwargs['compressed'] if 'compressed' in kwargs else True
# If enabled is not defined, assume True
properties['enabled'] = kwargs['enabled'] if 'enabled' in kwargs else True
properties['trusted'] = kwargs.get('trusted')
_add_new_repo(repo, properties)
if 'refresh' in kwargs:
refresh_db()
def file_list(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
output = file_dict(*packages)
files = []
for package in list(output['packages'].values()):
files.extend(package)
return {'errors': output['errors'], 'files': files}
def file_dict(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
errors = []
ret = {}
cmd_files = ['opkg', 'files']
if not packages:
packages = list(list_pkgs().keys())
for package in packages:
files = []
cmd = cmd_files[:]
cmd.append(package)
out = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
for line in out['stdout'].splitlines():
if line.startswith('/'):
files.append(line)
elif line.startswith(' * '):
errors.append(line[3:])
break
else:
continue
if files:
ret[package] = files
return {'errors': errors, 'packages': ret}
def owner(*paths, **kwargs): # pylint: disable=unused-argument
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.opkg.version`, if a single
path is passed, a string will be returned, and if multiple paths are passed,
a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
cmd_search = ['opkg', 'search']
for path in paths:
cmd = cmd_search[:]
cmd.append(path)
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
if output:
ret[path] = output.split(' - ')[0].strip()
else:
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def version_clean(version):
'''
Clean the version string removing extra data.
There's nothing do to here for nipkg.py, therefore it will always
return the given version.
'''
return version
def check_extra_requirements(pkgname, pkgver):
'''
Check if the installed package already has the given requirements.
There's nothing do to here for nipkg.py, therefore it will always
return True.
'''
return True
|
saltstack/salt
|
salt/modules/opkg.py
|
_process_restartcheck_result
|
python
|
def _process_restartcheck_result(rs_result, **kwargs):
'''
Check restartcheck output to see if system/service restarts were requested
and take appropriate action.
'''
if 'No packages seem to need to be restarted' in rs_result:
return
reboot_required = False
for rstr in rs_result:
if 'System restart required' in rstr:
_update_nilrt_restart_state()
__salt__['system.set_reboot_required_witnessed']()
reboot_required = True
if kwargs.get('always_restart_services', True) or not reboot_required:
for rstr in rs_result:
if 'System restart required' not in rstr:
service = os.path.join('/etc/init.d', rstr)
if os.path.exists(service):
__salt__['cmd.run']([service, 'restart'])
|
Check restartcheck output to see if system/service restarts were requested
and take appropriate action.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/opkg.py#L119-L137
|
[
"def _update_nilrt_restart_state():\n '''\n NILRT systems determine whether to reboot after various package operations\n including but not limited to kernel module installs/removals by checking\n specific file md5sums & timestamps. These files are touched/modified by\n the post-install/post-remove functions of their respective packages.\n\n The opkg module uses this function to store/update those file timestamps\n and checksums to be used later by the restartcheck module.\n\n '''\n __salt__['cmd.shell']('stat -c %Y /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.timestamp'\n .format(NILRT_RESTARTCHECK_STATE_PATH))\n __salt__['cmd.shell']('md5sum /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.md5sum'\n .format(NILRT_RESTARTCHECK_STATE_PATH))\n\n # We can't assume nisysapi.ini always exists like modules.dep\n nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'\n if os.path.exists(nisysapi_path):\n __salt__['cmd.shell']('stat -c %Y {0} >{1}/nisysapi.ini.timestamp'\n .format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))\n __salt__['cmd.shell']('md5sum {0} >{1}/nisysapi.ini.md5sum'\n .format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))\n\n # Expert plugin files get added to a conf.d dir, so keep track of the total\n # no. of files, their timestamps and content hashes\n nisysapi_conf_d_path = \"/usr/lib/{0}/nisysapi/conf.d/experts/\".format(\n 'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'\n )\n\n if os.path.exists(nisysapi_conf_d_path):\n with salt.utils.files.fopen('{0}/sysapi.conf.d.count'.format(\n NILRT_RESTARTCHECK_STATE_PATH), 'w') as fcount:\n fcount.write(str(len(os.listdir(nisysapi_conf_d_path))))\n\n for fexpert in os.listdir(nisysapi_conf_d_path):\n __salt__['cmd.shell']('stat -c %Y {0}/{1} >{2}/{1}.timestamp'\n .format(nisysapi_conf_d_path,\n fexpert,\n NILRT_RESTARTCHECK_STATE_PATH))\n __salt__['cmd.shell']('md5sum {0}/{1} >{2}/{1}.md5sum'\n .format(nisysapi_conf_d_path,\n fexpert,\n NILRT_RESTARTCHECK_STATE_PATH))\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Opkg
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
.. versionadded: 2016.3.0
.. note::
For version comparison support on opkg < 0.3.4, the ``opkg-utils`` package
must be installed.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import os
import re
import logging
import errno
# Import salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.itertools
import salt.utils.path
import salt.utils.pkg
import salt.utils.stringutils
import salt.utils.versions
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import shlex_quote as _cmd_quote # pylint: disable=import-error
from salt.ext.six.moves import map # pylint: disable=import-error,redefined-builtin
REPO_REGEXP = r'^#?\s*(src|src/gz)\s+([^\s<>]+|"[^<>]+")\s+[^\s<>]+'
OPKG_CONFDIR = '/etc/opkg'
ATTR_MAP = {
'Architecture': 'arch',
'Homepage': 'url',
'Installed-Time': 'install_date_time_t',
'Maintainer': 'packager',
'Package': 'name',
'Section': 'group'
}
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
NILRT_RESTARTCHECK_STATE_PATH = '/var/lib/salt/restartcheck_state'
def _update_nilrt_restart_state():
'''
NILRT systems determine whether to reboot after various package operations
including but not limited to kernel module installs/removals by checking
specific file md5sums & timestamps. These files are touched/modified by
the post-install/post-remove functions of their respective packages.
The opkg module uses this function to store/update those file timestamps
and checksums to be used later by the restartcheck module.
'''
__salt__['cmd.shell']('stat -c %Y /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.timestamp'
.format(NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.md5sum'
.format(NILRT_RESTARTCHECK_STATE_PATH))
# We can't assume nisysapi.ini always exists like modules.dep
nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'
if os.path.exists(nisysapi_path):
__salt__['cmd.shell']('stat -c %Y {0} >{1}/nisysapi.ini.timestamp'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0} >{1}/nisysapi.ini.md5sum'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
# Expert plugin files get added to a conf.d dir, so keep track of the total
# no. of files, their timestamps and content hashes
nisysapi_conf_d_path = "/usr/lib/{0}/nisysapi/conf.d/experts/".format(
'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'
)
if os.path.exists(nisysapi_conf_d_path):
with salt.utils.files.fopen('{0}/sysapi.conf.d.count'.format(
NILRT_RESTARTCHECK_STATE_PATH), 'w') as fcount:
fcount.write(str(len(os.listdir(nisysapi_conf_d_path))))
for fexpert in os.listdir(nisysapi_conf_d_path):
__salt__['cmd.shell']('stat -c %Y {0}/{1} >{2}/{1}.timestamp'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0}/{1} >{2}/{1}.md5sum'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
def _get_restartcheck_result(errors):
'''
Return restartcheck result and append errors (if any) to ``errors``
'''
rs_result = __salt__['restartcheck.restartcheck'](verbose=False)
if isinstance(rs_result, dict) and 'comment' in rs_result:
errors.append(rs_result['comment'])
return rs_result
def __virtual__():
'''
Confirm this module is on a nilrt based system
'''
if __grains__.get('os_family') == 'NILinuxRT':
try:
os.makedirs(NILRT_RESTARTCHECK_STATE_PATH)
except OSError as exc:
if exc.errno != errno.EEXIST:
return False, 'Error creating {0} (-{1}): {2}'.format(
NILRT_RESTARTCHECK_STATE_PATH,
exc.errno,
exc.strerror)
# populate state dir if empty
if not os.listdir(NILRT_RESTARTCHECK_STATE_PATH):
_update_nilrt_restart_state()
return __virtualname__
if os.path.isdir(OPKG_CONFDIR):
return __virtualname__
return False, "Module opkg only works on OpenEmbedded based systems"
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
if not names:
return ''
ret = {}
for name in names:
ret[name] = ''
# Refresh before looking for the latest version available
if refresh:
refresh_db()
cmd = ['opkg', 'list-upgradable']
out = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
try:
name, _oldversion, newversion = line.split(' - ')
if name in names:
ret[name] = newversion
except ValueError:
pass
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = latest_version
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(failhard=False, **kwargs): # pylint: disable=unused-argument
'''
Updates the opkg database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
failhard
If False, return results of failed lines as ``False`` for the package
database that encountered the error.
If True, raise an error with a list of the package databases that
encountered errors.
.. versionadded:: 2018.3.0
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
error_repos = []
cmd = ['opkg', 'update']
# opkg returns a non-zero retcode when there is a failure to refresh
# from one or more repos. Due to this, ignore the retcode.
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True,
redirect_stderr=True)
out = call['stdout']
prev_line = ''
for line in salt.utils.itertools.split(out, '\n'):
if 'Inflating' in line:
key = line.strip().split()[1][:-1]
ret[key] = True
elif 'Updated source' in line:
# Use the previous line.
key = prev_line.strip().split()[1][:-1]
ret[key] = True
elif 'Failed to download' in line:
key = line.strip().split()[5].split(',')[0]
ret[key] = False
error_repos.append(key)
prev_line = line
if failhard and error_repos:
raise CommandExecutionError(
'Error getting repos: {0}'.format(', '.join(error_repos))
)
# On a non-zero exit code where no failed repos were found, raise an
# exception because this appears to be a different kind of error.
if call['retcode'] != 0 and not error_repos:
raise CommandExecutionError(out)
return ret
def _is_testmode(**kwargs):
'''
Returns whether a test mode (noaction) operation was requested.
'''
return bool(kwargs.get('test') or __opts__.get('test'))
def _append_noaction_if_testmode(cmd, **kwargs):
'''
Adds the --noaction flag to the command if it's running in the test mode.
'''
if _is_testmode(**kwargs):
cmd.append('--noaction')
def _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall):
'''
Builds a list of install commands to be executed in sequence in order to process
each of the to_install, to_downgrade, and to_reinstall lists.
'''
cmds = []
if to_install:
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(to_install)
cmds.append(cmd)
if to_downgrade:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-downgrade')
cmd.extend(to_downgrade)
cmds.append(cmd)
if to_reinstall:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-reinstall')
cmd.extend(to_reinstall)
cmds.append(cmd)
return cmds
def _parse_reported_packages_from_install_output(output):
'''
Parses the output of "opkg install" to determine what packages would have been
installed by an operation run with the --noaction flag.
We are looking for lines like:
Installing <package> (<version>) on <target>
or
Upgrading <package> from <oldVersion> to <version> on root
'''
reported_pkgs = {}
install_pattern = re.compile(r'Installing\s(?P<package>.*?)\s\((?P<version>.*?)\)\son\s(?P<target>.*?)')
upgrade_pattern = re.compile(r'Upgrading\s(?P<package>.*?)\sfrom\s(?P<oldVersion>.*?)\sto\s(?P<version>.*?)\son\s(?P<target>.*?)')
for line in salt.utils.itertools.split(output, '\n'):
match = install_pattern.match(line)
if match is None:
match = upgrade_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = match.group('version')
return reported_pkgs
def _execute_install_command(cmd, parse_output, errors, parsed_packages):
'''
Executes a command for the install operation.
If the command fails, its error output will be appended to the errors list.
If the command succeeds and parse_output is true, updated packages will be appended
to the parsed_packages dictionary.
'''
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors.append(out['stderr'])
else:
errors.append(out['stdout'])
elif parse_output:
parsed_packages.update(_parse_reported_packages_from_install_output(out['stdout']))
def install(name=None,
refresh=False,
pkgs=None,
sources=None,
reinstall=False,
**kwargs):
'''
Install the passed package, add refresh=True to update the opkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionadded:: 2017.7.0
reinstall : False
Specifying reinstall=True will use ``opkg install --force-reinstall``
rather than simply ``opkg install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``opkg
install --force-reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2017.7.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of IPK packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
install_recommends
Whether to install the packages marked as recommended. Default is True.
only_upgrade
Only upgrade the packages (disallow downgrades), if they are already
installed. Default is False.
.. versionadded:: 2017.7.0
always_restart_services
Whether to restart services even if a reboot is required. Default is True.
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
refreshdb = salt.utils.data.is_true(refresh)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
cmd_prefix = ['opkg', 'install']
to_install = []
to_reinstall = []
to_downgrade = []
_append_noaction_if_testmode(cmd_prefix, **kwargs)
if not pkg_params:
return {}
elif pkg_type == 'file':
if reinstall:
cmd_prefix.append('--force-reinstall')
if not kwargs.get('only_upgrade', False):
cmd_prefix.append('--force-downgrade')
to_install.extend(pkg_params)
elif pkg_type == 'repository':
if not kwargs.get('install_recommends', True):
cmd_prefix.append('--no-install-recommends')
for pkgname, pkgversion in six.iteritems(pkg_params):
if (name and pkgs is None and kwargs.get('version') and
len(pkg_params) == 1):
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
version_num = pkgversion
if version_num is None:
# Don't allow downgrades if the version
# number is not specified.
if reinstall and pkgname in old:
to_reinstall.append(pkgname)
else:
to_install.append(pkgname)
else:
pkgstr = '{0}={1}'.format(pkgname, version_num)
cver = old.get(pkgname, '')
if reinstall and cver and salt.utils.versions.compare(
ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall.append(pkgstr)
elif not cver or salt.utils.versions.compare(
ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
to_install.append(pkgstr)
else:
if not kwargs.get('only_upgrade', False):
to_downgrade.append(pkgstr)
else:
# This should cause the command to fail.
to_install.append(pkgstr)
cmds = _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall)
if not cmds:
return {}
if refreshdb:
refresh_db()
errors = []
is_testmode = _is_testmode(**kwargs)
test_packages = {}
for cmd in cmds:
_execute_install_command(cmd, is_testmode, errors, test_packages)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if is_testmode:
new = copy.deepcopy(new)
new.update(test_packages)
ret = salt.utils.data.compare_dicts(old, new)
if pkg_type == 'file' and reinstall:
# For file-based packages, prepare 'to_reinstall' to have a list
# of all the package names that may have been reinstalled.
# This way, we could include reinstalled packages in 'ret'.
for pkgfile in to_install:
# Convert from file name to package name.
cmd = ['opkg', 'info', pkgfile]
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] == 0:
# Just need the package name.
pkginfo_dict = _process_info_installed_output(
out['stdout'], []
)
if pkginfo_dict:
to_reinstall.append(list(pkginfo_dict.keys())[0])
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def _parse_reported_packages_from_remove_output(output):
'''
Parses the output of "opkg remove" to determine what packages would have been
removed by an operation run with the --noaction flag.
We are looking for lines like
Removing <package> (<version>) from <Target>...
'''
reported_pkgs = {}
remove_pattern = re.compile(r'Removing\s(?P<package>.*?)\s\((?P<version>.*?)\)\sfrom\s(?P<target>.*?)...')
for line in salt.utils.itertools.split(output, '\n'):
match = remove_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = ''
return reported_pkgs
def remove(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Remove packages using ``opkg remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
remove_dependencies
Remove package and all dependencies
.. versionadded:: 2019.2.0
auto_remove_deps
Remove packages that were installed automatically to satisfy dependencies
.. versionadded:: 2019.2.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
salt '*' pkg.remove pkgs='["foo", "bar"]' remove_dependencies=True auto_remove_deps=True
'''
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 {}
cmd = ['opkg', 'remove']
_append_noaction_if_testmode(cmd, **kwargs)
if kwargs.get('remove_dependencies', False):
cmd.append('--force-removal-of-dependent-packages')
if kwargs.get('auto_remove_deps', False):
cmd.append('--autoremove')
cmd.extend(targets)
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors = [out['stderr']]
else:
errors = [out['stdout']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if _is_testmode(**kwargs):
reportedPkgs = _parse_reported_packages_from_remove_output(out['stdout'])
new = {k: v for k, v in new.items() if k not in reportedPkgs}
ret = salt.utils.data.compare_dicts(old, new)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def purge(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Package purges are not supported by opkg, this function is identical to
:mod:`pkg.remove <salt.modules.opkg.remove>`.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name, pkgs=pkgs)
def upgrade(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
Upgrades all packages via ``opkg upgrade``
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
errors = []
if salt.utils.data.is_true(refresh):
refresh_db()
old = list_pkgs()
cmd = ['opkg', 'upgrade']
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
errors.append(result)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif state != 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = _set_state(target, 'hold')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif state == 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret['comment'] = ('Package {0} is set not to be held.'
.format(target))
else:
result = _set_state(target, 'ok')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def _get_state(pkg):
'''
View package state from the opkg database
Return the state of pkg
'''
cmd = ['opkg', 'status']
cmd.append(pkg)
out = __salt__['cmd.run'](cmd, python_shell=False)
state_flag = ''
for line in salt.utils.itertools.split(out, '\n'):
if line.startswith('Status'):
_status, _state_want, state_flag, _state_status = line.split()
return state_flag
def _set_state(pkg, state):
'''
Change package state on the opkg database
The state can be any of:
- hold
- noprune
- user
- ok
- installed
- unpacked
This command is commonly used to mark a specific package to be held from
being upgraded, that is, to be kept at a certain version.
Returns a dict containing the package name, and the new and old
versions.
'''
ret = {}
valid_states = ('hold', 'noprune', 'user', 'ok', 'installed', 'unpacked')
if state not in valid_states:
raise SaltInvocationError('Invalid state: {0}'.format(state))
oldstate = _get_state(pkg)
cmd = ['opkg', 'flag']
cmd.append(state)
cmd.append(pkg)
_out = __salt__['cmd.run'](cmd, python_shell=False)
# Missing return value check due to opkg issue 160
ret[pkg] = {'old': oldstate,
'new': state}
return ret
def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
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
cmd = ['opkg', 'list-installed']
ret = {}
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
# This is a continuation of package description
if not line or line[0] == ' ':
continue
# This contains package name, version, and description.
# Extract the first two.
pkg_name, pkg_version = line.split(' - ', 2)[:2]
__salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version)
__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 list_upgrades(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
List all available package upgrades.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
ret = {}
if salt.utils.data.is_true(refresh):
refresh_db()
cmd = ['opkg', 'list-upgradable']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
if 'stdout' in call:
comment += call['stdout']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
name, _oldversion, newversion = line.split(' - ')
ret[name] = newversion
return ret
def _convert_to_standard_attr(attr):
'''
Helper function for _process_info_installed_output()
Converts an opkg attribute name to a standard attribute
name which is used across 'pkg' modules.
'''
ret_attr = ATTR_MAP.get(attr, None)
if ret_attr is None:
# All others convert to lowercase
return attr.lower()
return ret_attr
def _process_info_installed_output(out, filter_attrs):
'''
Helper function for info_installed()
Processes stdout output from a single invocation of
'opkg status'.
'''
ret = {}
name = None
attrs = {}
attr = None
for line in salt.utils.itertools.split(out, '\n'):
if line and line[0] == ' ':
# This is a continuation of the last attr
if filter_attrs is None or attr in filter_attrs:
line = line.strip()
if attrs[attr]:
# If attr is empty, don't add leading newline
attrs[attr] += '\n'
attrs[attr] += line
continue
line = line.strip()
if not line:
# Separator between different packages
if name:
ret[name] = attrs
name = None
attrs = {}
attr = None
continue
key, value = line.split(':', 1)
value = value.lstrip()
attr = _convert_to_standard_attr(key)
if attr == 'name':
name = value
elif filter_attrs is None or attr in filter_attrs:
attrs[attr] = value
if name:
ret[name] = attrs
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
.. versionadded:: 2017.7.0
:param names:
Names of the packages to get information about. If none are specified,
will return information for all installed packages.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
arch, conffiles, conflicts, depends, description, filename, group,
install_date_time_t, md5sum, packager, provides, recommends,
replaces, size, source, suggests, url, version
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed
salt '*' pkg.info_installed attr=version,packager
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> attr=version,packager
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,packager
'''
attr = kwargs.pop('attr', None)
if attr is None:
filter_attrs = None
elif isinstance(attr, six.string_types):
filter_attrs = set(attr.split(','))
else:
filter_attrs = set(attr)
ret = {}
if names:
# Specific list of names of installed packages
for name in names:
cmd = ['opkg', 'status', name]
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
else:
# All installed packages
cmd = ['opkg', 'status']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
return ret
def upgrade_available(name, **kwargs): # pylint: disable=unused-argument
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs): # pylint: disable=unused-argument
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2016.3.4
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0' '0.2.4.1-0'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] if ignore_epoch else six.text_type(x)
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
output = __salt__['cmd.run_stdout'](['opkg', '--version'],
output_loglevel='trace',
python_shell=False)
opkg_version = output.split(' ')[2].strip()
if salt.utils.versions.LooseVersion(opkg_version) >= \
salt.utils.versions.LooseVersion('0.3.4'):
cmd_compare = ['opkg', 'compare-versions']
elif salt.utils.path.which('opkg-compare-versions'):
cmd_compare = ['opkg-compare-versions']
else:
log.warning('Unable to find a compare-versions utility installed. Either upgrade opkg to '
'version > 0.3.4 (preferred) or install the older opkg-compare-versions script.')
return None
for oper, ret in (("<<", -1), ("=", 0), (">>", 1)):
cmd = cmd_compare[:]
cmd.append(_cmd_quote(pkg1))
cmd.append(oper)
cmd.append(_cmd_quote(pkg2))
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
ignore_retcode=True,
python_shell=False)
if retcode == 0:
return ret
return None
def _set_repo_option(repo, option):
'''
Set the option to repo
'''
if not option:
return
opt = option.split('=')
if len(opt) != 2:
return
if opt[0] == 'trusted':
repo['trusted'] = opt[1] == 'yes'
else:
repo[opt[0]] = opt[1]
def _set_repo_options(repo, options):
'''
Set the options to the repo.
'''
delimiters = "[", "]"
pattern = '|'.join(map(re.escape, delimiters))
for option in options:
splitted = re.split(pattern, option)
for opt in splitted:
_set_repo_option(repo, opt)
def _create_repo(line, filename):
'''
Create repo
'''
repo = {}
if line.startswith('#'):
repo['enabled'] = False
line = line[1:]
else:
repo['enabled'] = True
cols = salt.utils.args.shlex_split(line.strip())
repo['compressed'] = not cols[0] in 'src'
repo['name'] = cols[1]
repo['uri'] = cols[2]
repo['file'] = os.path.join(OPKG_CONFDIR, filename)
if len(cols) > 3:
_set_repo_options(repo, cols[3:])
return repo
def _read_repos(conf_file, repos, filename, regex):
'''
Read repos from configuration file
'''
for line in conf_file:
line = salt.utils.stringutils.to_unicode(line)
if not regex.search(line):
continue
repo = _create_repo(line, filename)
# do not store duplicated uri's
if repo['uri'] not in repos:
repos[repo['uri']] = [repo]
def list_repos(**kwargs): # pylint: disable=unused-argument
'''
Lists all repos on ``/etc/opkg/*.conf``
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos = {}
regex = re.compile(REPO_REGEXP)
for filename in os.listdir(OPKG_CONFDIR):
if not filename.endswith(".conf"):
continue
with salt.utils.files.fopen(os.path.join(OPKG_CONFDIR, filename)) as conf_file:
_read_repos(conf_file, repos, filename, regex)
return repos
def get_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Display a repo from the ``/etc/opkg/*.conf``
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo repo
'''
repos = list_repos()
if repos:
for source in six.itervalues(repos):
for sub in source:
if sub['name'] == repo:
return sub
return {}
def _del_repo_from_file(repo, filepath):
'''
Remove a repo from filepath
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
regex = re.compile(REPO_REGEXP)
for line in fhandle:
line = salt.utils.stringutils.to_unicode(line)
if regex.search(line):
if line.startswith('#'):
line = line[1:]
cols = salt.utils.args.shlex_split(line.strip())
if repo != cols[1]:
output.append(salt.utils.stringutils.to_str(line))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def _set_trusted_option_if_needed(repostr, trusted):
'''
Set trusted option to repo if needed
'''
if trusted is True:
repostr += ' [trusted=yes]'
elif trusted is False:
repostr += ' [trusted=no]'
return repostr
def _add_new_repo(repo, properties):
'''
Add a new repo entry
'''
repostr = '# ' if not properties.get('enabled') else ''
repostr += 'src/gz ' if properties.get('compressed') else 'src '
if ' ' in repo:
repostr += '"' + repo + '" '
else:
repostr += repo + ' '
repostr += properties.get('uri')
repostr = _set_trusted_option_if_needed(repostr, properties.get('trusted'))
repostr += '\n'
conffile = os.path.join(OPKG_CONFDIR, repo + '.conf')
with salt.utils.files.fopen(conffile, 'a') as fhandle:
fhandle.write(salt.utils.stringutils.to_str(repostr))
def _mod_repo_in_file(repo, repostr, filepath):
'''
Replace a repo entry in filepath with repostr
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
for line in fhandle:
cols = salt.utils.args.shlex_split(
salt.utils.stringutils.to_unicode(line).strip()
)
if repo not in cols:
output.append(line)
else:
output.append(salt.utils.stringutils.to_str(repostr + '\n'))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def del_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Delete a repo from ``/etc/opkg/*.conf``
If the file does not contain any other repo configuration, the file itself
will be deleted.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo repo
'''
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
repos = list_repos()
if repos:
deleted_from = dict()
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
deleted_from[source['file']] = 0
_del_repo_from_file(repo, source['file'])
if deleted_from:
ret = ''
for repository in repos:
source = repos[repository][0]
if source['file'] in deleted_from:
deleted_from[source['file']] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 1 and os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.\n')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
if refresh:
refresh_db()
return ret
return "Repo {0} doesn't exist in the opkg repo lists".format(repo)
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as uri is defined.
The following options are available to modify a repo definition:
repo
alias by which opkg refers to the repo.
uri
the URI to the repo.
compressed
defines (True or False) if the index file is compressed
enabled
enable or disable (True or False) repository
but do not remove if disabled.
refresh
enable or disable (True or False) auto-refresh of the repositories
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo repo uri=http://new/uri
salt '*' pkg.mod_repo repo enabled=False
'''
repos = list_repos()
found = False
uri = ''
if 'uri' in kwargs:
uri = kwargs['uri']
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
found = True
repostr = ''
if 'enabled' in kwargs and not kwargs['enabled']:
repostr += '# '
if 'compressed' in kwargs:
repostr += 'src/gz ' if kwargs['compressed'] else 'src'
else:
repostr += 'src/gz' if source['compressed'] else 'src'
repo_alias = kwargs['alias'] if 'alias' in kwargs else repo
if ' ' in repo_alias:
repostr += ' "{0}"'.format(repo_alias)
else:
repostr += ' {0}'.format(repo_alias)
repostr += ' {0}'.format(kwargs['uri'] if 'uri' in kwargs else source['uri'])
trusted = kwargs.get('trusted')
repostr = _set_trusted_option_if_needed(repostr, trusted) if trusted is not None else \
_set_trusted_option_if_needed(repostr, source.get('trusted'))
_mod_repo_in_file(repo, repostr, source['file'])
elif uri and source['uri'] == uri:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(uri, source['name']))
if not found:
# Need to add a new repo
if 'uri' not in kwargs:
raise CommandExecutionError(
'Repository \'{0}\' not found and no URI passed to create one.'.format(repo))
properties = {'uri': kwargs['uri']}
# If compressed is not defined, assume True
properties['compressed'] = kwargs['compressed'] if 'compressed' in kwargs else True
# If enabled is not defined, assume True
properties['enabled'] = kwargs['enabled'] if 'enabled' in kwargs else True
properties['trusted'] = kwargs.get('trusted')
_add_new_repo(repo, properties)
if 'refresh' in kwargs:
refresh_db()
def file_list(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
output = file_dict(*packages)
files = []
for package in list(output['packages'].values()):
files.extend(package)
return {'errors': output['errors'], 'files': files}
def file_dict(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
errors = []
ret = {}
cmd_files = ['opkg', 'files']
if not packages:
packages = list(list_pkgs().keys())
for package in packages:
files = []
cmd = cmd_files[:]
cmd.append(package)
out = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
for line in out['stdout'].splitlines():
if line.startswith('/'):
files.append(line)
elif line.startswith(' * '):
errors.append(line[3:])
break
else:
continue
if files:
ret[package] = files
return {'errors': errors, 'packages': ret}
def owner(*paths, **kwargs): # pylint: disable=unused-argument
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.opkg.version`, if a single
path is passed, a string will be returned, and if multiple paths are passed,
a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
cmd_search = ['opkg', 'search']
for path in paths:
cmd = cmd_search[:]
cmd.append(path)
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
if output:
ret[path] = output.split(' - ')[0].strip()
else:
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def version_clean(version):
'''
Clean the version string removing extra data.
There's nothing do to here for nipkg.py, therefore it will always
return the given version.
'''
return version
def check_extra_requirements(pkgname, pkgver):
'''
Check if the installed package already has the given requirements.
There's nothing do to here for nipkg.py, therefore it will always
return True.
'''
return True
|
saltstack/salt
|
salt/modules/opkg.py
|
refresh_db
|
python
|
def refresh_db(failhard=False, **kwargs): # pylint: disable=unused-argument
'''
Updates the opkg database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
failhard
If False, return results of failed lines as ``False`` for the package
database that encountered the error.
If True, raise an error with a list of the package databases that
encountered errors.
.. versionadded:: 2018.3.0
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
error_repos = []
cmd = ['opkg', 'update']
# opkg returns a non-zero retcode when there is a failure to refresh
# from one or more repos. Due to this, ignore the retcode.
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True,
redirect_stderr=True)
out = call['stdout']
prev_line = ''
for line in salt.utils.itertools.split(out, '\n'):
if 'Inflating' in line:
key = line.strip().split()[1][:-1]
ret[key] = True
elif 'Updated source' in line:
# Use the previous line.
key = prev_line.strip().split()[1][:-1]
ret[key] = True
elif 'Failed to download' in line:
key = line.strip().split()[5].split(',')[0]
ret[key] = False
error_repos.append(key)
prev_line = line
if failhard and error_repos:
raise CommandExecutionError(
'Error getting repos: {0}'.format(', '.join(error_repos))
)
# On a non-zero exit code where no failed repos were found, raise an
# exception because this appears to be a different kind of error.
if call['retcode'] != 0 and not error_repos:
raise CommandExecutionError(out)
return ret
|
Updates the opkg database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
failhard
If False, return results of failed lines as ``False`` for the package
database that encountered the error.
If True, raise an error with a list of the package databases that
encountered errors.
.. versionadded:: 2018.3.0
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/opkg.py#L231-L294
|
[
"def split(orig, sep=None):\n '''\n Generator function for iterating through large strings, particularly useful\n as a replacement for str.splitlines().\n\n See http://stackoverflow.com/a/3865367\n '''\n exp = re.compile(r'\\s+' if sep is None else re.escape(sep))\n pos = 0\n length = len(orig)\n while True:\n match = exp.search(orig, pos)\n if not match:\n if pos < length or sep is not None:\n val = orig[pos:]\n if val:\n # Only yield a value if the slice was not an empty string,\n # because if it is then we've reached the end. This keeps\n # us from yielding an extra blank value at the end.\n yield val\n break\n if pos < match.start() or sep is not None:\n yield orig[pos:match.start()]\n pos = match.end()\n",
"def clear_rtag(opts):\n '''\n Remove the rtag file\n '''\n try:\n os.remove(rtag(opts))\n except OSError as exc:\n if exc.errno != errno.ENOENT:\n # Using __str__() here to get the fully-formatted error message\n # (error number, error message, path)\n log.warning('Encountered error removing rtag: %s', exc.__str__())\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Opkg
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
.. versionadded: 2016.3.0
.. note::
For version comparison support on opkg < 0.3.4, the ``opkg-utils`` package
must be installed.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import os
import re
import logging
import errno
# Import salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.itertools
import salt.utils.path
import salt.utils.pkg
import salt.utils.stringutils
import salt.utils.versions
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import shlex_quote as _cmd_quote # pylint: disable=import-error
from salt.ext.six.moves import map # pylint: disable=import-error,redefined-builtin
REPO_REGEXP = r'^#?\s*(src|src/gz)\s+([^\s<>]+|"[^<>]+")\s+[^\s<>]+'
OPKG_CONFDIR = '/etc/opkg'
ATTR_MAP = {
'Architecture': 'arch',
'Homepage': 'url',
'Installed-Time': 'install_date_time_t',
'Maintainer': 'packager',
'Package': 'name',
'Section': 'group'
}
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
NILRT_RESTARTCHECK_STATE_PATH = '/var/lib/salt/restartcheck_state'
def _update_nilrt_restart_state():
'''
NILRT systems determine whether to reboot after various package operations
including but not limited to kernel module installs/removals by checking
specific file md5sums & timestamps. These files are touched/modified by
the post-install/post-remove functions of their respective packages.
The opkg module uses this function to store/update those file timestamps
and checksums to be used later by the restartcheck module.
'''
__salt__['cmd.shell']('stat -c %Y /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.timestamp'
.format(NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.md5sum'
.format(NILRT_RESTARTCHECK_STATE_PATH))
# We can't assume nisysapi.ini always exists like modules.dep
nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'
if os.path.exists(nisysapi_path):
__salt__['cmd.shell']('stat -c %Y {0} >{1}/nisysapi.ini.timestamp'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0} >{1}/nisysapi.ini.md5sum'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
# Expert plugin files get added to a conf.d dir, so keep track of the total
# no. of files, their timestamps and content hashes
nisysapi_conf_d_path = "/usr/lib/{0}/nisysapi/conf.d/experts/".format(
'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'
)
if os.path.exists(nisysapi_conf_d_path):
with salt.utils.files.fopen('{0}/sysapi.conf.d.count'.format(
NILRT_RESTARTCHECK_STATE_PATH), 'w') as fcount:
fcount.write(str(len(os.listdir(nisysapi_conf_d_path))))
for fexpert in os.listdir(nisysapi_conf_d_path):
__salt__['cmd.shell']('stat -c %Y {0}/{1} >{2}/{1}.timestamp'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0}/{1} >{2}/{1}.md5sum'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
def _get_restartcheck_result(errors):
'''
Return restartcheck result and append errors (if any) to ``errors``
'''
rs_result = __salt__['restartcheck.restartcheck'](verbose=False)
if isinstance(rs_result, dict) and 'comment' in rs_result:
errors.append(rs_result['comment'])
return rs_result
def _process_restartcheck_result(rs_result, **kwargs):
'''
Check restartcheck output to see if system/service restarts were requested
and take appropriate action.
'''
if 'No packages seem to need to be restarted' in rs_result:
return
reboot_required = False
for rstr in rs_result:
if 'System restart required' in rstr:
_update_nilrt_restart_state()
__salt__['system.set_reboot_required_witnessed']()
reboot_required = True
if kwargs.get('always_restart_services', True) or not reboot_required:
for rstr in rs_result:
if 'System restart required' not in rstr:
service = os.path.join('/etc/init.d', rstr)
if os.path.exists(service):
__salt__['cmd.run']([service, 'restart'])
def __virtual__():
'''
Confirm this module is on a nilrt based system
'''
if __grains__.get('os_family') == 'NILinuxRT':
try:
os.makedirs(NILRT_RESTARTCHECK_STATE_PATH)
except OSError as exc:
if exc.errno != errno.EEXIST:
return False, 'Error creating {0} (-{1}): {2}'.format(
NILRT_RESTARTCHECK_STATE_PATH,
exc.errno,
exc.strerror)
# populate state dir if empty
if not os.listdir(NILRT_RESTARTCHECK_STATE_PATH):
_update_nilrt_restart_state()
return __virtualname__
if os.path.isdir(OPKG_CONFDIR):
return __virtualname__
return False, "Module opkg only works on OpenEmbedded based systems"
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
if not names:
return ''
ret = {}
for name in names:
ret[name] = ''
# Refresh before looking for the latest version available
if refresh:
refresh_db()
cmd = ['opkg', 'list-upgradable']
out = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
try:
name, _oldversion, newversion = line.split(' - ')
if name in names:
ret[name] = newversion
except ValueError:
pass
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = latest_version
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def _is_testmode(**kwargs):
'''
Returns whether a test mode (noaction) operation was requested.
'''
return bool(kwargs.get('test') or __opts__.get('test'))
def _append_noaction_if_testmode(cmd, **kwargs):
'''
Adds the --noaction flag to the command if it's running in the test mode.
'''
if _is_testmode(**kwargs):
cmd.append('--noaction')
def _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall):
'''
Builds a list of install commands to be executed in sequence in order to process
each of the to_install, to_downgrade, and to_reinstall lists.
'''
cmds = []
if to_install:
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(to_install)
cmds.append(cmd)
if to_downgrade:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-downgrade')
cmd.extend(to_downgrade)
cmds.append(cmd)
if to_reinstall:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-reinstall')
cmd.extend(to_reinstall)
cmds.append(cmd)
return cmds
def _parse_reported_packages_from_install_output(output):
'''
Parses the output of "opkg install" to determine what packages would have been
installed by an operation run with the --noaction flag.
We are looking for lines like:
Installing <package> (<version>) on <target>
or
Upgrading <package> from <oldVersion> to <version> on root
'''
reported_pkgs = {}
install_pattern = re.compile(r'Installing\s(?P<package>.*?)\s\((?P<version>.*?)\)\son\s(?P<target>.*?)')
upgrade_pattern = re.compile(r'Upgrading\s(?P<package>.*?)\sfrom\s(?P<oldVersion>.*?)\sto\s(?P<version>.*?)\son\s(?P<target>.*?)')
for line in salt.utils.itertools.split(output, '\n'):
match = install_pattern.match(line)
if match is None:
match = upgrade_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = match.group('version')
return reported_pkgs
def _execute_install_command(cmd, parse_output, errors, parsed_packages):
'''
Executes a command for the install operation.
If the command fails, its error output will be appended to the errors list.
If the command succeeds and parse_output is true, updated packages will be appended
to the parsed_packages dictionary.
'''
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors.append(out['stderr'])
else:
errors.append(out['stdout'])
elif parse_output:
parsed_packages.update(_parse_reported_packages_from_install_output(out['stdout']))
def install(name=None,
refresh=False,
pkgs=None,
sources=None,
reinstall=False,
**kwargs):
'''
Install the passed package, add refresh=True to update the opkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionadded:: 2017.7.0
reinstall : False
Specifying reinstall=True will use ``opkg install --force-reinstall``
rather than simply ``opkg install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``opkg
install --force-reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2017.7.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of IPK packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
install_recommends
Whether to install the packages marked as recommended. Default is True.
only_upgrade
Only upgrade the packages (disallow downgrades), if they are already
installed. Default is False.
.. versionadded:: 2017.7.0
always_restart_services
Whether to restart services even if a reboot is required. Default is True.
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
refreshdb = salt.utils.data.is_true(refresh)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
cmd_prefix = ['opkg', 'install']
to_install = []
to_reinstall = []
to_downgrade = []
_append_noaction_if_testmode(cmd_prefix, **kwargs)
if not pkg_params:
return {}
elif pkg_type == 'file':
if reinstall:
cmd_prefix.append('--force-reinstall')
if not kwargs.get('only_upgrade', False):
cmd_prefix.append('--force-downgrade')
to_install.extend(pkg_params)
elif pkg_type == 'repository':
if not kwargs.get('install_recommends', True):
cmd_prefix.append('--no-install-recommends')
for pkgname, pkgversion in six.iteritems(pkg_params):
if (name and pkgs is None and kwargs.get('version') and
len(pkg_params) == 1):
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
version_num = pkgversion
if version_num is None:
# Don't allow downgrades if the version
# number is not specified.
if reinstall and pkgname in old:
to_reinstall.append(pkgname)
else:
to_install.append(pkgname)
else:
pkgstr = '{0}={1}'.format(pkgname, version_num)
cver = old.get(pkgname, '')
if reinstall and cver and salt.utils.versions.compare(
ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall.append(pkgstr)
elif not cver or salt.utils.versions.compare(
ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
to_install.append(pkgstr)
else:
if not kwargs.get('only_upgrade', False):
to_downgrade.append(pkgstr)
else:
# This should cause the command to fail.
to_install.append(pkgstr)
cmds = _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall)
if not cmds:
return {}
if refreshdb:
refresh_db()
errors = []
is_testmode = _is_testmode(**kwargs)
test_packages = {}
for cmd in cmds:
_execute_install_command(cmd, is_testmode, errors, test_packages)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if is_testmode:
new = copy.deepcopy(new)
new.update(test_packages)
ret = salt.utils.data.compare_dicts(old, new)
if pkg_type == 'file' and reinstall:
# For file-based packages, prepare 'to_reinstall' to have a list
# of all the package names that may have been reinstalled.
# This way, we could include reinstalled packages in 'ret'.
for pkgfile in to_install:
# Convert from file name to package name.
cmd = ['opkg', 'info', pkgfile]
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] == 0:
# Just need the package name.
pkginfo_dict = _process_info_installed_output(
out['stdout'], []
)
if pkginfo_dict:
to_reinstall.append(list(pkginfo_dict.keys())[0])
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def _parse_reported_packages_from_remove_output(output):
'''
Parses the output of "opkg remove" to determine what packages would have been
removed by an operation run with the --noaction flag.
We are looking for lines like
Removing <package> (<version>) from <Target>...
'''
reported_pkgs = {}
remove_pattern = re.compile(r'Removing\s(?P<package>.*?)\s\((?P<version>.*?)\)\sfrom\s(?P<target>.*?)...')
for line in salt.utils.itertools.split(output, '\n'):
match = remove_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = ''
return reported_pkgs
def remove(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Remove packages using ``opkg remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
remove_dependencies
Remove package and all dependencies
.. versionadded:: 2019.2.0
auto_remove_deps
Remove packages that were installed automatically to satisfy dependencies
.. versionadded:: 2019.2.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
salt '*' pkg.remove pkgs='["foo", "bar"]' remove_dependencies=True auto_remove_deps=True
'''
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 {}
cmd = ['opkg', 'remove']
_append_noaction_if_testmode(cmd, **kwargs)
if kwargs.get('remove_dependencies', False):
cmd.append('--force-removal-of-dependent-packages')
if kwargs.get('auto_remove_deps', False):
cmd.append('--autoremove')
cmd.extend(targets)
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors = [out['stderr']]
else:
errors = [out['stdout']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if _is_testmode(**kwargs):
reportedPkgs = _parse_reported_packages_from_remove_output(out['stdout'])
new = {k: v for k, v in new.items() if k not in reportedPkgs}
ret = salt.utils.data.compare_dicts(old, new)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def purge(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Package purges are not supported by opkg, this function is identical to
:mod:`pkg.remove <salt.modules.opkg.remove>`.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name, pkgs=pkgs)
def upgrade(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
Upgrades all packages via ``opkg upgrade``
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
errors = []
if salt.utils.data.is_true(refresh):
refresh_db()
old = list_pkgs()
cmd = ['opkg', 'upgrade']
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
errors.append(result)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif state != 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = _set_state(target, 'hold')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif state == 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret['comment'] = ('Package {0} is set not to be held.'
.format(target))
else:
result = _set_state(target, 'ok')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def _get_state(pkg):
'''
View package state from the opkg database
Return the state of pkg
'''
cmd = ['opkg', 'status']
cmd.append(pkg)
out = __salt__['cmd.run'](cmd, python_shell=False)
state_flag = ''
for line in salt.utils.itertools.split(out, '\n'):
if line.startswith('Status'):
_status, _state_want, state_flag, _state_status = line.split()
return state_flag
def _set_state(pkg, state):
'''
Change package state on the opkg database
The state can be any of:
- hold
- noprune
- user
- ok
- installed
- unpacked
This command is commonly used to mark a specific package to be held from
being upgraded, that is, to be kept at a certain version.
Returns a dict containing the package name, and the new and old
versions.
'''
ret = {}
valid_states = ('hold', 'noprune', 'user', 'ok', 'installed', 'unpacked')
if state not in valid_states:
raise SaltInvocationError('Invalid state: {0}'.format(state))
oldstate = _get_state(pkg)
cmd = ['opkg', 'flag']
cmd.append(state)
cmd.append(pkg)
_out = __salt__['cmd.run'](cmd, python_shell=False)
# Missing return value check due to opkg issue 160
ret[pkg] = {'old': oldstate,
'new': state}
return ret
def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
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
cmd = ['opkg', 'list-installed']
ret = {}
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
# This is a continuation of package description
if not line or line[0] == ' ':
continue
# This contains package name, version, and description.
# Extract the first two.
pkg_name, pkg_version = line.split(' - ', 2)[:2]
__salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version)
__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 list_upgrades(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
List all available package upgrades.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
ret = {}
if salt.utils.data.is_true(refresh):
refresh_db()
cmd = ['opkg', 'list-upgradable']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
if 'stdout' in call:
comment += call['stdout']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
name, _oldversion, newversion = line.split(' - ')
ret[name] = newversion
return ret
def _convert_to_standard_attr(attr):
'''
Helper function for _process_info_installed_output()
Converts an opkg attribute name to a standard attribute
name which is used across 'pkg' modules.
'''
ret_attr = ATTR_MAP.get(attr, None)
if ret_attr is None:
# All others convert to lowercase
return attr.lower()
return ret_attr
def _process_info_installed_output(out, filter_attrs):
'''
Helper function for info_installed()
Processes stdout output from a single invocation of
'opkg status'.
'''
ret = {}
name = None
attrs = {}
attr = None
for line in salt.utils.itertools.split(out, '\n'):
if line and line[0] == ' ':
# This is a continuation of the last attr
if filter_attrs is None or attr in filter_attrs:
line = line.strip()
if attrs[attr]:
# If attr is empty, don't add leading newline
attrs[attr] += '\n'
attrs[attr] += line
continue
line = line.strip()
if not line:
# Separator between different packages
if name:
ret[name] = attrs
name = None
attrs = {}
attr = None
continue
key, value = line.split(':', 1)
value = value.lstrip()
attr = _convert_to_standard_attr(key)
if attr == 'name':
name = value
elif filter_attrs is None or attr in filter_attrs:
attrs[attr] = value
if name:
ret[name] = attrs
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
.. versionadded:: 2017.7.0
:param names:
Names of the packages to get information about. If none are specified,
will return information for all installed packages.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
arch, conffiles, conflicts, depends, description, filename, group,
install_date_time_t, md5sum, packager, provides, recommends,
replaces, size, source, suggests, url, version
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed
salt '*' pkg.info_installed attr=version,packager
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> attr=version,packager
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,packager
'''
attr = kwargs.pop('attr', None)
if attr is None:
filter_attrs = None
elif isinstance(attr, six.string_types):
filter_attrs = set(attr.split(','))
else:
filter_attrs = set(attr)
ret = {}
if names:
# Specific list of names of installed packages
for name in names:
cmd = ['opkg', 'status', name]
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
else:
# All installed packages
cmd = ['opkg', 'status']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
return ret
def upgrade_available(name, **kwargs): # pylint: disable=unused-argument
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs): # pylint: disable=unused-argument
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2016.3.4
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0' '0.2.4.1-0'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] if ignore_epoch else six.text_type(x)
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
output = __salt__['cmd.run_stdout'](['opkg', '--version'],
output_loglevel='trace',
python_shell=False)
opkg_version = output.split(' ')[2].strip()
if salt.utils.versions.LooseVersion(opkg_version) >= \
salt.utils.versions.LooseVersion('0.3.4'):
cmd_compare = ['opkg', 'compare-versions']
elif salt.utils.path.which('opkg-compare-versions'):
cmd_compare = ['opkg-compare-versions']
else:
log.warning('Unable to find a compare-versions utility installed. Either upgrade opkg to '
'version > 0.3.4 (preferred) or install the older opkg-compare-versions script.')
return None
for oper, ret in (("<<", -1), ("=", 0), (">>", 1)):
cmd = cmd_compare[:]
cmd.append(_cmd_quote(pkg1))
cmd.append(oper)
cmd.append(_cmd_quote(pkg2))
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
ignore_retcode=True,
python_shell=False)
if retcode == 0:
return ret
return None
def _set_repo_option(repo, option):
'''
Set the option to repo
'''
if not option:
return
opt = option.split('=')
if len(opt) != 2:
return
if opt[0] == 'trusted':
repo['trusted'] = opt[1] == 'yes'
else:
repo[opt[0]] = opt[1]
def _set_repo_options(repo, options):
'''
Set the options to the repo.
'''
delimiters = "[", "]"
pattern = '|'.join(map(re.escape, delimiters))
for option in options:
splitted = re.split(pattern, option)
for opt in splitted:
_set_repo_option(repo, opt)
def _create_repo(line, filename):
'''
Create repo
'''
repo = {}
if line.startswith('#'):
repo['enabled'] = False
line = line[1:]
else:
repo['enabled'] = True
cols = salt.utils.args.shlex_split(line.strip())
repo['compressed'] = not cols[0] in 'src'
repo['name'] = cols[1]
repo['uri'] = cols[2]
repo['file'] = os.path.join(OPKG_CONFDIR, filename)
if len(cols) > 3:
_set_repo_options(repo, cols[3:])
return repo
def _read_repos(conf_file, repos, filename, regex):
'''
Read repos from configuration file
'''
for line in conf_file:
line = salt.utils.stringutils.to_unicode(line)
if not regex.search(line):
continue
repo = _create_repo(line, filename)
# do not store duplicated uri's
if repo['uri'] not in repos:
repos[repo['uri']] = [repo]
def list_repos(**kwargs): # pylint: disable=unused-argument
'''
Lists all repos on ``/etc/opkg/*.conf``
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos = {}
regex = re.compile(REPO_REGEXP)
for filename in os.listdir(OPKG_CONFDIR):
if not filename.endswith(".conf"):
continue
with salt.utils.files.fopen(os.path.join(OPKG_CONFDIR, filename)) as conf_file:
_read_repos(conf_file, repos, filename, regex)
return repos
def get_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Display a repo from the ``/etc/opkg/*.conf``
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo repo
'''
repos = list_repos()
if repos:
for source in six.itervalues(repos):
for sub in source:
if sub['name'] == repo:
return sub
return {}
def _del_repo_from_file(repo, filepath):
'''
Remove a repo from filepath
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
regex = re.compile(REPO_REGEXP)
for line in fhandle:
line = salt.utils.stringutils.to_unicode(line)
if regex.search(line):
if line.startswith('#'):
line = line[1:]
cols = salt.utils.args.shlex_split(line.strip())
if repo != cols[1]:
output.append(salt.utils.stringutils.to_str(line))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def _set_trusted_option_if_needed(repostr, trusted):
'''
Set trusted option to repo if needed
'''
if trusted is True:
repostr += ' [trusted=yes]'
elif trusted is False:
repostr += ' [trusted=no]'
return repostr
def _add_new_repo(repo, properties):
'''
Add a new repo entry
'''
repostr = '# ' if not properties.get('enabled') else ''
repostr += 'src/gz ' if properties.get('compressed') else 'src '
if ' ' in repo:
repostr += '"' + repo + '" '
else:
repostr += repo + ' '
repostr += properties.get('uri')
repostr = _set_trusted_option_if_needed(repostr, properties.get('trusted'))
repostr += '\n'
conffile = os.path.join(OPKG_CONFDIR, repo + '.conf')
with salt.utils.files.fopen(conffile, 'a') as fhandle:
fhandle.write(salt.utils.stringutils.to_str(repostr))
def _mod_repo_in_file(repo, repostr, filepath):
'''
Replace a repo entry in filepath with repostr
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
for line in fhandle:
cols = salt.utils.args.shlex_split(
salt.utils.stringutils.to_unicode(line).strip()
)
if repo not in cols:
output.append(line)
else:
output.append(salt.utils.stringutils.to_str(repostr + '\n'))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def del_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Delete a repo from ``/etc/opkg/*.conf``
If the file does not contain any other repo configuration, the file itself
will be deleted.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo repo
'''
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
repos = list_repos()
if repos:
deleted_from = dict()
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
deleted_from[source['file']] = 0
_del_repo_from_file(repo, source['file'])
if deleted_from:
ret = ''
for repository in repos:
source = repos[repository][0]
if source['file'] in deleted_from:
deleted_from[source['file']] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 1 and os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.\n')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
if refresh:
refresh_db()
return ret
return "Repo {0} doesn't exist in the opkg repo lists".format(repo)
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as uri is defined.
The following options are available to modify a repo definition:
repo
alias by which opkg refers to the repo.
uri
the URI to the repo.
compressed
defines (True or False) if the index file is compressed
enabled
enable or disable (True or False) repository
but do not remove if disabled.
refresh
enable or disable (True or False) auto-refresh of the repositories
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo repo uri=http://new/uri
salt '*' pkg.mod_repo repo enabled=False
'''
repos = list_repos()
found = False
uri = ''
if 'uri' in kwargs:
uri = kwargs['uri']
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
found = True
repostr = ''
if 'enabled' in kwargs and not kwargs['enabled']:
repostr += '# '
if 'compressed' in kwargs:
repostr += 'src/gz ' if kwargs['compressed'] else 'src'
else:
repostr += 'src/gz' if source['compressed'] else 'src'
repo_alias = kwargs['alias'] if 'alias' in kwargs else repo
if ' ' in repo_alias:
repostr += ' "{0}"'.format(repo_alias)
else:
repostr += ' {0}'.format(repo_alias)
repostr += ' {0}'.format(kwargs['uri'] if 'uri' in kwargs else source['uri'])
trusted = kwargs.get('trusted')
repostr = _set_trusted_option_if_needed(repostr, trusted) if trusted is not None else \
_set_trusted_option_if_needed(repostr, source.get('trusted'))
_mod_repo_in_file(repo, repostr, source['file'])
elif uri and source['uri'] == uri:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(uri, source['name']))
if not found:
# Need to add a new repo
if 'uri' not in kwargs:
raise CommandExecutionError(
'Repository \'{0}\' not found and no URI passed to create one.'.format(repo))
properties = {'uri': kwargs['uri']}
# If compressed is not defined, assume True
properties['compressed'] = kwargs['compressed'] if 'compressed' in kwargs else True
# If enabled is not defined, assume True
properties['enabled'] = kwargs['enabled'] if 'enabled' in kwargs else True
properties['trusted'] = kwargs.get('trusted')
_add_new_repo(repo, properties)
if 'refresh' in kwargs:
refresh_db()
def file_list(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
output = file_dict(*packages)
files = []
for package in list(output['packages'].values()):
files.extend(package)
return {'errors': output['errors'], 'files': files}
def file_dict(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
errors = []
ret = {}
cmd_files = ['opkg', 'files']
if not packages:
packages = list(list_pkgs().keys())
for package in packages:
files = []
cmd = cmd_files[:]
cmd.append(package)
out = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
for line in out['stdout'].splitlines():
if line.startswith('/'):
files.append(line)
elif line.startswith(' * '):
errors.append(line[3:])
break
else:
continue
if files:
ret[package] = files
return {'errors': errors, 'packages': ret}
def owner(*paths, **kwargs): # pylint: disable=unused-argument
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.opkg.version`, if a single
path is passed, a string will be returned, and if multiple paths are passed,
a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
cmd_search = ['opkg', 'search']
for path in paths:
cmd = cmd_search[:]
cmd.append(path)
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
if output:
ret[path] = output.split(' - ')[0].strip()
else:
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def version_clean(version):
'''
Clean the version string removing extra data.
There's nothing do to here for nipkg.py, therefore it will always
return the given version.
'''
return version
def check_extra_requirements(pkgname, pkgver):
'''
Check if the installed package already has the given requirements.
There's nothing do to here for nipkg.py, therefore it will always
return True.
'''
return True
|
saltstack/salt
|
salt/modules/opkg.py
|
_build_install_command_list
|
python
|
def _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall):
'''
Builds a list of install commands to be executed in sequence in order to process
each of the to_install, to_downgrade, and to_reinstall lists.
'''
cmds = []
if to_install:
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(to_install)
cmds.append(cmd)
if to_downgrade:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-downgrade')
cmd.extend(to_downgrade)
cmds.append(cmd)
if to_reinstall:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-reinstall')
cmd.extend(to_reinstall)
cmds.append(cmd)
return cmds
|
Builds a list of install commands to be executed in sequence in order to process
each of the to_install, to_downgrade, and to_reinstall lists.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/opkg.py#L312-L333
| null |
# -*- coding: utf-8 -*-
'''
Support for Opkg
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
.. versionadded: 2016.3.0
.. note::
For version comparison support on opkg < 0.3.4, the ``opkg-utils`` package
must be installed.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import os
import re
import logging
import errno
# Import salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.itertools
import salt.utils.path
import salt.utils.pkg
import salt.utils.stringutils
import salt.utils.versions
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import shlex_quote as _cmd_quote # pylint: disable=import-error
from salt.ext.six.moves import map # pylint: disable=import-error,redefined-builtin
REPO_REGEXP = r'^#?\s*(src|src/gz)\s+([^\s<>]+|"[^<>]+")\s+[^\s<>]+'
OPKG_CONFDIR = '/etc/opkg'
ATTR_MAP = {
'Architecture': 'arch',
'Homepage': 'url',
'Installed-Time': 'install_date_time_t',
'Maintainer': 'packager',
'Package': 'name',
'Section': 'group'
}
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
NILRT_RESTARTCHECK_STATE_PATH = '/var/lib/salt/restartcheck_state'
def _update_nilrt_restart_state():
'''
NILRT systems determine whether to reboot after various package operations
including but not limited to kernel module installs/removals by checking
specific file md5sums & timestamps. These files are touched/modified by
the post-install/post-remove functions of their respective packages.
The opkg module uses this function to store/update those file timestamps
and checksums to be used later by the restartcheck module.
'''
__salt__['cmd.shell']('stat -c %Y /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.timestamp'
.format(NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.md5sum'
.format(NILRT_RESTARTCHECK_STATE_PATH))
# We can't assume nisysapi.ini always exists like modules.dep
nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'
if os.path.exists(nisysapi_path):
__salt__['cmd.shell']('stat -c %Y {0} >{1}/nisysapi.ini.timestamp'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0} >{1}/nisysapi.ini.md5sum'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
# Expert plugin files get added to a conf.d dir, so keep track of the total
# no. of files, their timestamps and content hashes
nisysapi_conf_d_path = "/usr/lib/{0}/nisysapi/conf.d/experts/".format(
'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'
)
if os.path.exists(nisysapi_conf_d_path):
with salt.utils.files.fopen('{0}/sysapi.conf.d.count'.format(
NILRT_RESTARTCHECK_STATE_PATH), 'w') as fcount:
fcount.write(str(len(os.listdir(nisysapi_conf_d_path))))
for fexpert in os.listdir(nisysapi_conf_d_path):
__salt__['cmd.shell']('stat -c %Y {0}/{1} >{2}/{1}.timestamp'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0}/{1} >{2}/{1}.md5sum'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
def _get_restartcheck_result(errors):
'''
Return restartcheck result and append errors (if any) to ``errors``
'''
rs_result = __salt__['restartcheck.restartcheck'](verbose=False)
if isinstance(rs_result, dict) and 'comment' in rs_result:
errors.append(rs_result['comment'])
return rs_result
def _process_restartcheck_result(rs_result, **kwargs):
'''
Check restartcheck output to see if system/service restarts were requested
and take appropriate action.
'''
if 'No packages seem to need to be restarted' in rs_result:
return
reboot_required = False
for rstr in rs_result:
if 'System restart required' in rstr:
_update_nilrt_restart_state()
__salt__['system.set_reboot_required_witnessed']()
reboot_required = True
if kwargs.get('always_restart_services', True) or not reboot_required:
for rstr in rs_result:
if 'System restart required' not in rstr:
service = os.path.join('/etc/init.d', rstr)
if os.path.exists(service):
__salt__['cmd.run']([service, 'restart'])
def __virtual__():
'''
Confirm this module is on a nilrt based system
'''
if __grains__.get('os_family') == 'NILinuxRT':
try:
os.makedirs(NILRT_RESTARTCHECK_STATE_PATH)
except OSError as exc:
if exc.errno != errno.EEXIST:
return False, 'Error creating {0} (-{1}): {2}'.format(
NILRT_RESTARTCHECK_STATE_PATH,
exc.errno,
exc.strerror)
# populate state dir if empty
if not os.listdir(NILRT_RESTARTCHECK_STATE_PATH):
_update_nilrt_restart_state()
return __virtualname__
if os.path.isdir(OPKG_CONFDIR):
return __virtualname__
return False, "Module opkg only works on OpenEmbedded based systems"
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
if not names:
return ''
ret = {}
for name in names:
ret[name] = ''
# Refresh before looking for the latest version available
if refresh:
refresh_db()
cmd = ['opkg', 'list-upgradable']
out = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
try:
name, _oldversion, newversion = line.split(' - ')
if name in names:
ret[name] = newversion
except ValueError:
pass
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = latest_version
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(failhard=False, **kwargs): # pylint: disable=unused-argument
'''
Updates the opkg database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
failhard
If False, return results of failed lines as ``False`` for the package
database that encountered the error.
If True, raise an error with a list of the package databases that
encountered errors.
.. versionadded:: 2018.3.0
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
error_repos = []
cmd = ['opkg', 'update']
# opkg returns a non-zero retcode when there is a failure to refresh
# from one or more repos. Due to this, ignore the retcode.
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True,
redirect_stderr=True)
out = call['stdout']
prev_line = ''
for line in salt.utils.itertools.split(out, '\n'):
if 'Inflating' in line:
key = line.strip().split()[1][:-1]
ret[key] = True
elif 'Updated source' in line:
# Use the previous line.
key = prev_line.strip().split()[1][:-1]
ret[key] = True
elif 'Failed to download' in line:
key = line.strip().split()[5].split(',')[0]
ret[key] = False
error_repos.append(key)
prev_line = line
if failhard and error_repos:
raise CommandExecutionError(
'Error getting repos: {0}'.format(', '.join(error_repos))
)
# On a non-zero exit code where no failed repos were found, raise an
# exception because this appears to be a different kind of error.
if call['retcode'] != 0 and not error_repos:
raise CommandExecutionError(out)
return ret
def _is_testmode(**kwargs):
'''
Returns whether a test mode (noaction) operation was requested.
'''
return bool(kwargs.get('test') or __opts__.get('test'))
def _append_noaction_if_testmode(cmd, **kwargs):
'''
Adds the --noaction flag to the command if it's running in the test mode.
'''
if _is_testmode(**kwargs):
cmd.append('--noaction')
def _parse_reported_packages_from_install_output(output):
'''
Parses the output of "opkg install" to determine what packages would have been
installed by an operation run with the --noaction flag.
We are looking for lines like:
Installing <package> (<version>) on <target>
or
Upgrading <package> from <oldVersion> to <version> on root
'''
reported_pkgs = {}
install_pattern = re.compile(r'Installing\s(?P<package>.*?)\s\((?P<version>.*?)\)\son\s(?P<target>.*?)')
upgrade_pattern = re.compile(r'Upgrading\s(?P<package>.*?)\sfrom\s(?P<oldVersion>.*?)\sto\s(?P<version>.*?)\son\s(?P<target>.*?)')
for line in salt.utils.itertools.split(output, '\n'):
match = install_pattern.match(line)
if match is None:
match = upgrade_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = match.group('version')
return reported_pkgs
def _execute_install_command(cmd, parse_output, errors, parsed_packages):
'''
Executes a command for the install operation.
If the command fails, its error output will be appended to the errors list.
If the command succeeds and parse_output is true, updated packages will be appended
to the parsed_packages dictionary.
'''
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors.append(out['stderr'])
else:
errors.append(out['stdout'])
elif parse_output:
parsed_packages.update(_parse_reported_packages_from_install_output(out['stdout']))
def install(name=None,
refresh=False,
pkgs=None,
sources=None,
reinstall=False,
**kwargs):
'''
Install the passed package, add refresh=True to update the opkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionadded:: 2017.7.0
reinstall : False
Specifying reinstall=True will use ``opkg install --force-reinstall``
rather than simply ``opkg install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``opkg
install --force-reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2017.7.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of IPK packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
install_recommends
Whether to install the packages marked as recommended. Default is True.
only_upgrade
Only upgrade the packages (disallow downgrades), if they are already
installed. Default is False.
.. versionadded:: 2017.7.0
always_restart_services
Whether to restart services even if a reboot is required. Default is True.
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
refreshdb = salt.utils.data.is_true(refresh)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
cmd_prefix = ['opkg', 'install']
to_install = []
to_reinstall = []
to_downgrade = []
_append_noaction_if_testmode(cmd_prefix, **kwargs)
if not pkg_params:
return {}
elif pkg_type == 'file':
if reinstall:
cmd_prefix.append('--force-reinstall')
if not kwargs.get('only_upgrade', False):
cmd_prefix.append('--force-downgrade')
to_install.extend(pkg_params)
elif pkg_type == 'repository':
if not kwargs.get('install_recommends', True):
cmd_prefix.append('--no-install-recommends')
for pkgname, pkgversion in six.iteritems(pkg_params):
if (name and pkgs is None and kwargs.get('version') and
len(pkg_params) == 1):
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
version_num = pkgversion
if version_num is None:
# Don't allow downgrades if the version
# number is not specified.
if reinstall and pkgname in old:
to_reinstall.append(pkgname)
else:
to_install.append(pkgname)
else:
pkgstr = '{0}={1}'.format(pkgname, version_num)
cver = old.get(pkgname, '')
if reinstall and cver and salt.utils.versions.compare(
ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall.append(pkgstr)
elif not cver or salt.utils.versions.compare(
ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
to_install.append(pkgstr)
else:
if not kwargs.get('only_upgrade', False):
to_downgrade.append(pkgstr)
else:
# This should cause the command to fail.
to_install.append(pkgstr)
cmds = _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall)
if not cmds:
return {}
if refreshdb:
refresh_db()
errors = []
is_testmode = _is_testmode(**kwargs)
test_packages = {}
for cmd in cmds:
_execute_install_command(cmd, is_testmode, errors, test_packages)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if is_testmode:
new = copy.deepcopy(new)
new.update(test_packages)
ret = salt.utils.data.compare_dicts(old, new)
if pkg_type == 'file' and reinstall:
# For file-based packages, prepare 'to_reinstall' to have a list
# of all the package names that may have been reinstalled.
# This way, we could include reinstalled packages in 'ret'.
for pkgfile in to_install:
# Convert from file name to package name.
cmd = ['opkg', 'info', pkgfile]
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] == 0:
# Just need the package name.
pkginfo_dict = _process_info_installed_output(
out['stdout'], []
)
if pkginfo_dict:
to_reinstall.append(list(pkginfo_dict.keys())[0])
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def _parse_reported_packages_from_remove_output(output):
'''
Parses the output of "opkg remove" to determine what packages would have been
removed by an operation run with the --noaction flag.
We are looking for lines like
Removing <package> (<version>) from <Target>...
'''
reported_pkgs = {}
remove_pattern = re.compile(r'Removing\s(?P<package>.*?)\s\((?P<version>.*?)\)\sfrom\s(?P<target>.*?)...')
for line in salt.utils.itertools.split(output, '\n'):
match = remove_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = ''
return reported_pkgs
def remove(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Remove packages using ``opkg remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
remove_dependencies
Remove package and all dependencies
.. versionadded:: 2019.2.0
auto_remove_deps
Remove packages that were installed automatically to satisfy dependencies
.. versionadded:: 2019.2.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
salt '*' pkg.remove pkgs='["foo", "bar"]' remove_dependencies=True auto_remove_deps=True
'''
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 {}
cmd = ['opkg', 'remove']
_append_noaction_if_testmode(cmd, **kwargs)
if kwargs.get('remove_dependencies', False):
cmd.append('--force-removal-of-dependent-packages')
if kwargs.get('auto_remove_deps', False):
cmd.append('--autoremove')
cmd.extend(targets)
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors = [out['stderr']]
else:
errors = [out['stdout']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if _is_testmode(**kwargs):
reportedPkgs = _parse_reported_packages_from_remove_output(out['stdout'])
new = {k: v for k, v in new.items() if k not in reportedPkgs}
ret = salt.utils.data.compare_dicts(old, new)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def purge(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Package purges are not supported by opkg, this function is identical to
:mod:`pkg.remove <salt.modules.opkg.remove>`.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name, pkgs=pkgs)
def upgrade(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
Upgrades all packages via ``opkg upgrade``
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
errors = []
if salt.utils.data.is_true(refresh):
refresh_db()
old = list_pkgs()
cmd = ['opkg', 'upgrade']
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
errors.append(result)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif state != 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = _set_state(target, 'hold')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif state == 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret['comment'] = ('Package {0} is set not to be held.'
.format(target))
else:
result = _set_state(target, 'ok')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def _get_state(pkg):
'''
View package state from the opkg database
Return the state of pkg
'''
cmd = ['opkg', 'status']
cmd.append(pkg)
out = __salt__['cmd.run'](cmd, python_shell=False)
state_flag = ''
for line in salt.utils.itertools.split(out, '\n'):
if line.startswith('Status'):
_status, _state_want, state_flag, _state_status = line.split()
return state_flag
def _set_state(pkg, state):
'''
Change package state on the opkg database
The state can be any of:
- hold
- noprune
- user
- ok
- installed
- unpacked
This command is commonly used to mark a specific package to be held from
being upgraded, that is, to be kept at a certain version.
Returns a dict containing the package name, and the new and old
versions.
'''
ret = {}
valid_states = ('hold', 'noprune', 'user', 'ok', 'installed', 'unpacked')
if state not in valid_states:
raise SaltInvocationError('Invalid state: {0}'.format(state))
oldstate = _get_state(pkg)
cmd = ['opkg', 'flag']
cmd.append(state)
cmd.append(pkg)
_out = __salt__['cmd.run'](cmd, python_shell=False)
# Missing return value check due to opkg issue 160
ret[pkg] = {'old': oldstate,
'new': state}
return ret
def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
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
cmd = ['opkg', 'list-installed']
ret = {}
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
# This is a continuation of package description
if not line or line[0] == ' ':
continue
# This contains package name, version, and description.
# Extract the first two.
pkg_name, pkg_version = line.split(' - ', 2)[:2]
__salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version)
__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 list_upgrades(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
List all available package upgrades.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
ret = {}
if salt.utils.data.is_true(refresh):
refresh_db()
cmd = ['opkg', 'list-upgradable']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
if 'stdout' in call:
comment += call['stdout']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
name, _oldversion, newversion = line.split(' - ')
ret[name] = newversion
return ret
def _convert_to_standard_attr(attr):
'''
Helper function for _process_info_installed_output()
Converts an opkg attribute name to a standard attribute
name which is used across 'pkg' modules.
'''
ret_attr = ATTR_MAP.get(attr, None)
if ret_attr is None:
# All others convert to lowercase
return attr.lower()
return ret_attr
def _process_info_installed_output(out, filter_attrs):
'''
Helper function for info_installed()
Processes stdout output from a single invocation of
'opkg status'.
'''
ret = {}
name = None
attrs = {}
attr = None
for line in salt.utils.itertools.split(out, '\n'):
if line and line[0] == ' ':
# This is a continuation of the last attr
if filter_attrs is None or attr in filter_attrs:
line = line.strip()
if attrs[attr]:
# If attr is empty, don't add leading newline
attrs[attr] += '\n'
attrs[attr] += line
continue
line = line.strip()
if not line:
# Separator between different packages
if name:
ret[name] = attrs
name = None
attrs = {}
attr = None
continue
key, value = line.split(':', 1)
value = value.lstrip()
attr = _convert_to_standard_attr(key)
if attr == 'name':
name = value
elif filter_attrs is None or attr in filter_attrs:
attrs[attr] = value
if name:
ret[name] = attrs
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
.. versionadded:: 2017.7.0
:param names:
Names of the packages to get information about. If none are specified,
will return information for all installed packages.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
arch, conffiles, conflicts, depends, description, filename, group,
install_date_time_t, md5sum, packager, provides, recommends,
replaces, size, source, suggests, url, version
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed
salt '*' pkg.info_installed attr=version,packager
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> attr=version,packager
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,packager
'''
attr = kwargs.pop('attr', None)
if attr is None:
filter_attrs = None
elif isinstance(attr, six.string_types):
filter_attrs = set(attr.split(','))
else:
filter_attrs = set(attr)
ret = {}
if names:
# Specific list of names of installed packages
for name in names:
cmd = ['opkg', 'status', name]
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
else:
# All installed packages
cmd = ['opkg', 'status']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
return ret
def upgrade_available(name, **kwargs): # pylint: disable=unused-argument
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs): # pylint: disable=unused-argument
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2016.3.4
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0' '0.2.4.1-0'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] if ignore_epoch else six.text_type(x)
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
output = __salt__['cmd.run_stdout'](['opkg', '--version'],
output_loglevel='trace',
python_shell=False)
opkg_version = output.split(' ')[2].strip()
if salt.utils.versions.LooseVersion(opkg_version) >= \
salt.utils.versions.LooseVersion('0.3.4'):
cmd_compare = ['opkg', 'compare-versions']
elif salt.utils.path.which('opkg-compare-versions'):
cmd_compare = ['opkg-compare-versions']
else:
log.warning('Unable to find a compare-versions utility installed. Either upgrade opkg to '
'version > 0.3.4 (preferred) or install the older opkg-compare-versions script.')
return None
for oper, ret in (("<<", -1), ("=", 0), (">>", 1)):
cmd = cmd_compare[:]
cmd.append(_cmd_quote(pkg1))
cmd.append(oper)
cmd.append(_cmd_quote(pkg2))
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
ignore_retcode=True,
python_shell=False)
if retcode == 0:
return ret
return None
def _set_repo_option(repo, option):
'''
Set the option to repo
'''
if not option:
return
opt = option.split('=')
if len(opt) != 2:
return
if opt[0] == 'trusted':
repo['trusted'] = opt[1] == 'yes'
else:
repo[opt[0]] = opt[1]
def _set_repo_options(repo, options):
'''
Set the options to the repo.
'''
delimiters = "[", "]"
pattern = '|'.join(map(re.escape, delimiters))
for option in options:
splitted = re.split(pattern, option)
for opt in splitted:
_set_repo_option(repo, opt)
def _create_repo(line, filename):
'''
Create repo
'''
repo = {}
if line.startswith('#'):
repo['enabled'] = False
line = line[1:]
else:
repo['enabled'] = True
cols = salt.utils.args.shlex_split(line.strip())
repo['compressed'] = not cols[0] in 'src'
repo['name'] = cols[1]
repo['uri'] = cols[2]
repo['file'] = os.path.join(OPKG_CONFDIR, filename)
if len(cols) > 3:
_set_repo_options(repo, cols[3:])
return repo
def _read_repos(conf_file, repos, filename, regex):
'''
Read repos from configuration file
'''
for line in conf_file:
line = salt.utils.stringutils.to_unicode(line)
if not regex.search(line):
continue
repo = _create_repo(line, filename)
# do not store duplicated uri's
if repo['uri'] not in repos:
repos[repo['uri']] = [repo]
def list_repos(**kwargs): # pylint: disable=unused-argument
'''
Lists all repos on ``/etc/opkg/*.conf``
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos = {}
regex = re.compile(REPO_REGEXP)
for filename in os.listdir(OPKG_CONFDIR):
if not filename.endswith(".conf"):
continue
with salt.utils.files.fopen(os.path.join(OPKG_CONFDIR, filename)) as conf_file:
_read_repos(conf_file, repos, filename, regex)
return repos
def get_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Display a repo from the ``/etc/opkg/*.conf``
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo repo
'''
repos = list_repos()
if repos:
for source in six.itervalues(repos):
for sub in source:
if sub['name'] == repo:
return sub
return {}
def _del_repo_from_file(repo, filepath):
'''
Remove a repo from filepath
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
regex = re.compile(REPO_REGEXP)
for line in fhandle:
line = salt.utils.stringutils.to_unicode(line)
if regex.search(line):
if line.startswith('#'):
line = line[1:]
cols = salt.utils.args.shlex_split(line.strip())
if repo != cols[1]:
output.append(salt.utils.stringutils.to_str(line))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def _set_trusted_option_if_needed(repostr, trusted):
'''
Set trusted option to repo if needed
'''
if trusted is True:
repostr += ' [trusted=yes]'
elif trusted is False:
repostr += ' [trusted=no]'
return repostr
def _add_new_repo(repo, properties):
'''
Add a new repo entry
'''
repostr = '# ' if not properties.get('enabled') else ''
repostr += 'src/gz ' if properties.get('compressed') else 'src '
if ' ' in repo:
repostr += '"' + repo + '" '
else:
repostr += repo + ' '
repostr += properties.get('uri')
repostr = _set_trusted_option_if_needed(repostr, properties.get('trusted'))
repostr += '\n'
conffile = os.path.join(OPKG_CONFDIR, repo + '.conf')
with salt.utils.files.fopen(conffile, 'a') as fhandle:
fhandle.write(salt.utils.stringutils.to_str(repostr))
def _mod_repo_in_file(repo, repostr, filepath):
'''
Replace a repo entry in filepath with repostr
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
for line in fhandle:
cols = salt.utils.args.shlex_split(
salt.utils.stringutils.to_unicode(line).strip()
)
if repo not in cols:
output.append(line)
else:
output.append(salt.utils.stringutils.to_str(repostr + '\n'))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def del_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Delete a repo from ``/etc/opkg/*.conf``
If the file does not contain any other repo configuration, the file itself
will be deleted.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo repo
'''
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
repos = list_repos()
if repos:
deleted_from = dict()
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
deleted_from[source['file']] = 0
_del_repo_from_file(repo, source['file'])
if deleted_from:
ret = ''
for repository in repos:
source = repos[repository][0]
if source['file'] in deleted_from:
deleted_from[source['file']] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 1 and os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.\n')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
if refresh:
refresh_db()
return ret
return "Repo {0} doesn't exist in the opkg repo lists".format(repo)
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as uri is defined.
The following options are available to modify a repo definition:
repo
alias by which opkg refers to the repo.
uri
the URI to the repo.
compressed
defines (True or False) if the index file is compressed
enabled
enable or disable (True or False) repository
but do not remove if disabled.
refresh
enable or disable (True or False) auto-refresh of the repositories
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo repo uri=http://new/uri
salt '*' pkg.mod_repo repo enabled=False
'''
repos = list_repos()
found = False
uri = ''
if 'uri' in kwargs:
uri = kwargs['uri']
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
found = True
repostr = ''
if 'enabled' in kwargs and not kwargs['enabled']:
repostr += '# '
if 'compressed' in kwargs:
repostr += 'src/gz ' if kwargs['compressed'] else 'src'
else:
repostr += 'src/gz' if source['compressed'] else 'src'
repo_alias = kwargs['alias'] if 'alias' in kwargs else repo
if ' ' in repo_alias:
repostr += ' "{0}"'.format(repo_alias)
else:
repostr += ' {0}'.format(repo_alias)
repostr += ' {0}'.format(kwargs['uri'] if 'uri' in kwargs else source['uri'])
trusted = kwargs.get('trusted')
repostr = _set_trusted_option_if_needed(repostr, trusted) if trusted is not None else \
_set_trusted_option_if_needed(repostr, source.get('trusted'))
_mod_repo_in_file(repo, repostr, source['file'])
elif uri and source['uri'] == uri:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(uri, source['name']))
if not found:
# Need to add a new repo
if 'uri' not in kwargs:
raise CommandExecutionError(
'Repository \'{0}\' not found and no URI passed to create one.'.format(repo))
properties = {'uri': kwargs['uri']}
# If compressed is not defined, assume True
properties['compressed'] = kwargs['compressed'] if 'compressed' in kwargs else True
# If enabled is not defined, assume True
properties['enabled'] = kwargs['enabled'] if 'enabled' in kwargs else True
properties['trusted'] = kwargs.get('trusted')
_add_new_repo(repo, properties)
if 'refresh' in kwargs:
refresh_db()
def file_list(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
output = file_dict(*packages)
files = []
for package in list(output['packages'].values()):
files.extend(package)
return {'errors': output['errors'], 'files': files}
def file_dict(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
errors = []
ret = {}
cmd_files = ['opkg', 'files']
if not packages:
packages = list(list_pkgs().keys())
for package in packages:
files = []
cmd = cmd_files[:]
cmd.append(package)
out = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
for line in out['stdout'].splitlines():
if line.startswith('/'):
files.append(line)
elif line.startswith(' * '):
errors.append(line[3:])
break
else:
continue
if files:
ret[package] = files
return {'errors': errors, 'packages': ret}
def owner(*paths, **kwargs): # pylint: disable=unused-argument
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.opkg.version`, if a single
path is passed, a string will be returned, and if multiple paths are passed,
a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
cmd_search = ['opkg', 'search']
for path in paths:
cmd = cmd_search[:]
cmd.append(path)
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
if output:
ret[path] = output.split(' - ')[0].strip()
else:
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def version_clean(version):
'''
Clean the version string removing extra data.
There's nothing do to here for nipkg.py, therefore it will always
return the given version.
'''
return version
def check_extra_requirements(pkgname, pkgver):
'''
Check if the installed package already has the given requirements.
There's nothing do to here for nipkg.py, therefore it will always
return True.
'''
return True
|
saltstack/salt
|
salt/modules/opkg.py
|
_parse_reported_packages_from_install_output
|
python
|
def _parse_reported_packages_from_install_output(output):
'''
Parses the output of "opkg install" to determine what packages would have been
installed by an operation run with the --noaction flag.
We are looking for lines like:
Installing <package> (<version>) on <target>
or
Upgrading <package> from <oldVersion> to <version> on root
'''
reported_pkgs = {}
install_pattern = re.compile(r'Installing\s(?P<package>.*?)\s\((?P<version>.*?)\)\son\s(?P<target>.*?)')
upgrade_pattern = re.compile(r'Upgrading\s(?P<package>.*?)\sfrom\s(?P<oldVersion>.*?)\sto\s(?P<version>.*?)\son\s(?P<target>.*?)')
for line in salt.utils.itertools.split(output, '\n'):
match = install_pattern.match(line)
if match is None:
match = upgrade_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = match.group('version')
return reported_pkgs
|
Parses the output of "opkg install" to determine what packages would have been
installed by an operation run with the --noaction flag.
We are looking for lines like:
Installing <package> (<version>) on <target>
or
Upgrading <package> from <oldVersion> to <version> on root
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/opkg.py#L336-L356
| null |
# -*- coding: utf-8 -*-
'''
Support for Opkg
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
.. versionadded: 2016.3.0
.. note::
For version comparison support on opkg < 0.3.4, the ``opkg-utils`` package
must be installed.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import os
import re
import logging
import errno
# Import salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.itertools
import salt.utils.path
import salt.utils.pkg
import salt.utils.stringutils
import salt.utils.versions
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import shlex_quote as _cmd_quote # pylint: disable=import-error
from salt.ext.six.moves import map # pylint: disable=import-error,redefined-builtin
REPO_REGEXP = r'^#?\s*(src|src/gz)\s+([^\s<>]+|"[^<>]+")\s+[^\s<>]+'
OPKG_CONFDIR = '/etc/opkg'
ATTR_MAP = {
'Architecture': 'arch',
'Homepage': 'url',
'Installed-Time': 'install_date_time_t',
'Maintainer': 'packager',
'Package': 'name',
'Section': 'group'
}
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
NILRT_RESTARTCHECK_STATE_PATH = '/var/lib/salt/restartcheck_state'
def _update_nilrt_restart_state():
'''
NILRT systems determine whether to reboot after various package operations
including but not limited to kernel module installs/removals by checking
specific file md5sums & timestamps. These files are touched/modified by
the post-install/post-remove functions of their respective packages.
The opkg module uses this function to store/update those file timestamps
and checksums to be used later by the restartcheck module.
'''
__salt__['cmd.shell']('stat -c %Y /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.timestamp'
.format(NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.md5sum'
.format(NILRT_RESTARTCHECK_STATE_PATH))
# We can't assume nisysapi.ini always exists like modules.dep
nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'
if os.path.exists(nisysapi_path):
__salt__['cmd.shell']('stat -c %Y {0} >{1}/nisysapi.ini.timestamp'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0} >{1}/nisysapi.ini.md5sum'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
# Expert plugin files get added to a conf.d dir, so keep track of the total
# no. of files, their timestamps and content hashes
nisysapi_conf_d_path = "/usr/lib/{0}/nisysapi/conf.d/experts/".format(
'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'
)
if os.path.exists(nisysapi_conf_d_path):
with salt.utils.files.fopen('{0}/sysapi.conf.d.count'.format(
NILRT_RESTARTCHECK_STATE_PATH), 'w') as fcount:
fcount.write(str(len(os.listdir(nisysapi_conf_d_path))))
for fexpert in os.listdir(nisysapi_conf_d_path):
__salt__['cmd.shell']('stat -c %Y {0}/{1} >{2}/{1}.timestamp'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0}/{1} >{2}/{1}.md5sum'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
def _get_restartcheck_result(errors):
'''
Return restartcheck result and append errors (if any) to ``errors``
'''
rs_result = __salt__['restartcheck.restartcheck'](verbose=False)
if isinstance(rs_result, dict) and 'comment' in rs_result:
errors.append(rs_result['comment'])
return rs_result
def _process_restartcheck_result(rs_result, **kwargs):
'''
Check restartcheck output to see if system/service restarts were requested
and take appropriate action.
'''
if 'No packages seem to need to be restarted' in rs_result:
return
reboot_required = False
for rstr in rs_result:
if 'System restart required' in rstr:
_update_nilrt_restart_state()
__salt__['system.set_reboot_required_witnessed']()
reboot_required = True
if kwargs.get('always_restart_services', True) or not reboot_required:
for rstr in rs_result:
if 'System restart required' not in rstr:
service = os.path.join('/etc/init.d', rstr)
if os.path.exists(service):
__salt__['cmd.run']([service, 'restart'])
def __virtual__():
'''
Confirm this module is on a nilrt based system
'''
if __grains__.get('os_family') == 'NILinuxRT':
try:
os.makedirs(NILRT_RESTARTCHECK_STATE_PATH)
except OSError as exc:
if exc.errno != errno.EEXIST:
return False, 'Error creating {0} (-{1}): {2}'.format(
NILRT_RESTARTCHECK_STATE_PATH,
exc.errno,
exc.strerror)
# populate state dir if empty
if not os.listdir(NILRT_RESTARTCHECK_STATE_PATH):
_update_nilrt_restart_state()
return __virtualname__
if os.path.isdir(OPKG_CONFDIR):
return __virtualname__
return False, "Module opkg only works on OpenEmbedded based systems"
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
if not names:
return ''
ret = {}
for name in names:
ret[name] = ''
# Refresh before looking for the latest version available
if refresh:
refresh_db()
cmd = ['opkg', 'list-upgradable']
out = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
try:
name, _oldversion, newversion = line.split(' - ')
if name in names:
ret[name] = newversion
except ValueError:
pass
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = latest_version
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(failhard=False, **kwargs): # pylint: disable=unused-argument
'''
Updates the opkg database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
failhard
If False, return results of failed lines as ``False`` for the package
database that encountered the error.
If True, raise an error with a list of the package databases that
encountered errors.
.. versionadded:: 2018.3.0
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
error_repos = []
cmd = ['opkg', 'update']
# opkg returns a non-zero retcode when there is a failure to refresh
# from one or more repos. Due to this, ignore the retcode.
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True,
redirect_stderr=True)
out = call['stdout']
prev_line = ''
for line in salt.utils.itertools.split(out, '\n'):
if 'Inflating' in line:
key = line.strip().split()[1][:-1]
ret[key] = True
elif 'Updated source' in line:
# Use the previous line.
key = prev_line.strip().split()[1][:-1]
ret[key] = True
elif 'Failed to download' in line:
key = line.strip().split()[5].split(',')[0]
ret[key] = False
error_repos.append(key)
prev_line = line
if failhard and error_repos:
raise CommandExecutionError(
'Error getting repos: {0}'.format(', '.join(error_repos))
)
# On a non-zero exit code where no failed repos were found, raise an
# exception because this appears to be a different kind of error.
if call['retcode'] != 0 and not error_repos:
raise CommandExecutionError(out)
return ret
def _is_testmode(**kwargs):
'''
Returns whether a test mode (noaction) operation was requested.
'''
return bool(kwargs.get('test') or __opts__.get('test'))
def _append_noaction_if_testmode(cmd, **kwargs):
'''
Adds the --noaction flag to the command if it's running in the test mode.
'''
if _is_testmode(**kwargs):
cmd.append('--noaction')
def _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall):
'''
Builds a list of install commands to be executed in sequence in order to process
each of the to_install, to_downgrade, and to_reinstall lists.
'''
cmds = []
if to_install:
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(to_install)
cmds.append(cmd)
if to_downgrade:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-downgrade')
cmd.extend(to_downgrade)
cmds.append(cmd)
if to_reinstall:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-reinstall')
cmd.extend(to_reinstall)
cmds.append(cmd)
return cmds
def _execute_install_command(cmd, parse_output, errors, parsed_packages):
'''
Executes a command for the install operation.
If the command fails, its error output will be appended to the errors list.
If the command succeeds and parse_output is true, updated packages will be appended
to the parsed_packages dictionary.
'''
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors.append(out['stderr'])
else:
errors.append(out['stdout'])
elif parse_output:
parsed_packages.update(_parse_reported_packages_from_install_output(out['stdout']))
def install(name=None,
refresh=False,
pkgs=None,
sources=None,
reinstall=False,
**kwargs):
'''
Install the passed package, add refresh=True to update the opkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionadded:: 2017.7.0
reinstall : False
Specifying reinstall=True will use ``opkg install --force-reinstall``
rather than simply ``opkg install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``opkg
install --force-reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2017.7.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of IPK packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
install_recommends
Whether to install the packages marked as recommended. Default is True.
only_upgrade
Only upgrade the packages (disallow downgrades), if they are already
installed. Default is False.
.. versionadded:: 2017.7.0
always_restart_services
Whether to restart services even if a reboot is required. Default is True.
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
refreshdb = salt.utils.data.is_true(refresh)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
cmd_prefix = ['opkg', 'install']
to_install = []
to_reinstall = []
to_downgrade = []
_append_noaction_if_testmode(cmd_prefix, **kwargs)
if not pkg_params:
return {}
elif pkg_type == 'file':
if reinstall:
cmd_prefix.append('--force-reinstall')
if not kwargs.get('only_upgrade', False):
cmd_prefix.append('--force-downgrade')
to_install.extend(pkg_params)
elif pkg_type == 'repository':
if not kwargs.get('install_recommends', True):
cmd_prefix.append('--no-install-recommends')
for pkgname, pkgversion in six.iteritems(pkg_params):
if (name and pkgs is None and kwargs.get('version') and
len(pkg_params) == 1):
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
version_num = pkgversion
if version_num is None:
# Don't allow downgrades if the version
# number is not specified.
if reinstall and pkgname in old:
to_reinstall.append(pkgname)
else:
to_install.append(pkgname)
else:
pkgstr = '{0}={1}'.format(pkgname, version_num)
cver = old.get(pkgname, '')
if reinstall and cver and salt.utils.versions.compare(
ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall.append(pkgstr)
elif not cver or salt.utils.versions.compare(
ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
to_install.append(pkgstr)
else:
if not kwargs.get('only_upgrade', False):
to_downgrade.append(pkgstr)
else:
# This should cause the command to fail.
to_install.append(pkgstr)
cmds = _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall)
if not cmds:
return {}
if refreshdb:
refresh_db()
errors = []
is_testmode = _is_testmode(**kwargs)
test_packages = {}
for cmd in cmds:
_execute_install_command(cmd, is_testmode, errors, test_packages)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if is_testmode:
new = copy.deepcopy(new)
new.update(test_packages)
ret = salt.utils.data.compare_dicts(old, new)
if pkg_type == 'file' and reinstall:
# For file-based packages, prepare 'to_reinstall' to have a list
# of all the package names that may have been reinstalled.
# This way, we could include reinstalled packages in 'ret'.
for pkgfile in to_install:
# Convert from file name to package name.
cmd = ['opkg', 'info', pkgfile]
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] == 0:
# Just need the package name.
pkginfo_dict = _process_info_installed_output(
out['stdout'], []
)
if pkginfo_dict:
to_reinstall.append(list(pkginfo_dict.keys())[0])
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def _parse_reported_packages_from_remove_output(output):
'''
Parses the output of "opkg remove" to determine what packages would have been
removed by an operation run with the --noaction flag.
We are looking for lines like
Removing <package> (<version>) from <Target>...
'''
reported_pkgs = {}
remove_pattern = re.compile(r'Removing\s(?P<package>.*?)\s\((?P<version>.*?)\)\sfrom\s(?P<target>.*?)...')
for line in salt.utils.itertools.split(output, '\n'):
match = remove_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = ''
return reported_pkgs
def remove(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Remove packages using ``opkg remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
remove_dependencies
Remove package and all dependencies
.. versionadded:: 2019.2.0
auto_remove_deps
Remove packages that were installed automatically to satisfy dependencies
.. versionadded:: 2019.2.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
salt '*' pkg.remove pkgs='["foo", "bar"]' remove_dependencies=True auto_remove_deps=True
'''
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 {}
cmd = ['opkg', 'remove']
_append_noaction_if_testmode(cmd, **kwargs)
if kwargs.get('remove_dependencies', False):
cmd.append('--force-removal-of-dependent-packages')
if kwargs.get('auto_remove_deps', False):
cmd.append('--autoremove')
cmd.extend(targets)
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors = [out['stderr']]
else:
errors = [out['stdout']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if _is_testmode(**kwargs):
reportedPkgs = _parse_reported_packages_from_remove_output(out['stdout'])
new = {k: v for k, v in new.items() if k not in reportedPkgs}
ret = salt.utils.data.compare_dicts(old, new)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def purge(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Package purges are not supported by opkg, this function is identical to
:mod:`pkg.remove <salt.modules.opkg.remove>`.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name, pkgs=pkgs)
def upgrade(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
Upgrades all packages via ``opkg upgrade``
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
errors = []
if salt.utils.data.is_true(refresh):
refresh_db()
old = list_pkgs()
cmd = ['opkg', 'upgrade']
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
errors.append(result)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif state != 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = _set_state(target, 'hold')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif state == 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret['comment'] = ('Package {0} is set not to be held.'
.format(target))
else:
result = _set_state(target, 'ok')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def _get_state(pkg):
'''
View package state from the opkg database
Return the state of pkg
'''
cmd = ['opkg', 'status']
cmd.append(pkg)
out = __salt__['cmd.run'](cmd, python_shell=False)
state_flag = ''
for line in salt.utils.itertools.split(out, '\n'):
if line.startswith('Status'):
_status, _state_want, state_flag, _state_status = line.split()
return state_flag
def _set_state(pkg, state):
'''
Change package state on the opkg database
The state can be any of:
- hold
- noprune
- user
- ok
- installed
- unpacked
This command is commonly used to mark a specific package to be held from
being upgraded, that is, to be kept at a certain version.
Returns a dict containing the package name, and the new and old
versions.
'''
ret = {}
valid_states = ('hold', 'noprune', 'user', 'ok', 'installed', 'unpacked')
if state not in valid_states:
raise SaltInvocationError('Invalid state: {0}'.format(state))
oldstate = _get_state(pkg)
cmd = ['opkg', 'flag']
cmd.append(state)
cmd.append(pkg)
_out = __salt__['cmd.run'](cmd, python_shell=False)
# Missing return value check due to opkg issue 160
ret[pkg] = {'old': oldstate,
'new': state}
return ret
def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
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
cmd = ['opkg', 'list-installed']
ret = {}
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
# This is a continuation of package description
if not line or line[0] == ' ':
continue
# This contains package name, version, and description.
# Extract the first two.
pkg_name, pkg_version = line.split(' - ', 2)[:2]
__salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version)
__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 list_upgrades(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
List all available package upgrades.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
ret = {}
if salt.utils.data.is_true(refresh):
refresh_db()
cmd = ['opkg', 'list-upgradable']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
if 'stdout' in call:
comment += call['stdout']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
name, _oldversion, newversion = line.split(' - ')
ret[name] = newversion
return ret
def _convert_to_standard_attr(attr):
'''
Helper function for _process_info_installed_output()
Converts an opkg attribute name to a standard attribute
name which is used across 'pkg' modules.
'''
ret_attr = ATTR_MAP.get(attr, None)
if ret_attr is None:
# All others convert to lowercase
return attr.lower()
return ret_attr
def _process_info_installed_output(out, filter_attrs):
'''
Helper function for info_installed()
Processes stdout output from a single invocation of
'opkg status'.
'''
ret = {}
name = None
attrs = {}
attr = None
for line in salt.utils.itertools.split(out, '\n'):
if line and line[0] == ' ':
# This is a continuation of the last attr
if filter_attrs is None or attr in filter_attrs:
line = line.strip()
if attrs[attr]:
# If attr is empty, don't add leading newline
attrs[attr] += '\n'
attrs[attr] += line
continue
line = line.strip()
if not line:
# Separator between different packages
if name:
ret[name] = attrs
name = None
attrs = {}
attr = None
continue
key, value = line.split(':', 1)
value = value.lstrip()
attr = _convert_to_standard_attr(key)
if attr == 'name':
name = value
elif filter_attrs is None or attr in filter_attrs:
attrs[attr] = value
if name:
ret[name] = attrs
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
.. versionadded:: 2017.7.0
:param names:
Names of the packages to get information about. If none are specified,
will return information for all installed packages.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
arch, conffiles, conflicts, depends, description, filename, group,
install_date_time_t, md5sum, packager, provides, recommends,
replaces, size, source, suggests, url, version
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed
salt '*' pkg.info_installed attr=version,packager
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> attr=version,packager
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,packager
'''
attr = kwargs.pop('attr', None)
if attr is None:
filter_attrs = None
elif isinstance(attr, six.string_types):
filter_attrs = set(attr.split(','))
else:
filter_attrs = set(attr)
ret = {}
if names:
# Specific list of names of installed packages
for name in names:
cmd = ['opkg', 'status', name]
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
else:
# All installed packages
cmd = ['opkg', 'status']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
return ret
def upgrade_available(name, **kwargs): # pylint: disable=unused-argument
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs): # pylint: disable=unused-argument
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2016.3.4
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0' '0.2.4.1-0'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] if ignore_epoch else six.text_type(x)
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
output = __salt__['cmd.run_stdout'](['opkg', '--version'],
output_loglevel='trace',
python_shell=False)
opkg_version = output.split(' ')[2].strip()
if salt.utils.versions.LooseVersion(opkg_version) >= \
salt.utils.versions.LooseVersion('0.3.4'):
cmd_compare = ['opkg', 'compare-versions']
elif salt.utils.path.which('opkg-compare-versions'):
cmd_compare = ['opkg-compare-versions']
else:
log.warning('Unable to find a compare-versions utility installed. Either upgrade opkg to '
'version > 0.3.4 (preferred) or install the older opkg-compare-versions script.')
return None
for oper, ret in (("<<", -1), ("=", 0), (">>", 1)):
cmd = cmd_compare[:]
cmd.append(_cmd_quote(pkg1))
cmd.append(oper)
cmd.append(_cmd_quote(pkg2))
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
ignore_retcode=True,
python_shell=False)
if retcode == 0:
return ret
return None
def _set_repo_option(repo, option):
'''
Set the option to repo
'''
if not option:
return
opt = option.split('=')
if len(opt) != 2:
return
if opt[0] == 'trusted':
repo['trusted'] = opt[1] == 'yes'
else:
repo[opt[0]] = opt[1]
def _set_repo_options(repo, options):
'''
Set the options to the repo.
'''
delimiters = "[", "]"
pattern = '|'.join(map(re.escape, delimiters))
for option in options:
splitted = re.split(pattern, option)
for opt in splitted:
_set_repo_option(repo, opt)
def _create_repo(line, filename):
'''
Create repo
'''
repo = {}
if line.startswith('#'):
repo['enabled'] = False
line = line[1:]
else:
repo['enabled'] = True
cols = salt.utils.args.shlex_split(line.strip())
repo['compressed'] = not cols[0] in 'src'
repo['name'] = cols[1]
repo['uri'] = cols[2]
repo['file'] = os.path.join(OPKG_CONFDIR, filename)
if len(cols) > 3:
_set_repo_options(repo, cols[3:])
return repo
def _read_repos(conf_file, repos, filename, regex):
'''
Read repos from configuration file
'''
for line in conf_file:
line = salt.utils.stringutils.to_unicode(line)
if not regex.search(line):
continue
repo = _create_repo(line, filename)
# do not store duplicated uri's
if repo['uri'] not in repos:
repos[repo['uri']] = [repo]
def list_repos(**kwargs): # pylint: disable=unused-argument
'''
Lists all repos on ``/etc/opkg/*.conf``
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos = {}
regex = re.compile(REPO_REGEXP)
for filename in os.listdir(OPKG_CONFDIR):
if not filename.endswith(".conf"):
continue
with salt.utils.files.fopen(os.path.join(OPKG_CONFDIR, filename)) as conf_file:
_read_repos(conf_file, repos, filename, regex)
return repos
def get_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Display a repo from the ``/etc/opkg/*.conf``
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo repo
'''
repos = list_repos()
if repos:
for source in six.itervalues(repos):
for sub in source:
if sub['name'] == repo:
return sub
return {}
def _del_repo_from_file(repo, filepath):
'''
Remove a repo from filepath
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
regex = re.compile(REPO_REGEXP)
for line in fhandle:
line = salt.utils.stringutils.to_unicode(line)
if regex.search(line):
if line.startswith('#'):
line = line[1:]
cols = salt.utils.args.shlex_split(line.strip())
if repo != cols[1]:
output.append(salt.utils.stringutils.to_str(line))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def _set_trusted_option_if_needed(repostr, trusted):
'''
Set trusted option to repo if needed
'''
if trusted is True:
repostr += ' [trusted=yes]'
elif trusted is False:
repostr += ' [trusted=no]'
return repostr
def _add_new_repo(repo, properties):
'''
Add a new repo entry
'''
repostr = '# ' if not properties.get('enabled') else ''
repostr += 'src/gz ' if properties.get('compressed') else 'src '
if ' ' in repo:
repostr += '"' + repo + '" '
else:
repostr += repo + ' '
repostr += properties.get('uri')
repostr = _set_trusted_option_if_needed(repostr, properties.get('trusted'))
repostr += '\n'
conffile = os.path.join(OPKG_CONFDIR, repo + '.conf')
with salt.utils.files.fopen(conffile, 'a') as fhandle:
fhandle.write(salt.utils.stringutils.to_str(repostr))
def _mod_repo_in_file(repo, repostr, filepath):
'''
Replace a repo entry in filepath with repostr
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
for line in fhandle:
cols = salt.utils.args.shlex_split(
salt.utils.stringutils.to_unicode(line).strip()
)
if repo not in cols:
output.append(line)
else:
output.append(salt.utils.stringutils.to_str(repostr + '\n'))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def del_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Delete a repo from ``/etc/opkg/*.conf``
If the file does not contain any other repo configuration, the file itself
will be deleted.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo repo
'''
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
repos = list_repos()
if repos:
deleted_from = dict()
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
deleted_from[source['file']] = 0
_del_repo_from_file(repo, source['file'])
if deleted_from:
ret = ''
for repository in repos:
source = repos[repository][0]
if source['file'] in deleted_from:
deleted_from[source['file']] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 1 and os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.\n')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
if refresh:
refresh_db()
return ret
return "Repo {0} doesn't exist in the opkg repo lists".format(repo)
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as uri is defined.
The following options are available to modify a repo definition:
repo
alias by which opkg refers to the repo.
uri
the URI to the repo.
compressed
defines (True or False) if the index file is compressed
enabled
enable or disable (True or False) repository
but do not remove if disabled.
refresh
enable or disable (True or False) auto-refresh of the repositories
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo repo uri=http://new/uri
salt '*' pkg.mod_repo repo enabled=False
'''
repos = list_repos()
found = False
uri = ''
if 'uri' in kwargs:
uri = kwargs['uri']
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
found = True
repostr = ''
if 'enabled' in kwargs and not kwargs['enabled']:
repostr += '# '
if 'compressed' in kwargs:
repostr += 'src/gz ' if kwargs['compressed'] else 'src'
else:
repostr += 'src/gz' if source['compressed'] else 'src'
repo_alias = kwargs['alias'] if 'alias' in kwargs else repo
if ' ' in repo_alias:
repostr += ' "{0}"'.format(repo_alias)
else:
repostr += ' {0}'.format(repo_alias)
repostr += ' {0}'.format(kwargs['uri'] if 'uri' in kwargs else source['uri'])
trusted = kwargs.get('trusted')
repostr = _set_trusted_option_if_needed(repostr, trusted) if trusted is not None else \
_set_trusted_option_if_needed(repostr, source.get('trusted'))
_mod_repo_in_file(repo, repostr, source['file'])
elif uri and source['uri'] == uri:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(uri, source['name']))
if not found:
# Need to add a new repo
if 'uri' not in kwargs:
raise CommandExecutionError(
'Repository \'{0}\' not found and no URI passed to create one.'.format(repo))
properties = {'uri': kwargs['uri']}
# If compressed is not defined, assume True
properties['compressed'] = kwargs['compressed'] if 'compressed' in kwargs else True
# If enabled is not defined, assume True
properties['enabled'] = kwargs['enabled'] if 'enabled' in kwargs else True
properties['trusted'] = kwargs.get('trusted')
_add_new_repo(repo, properties)
if 'refresh' in kwargs:
refresh_db()
def file_list(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
output = file_dict(*packages)
files = []
for package in list(output['packages'].values()):
files.extend(package)
return {'errors': output['errors'], 'files': files}
def file_dict(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
errors = []
ret = {}
cmd_files = ['opkg', 'files']
if not packages:
packages = list(list_pkgs().keys())
for package in packages:
files = []
cmd = cmd_files[:]
cmd.append(package)
out = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
for line in out['stdout'].splitlines():
if line.startswith('/'):
files.append(line)
elif line.startswith(' * '):
errors.append(line[3:])
break
else:
continue
if files:
ret[package] = files
return {'errors': errors, 'packages': ret}
def owner(*paths, **kwargs): # pylint: disable=unused-argument
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.opkg.version`, if a single
path is passed, a string will be returned, and if multiple paths are passed,
a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
cmd_search = ['opkg', 'search']
for path in paths:
cmd = cmd_search[:]
cmd.append(path)
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
if output:
ret[path] = output.split(' - ')[0].strip()
else:
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def version_clean(version):
'''
Clean the version string removing extra data.
There's nothing do to here for nipkg.py, therefore it will always
return the given version.
'''
return version
def check_extra_requirements(pkgname, pkgver):
'''
Check if the installed package already has the given requirements.
There's nothing do to here for nipkg.py, therefore it will always
return True.
'''
return True
|
saltstack/salt
|
salt/modules/opkg.py
|
_execute_install_command
|
python
|
def _execute_install_command(cmd, parse_output, errors, parsed_packages):
'''
Executes a command for the install operation.
If the command fails, its error output will be appended to the errors list.
If the command succeeds and parse_output is true, updated packages will be appended
to the parsed_packages dictionary.
'''
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors.append(out['stderr'])
else:
errors.append(out['stdout'])
elif parse_output:
parsed_packages.update(_parse_reported_packages_from_install_output(out['stdout']))
|
Executes a command for the install operation.
If the command fails, its error output will be appended to the errors list.
If the command succeeds and parse_output is true, updated packages will be appended
to the parsed_packages dictionary.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/opkg.py#L359-L377
| null |
# -*- coding: utf-8 -*-
'''
Support for Opkg
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
.. versionadded: 2016.3.0
.. note::
For version comparison support on opkg < 0.3.4, the ``opkg-utils`` package
must be installed.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import os
import re
import logging
import errno
# Import salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.itertools
import salt.utils.path
import salt.utils.pkg
import salt.utils.stringutils
import salt.utils.versions
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import shlex_quote as _cmd_quote # pylint: disable=import-error
from salt.ext.six.moves import map # pylint: disable=import-error,redefined-builtin
REPO_REGEXP = r'^#?\s*(src|src/gz)\s+([^\s<>]+|"[^<>]+")\s+[^\s<>]+'
OPKG_CONFDIR = '/etc/opkg'
ATTR_MAP = {
'Architecture': 'arch',
'Homepage': 'url',
'Installed-Time': 'install_date_time_t',
'Maintainer': 'packager',
'Package': 'name',
'Section': 'group'
}
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
NILRT_RESTARTCHECK_STATE_PATH = '/var/lib/salt/restartcheck_state'
def _update_nilrt_restart_state():
'''
NILRT systems determine whether to reboot after various package operations
including but not limited to kernel module installs/removals by checking
specific file md5sums & timestamps. These files are touched/modified by
the post-install/post-remove functions of their respective packages.
The opkg module uses this function to store/update those file timestamps
and checksums to be used later by the restartcheck module.
'''
__salt__['cmd.shell']('stat -c %Y /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.timestamp'
.format(NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.md5sum'
.format(NILRT_RESTARTCHECK_STATE_PATH))
# We can't assume nisysapi.ini always exists like modules.dep
nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'
if os.path.exists(nisysapi_path):
__salt__['cmd.shell']('stat -c %Y {0} >{1}/nisysapi.ini.timestamp'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0} >{1}/nisysapi.ini.md5sum'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
# Expert plugin files get added to a conf.d dir, so keep track of the total
# no. of files, their timestamps and content hashes
nisysapi_conf_d_path = "/usr/lib/{0}/nisysapi/conf.d/experts/".format(
'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'
)
if os.path.exists(nisysapi_conf_d_path):
with salt.utils.files.fopen('{0}/sysapi.conf.d.count'.format(
NILRT_RESTARTCHECK_STATE_PATH), 'w') as fcount:
fcount.write(str(len(os.listdir(nisysapi_conf_d_path))))
for fexpert in os.listdir(nisysapi_conf_d_path):
__salt__['cmd.shell']('stat -c %Y {0}/{1} >{2}/{1}.timestamp'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0}/{1} >{2}/{1}.md5sum'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
def _get_restartcheck_result(errors):
'''
Return restartcheck result and append errors (if any) to ``errors``
'''
rs_result = __salt__['restartcheck.restartcheck'](verbose=False)
if isinstance(rs_result, dict) and 'comment' in rs_result:
errors.append(rs_result['comment'])
return rs_result
def _process_restartcheck_result(rs_result, **kwargs):
'''
Check restartcheck output to see if system/service restarts were requested
and take appropriate action.
'''
if 'No packages seem to need to be restarted' in rs_result:
return
reboot_required = False
for rstr in rs_result:
if 'System restart required' in rstr:
_update_nilrt_restart_state()
__salt__['system.set_reboot_required_witnessed']()
reboot_required = True
if kwargs.get('always_restart_services', True) or not reboot_required:
for rstr in rs_result:
if 'System restart required' not in rstr:
service = os.path.join('/etc/init.d', rstr)
if os.path.exists(service):
__salt__['cmd.run']([service, 'restart'])
def __virtual__():
'''
Confirm this module is on a nilrt based system
'''
if __grains__.get('os_family') == 'NILinuxRT':
try:
os.makedirs(NILRT_RESTARTCHECK_STATE_PATH)
except OSError as exc:
if exc.errno != errno.EEXIST:
return False, 'Error creating {0} (-{1}): {2}'.format(
NILRT_RESTARTCHECK_STATE_PATH,
exc.errno,
exc.strerror)
# populate state dir if empty
if not os.listdir(NILRT_RESTARTCHECK_STATE_PATH):
_update_nilrt_restart_state()
return __virtualname__
if os.path.isdir(OPKG_CONFDIR):
return __virtualname__
return False, "Module opkg only works on OpenEmbedded based systems"
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
if not names:
return ''
ret = {}
for name in names:
ret[name] = ''
# Refresh before looking for the latest version available
if refresh:
refresh_db()
cmd = ['opkg', 'list-upgradable']
out = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
try:
name, _oldversion, newversion = line.split(' - ')
if name in names:
ret[name] = newversion
except ValueError:
pass
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = latest_version
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(failhard=False, **kwargs): # pylint: disable=unused-argument
'''
Updates the opkg database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
failhard
If False, return results of failed lines as ``False`` for the package
database that encountered the error.
If True, raise an error with a list of the package databases that
encountered errors.
.. versionadded:: 2018.3.0
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
error_repos = []
cmd = ['opkg', 'update']
# opkg returns a non-zero retcode when there is a failure to refresh
# from one or more repos. Due to this, ignore the retcode.
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True,
redirect_stderr=True)
out = call['stdout']
prev_line = ''
for line in salt.utils.itertools.split(out, '\n'):
if 'Inflating' in line:
key = line.strip().split()[1][:-1]
ret[key] = True
elif 'Updated source' in line:
# Use the previous line.
key = prev_line.strip().split()[1][:-1]
ret[key] = True
elif 'Failed to download' in line:
key = line.strip().split()[5].split(',')[0]
ret[key] = False
error_repos.append(key)
prev_line = line
if failhard and error_repos:
raise CommandExecutionError(
'Error getting repos: {0}'.format(', '.join(error_repos))
)
# On a non-zero exit code where no failed repos were found, raise an
# exception because this appears to be a different kind of error.
if call['retcode'] != 0 and not error_repos:
raise CommandExecutionError(out)
return ret
def _is_testmode(**kwargs):
'''
Returns whether a test mode (noaction) operation was requested.
'''
return bool(kwargs.get('test') or __opts__.get('test'))
def _append_noaction_if_testmode(cmd, **kwargs):
'''
Adds the --noaction flag to the command if it's running in the test mode.
'''
if _is_testmode(**kwargs):
cmd.append('--noaction')
def _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall):
'''
Builds a list of install commands to be executed in sequence in order to process
each of the to_install, to_downgrade, and to_reinstall lists.
'''
cmds = []
if to_install:
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(to_install)
cmds.append(cmd)
if to_downgrade:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-downgrade')
cmd.extend(to_downgrade)
cmds.append(cmd)
if to_reinstall:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-reinstall')
cmd.extend(to_reinstall)
cmds.append(cmd)
return cmds
def _parse_reported_packages_from_install_output(output):
'''
Parses the output of "opkg install" to determine what packages would have been
installed by an operation run with the --noaction flag.
We are looking for lines like:
Installing <package> (<version>) on <target>
or
Upgrading <package> from <oldVersion> to <version> on root
'''
reported_pkgs = {}
install_pattern = re.compile(r'Installing\s(?P<package>.*?)\s\((?P<version>.*?)\)\son\s(?P<target>.*?)')
upgrade_pattern = re.compile(r'Upgrading\s(?P<package>.*?)\sfrom\s(?P<oldVersion>.*?)\sto\s(?P<version>.*?)\son\s(?P<target>.*?)')
for line in salt.utils.itertools.split(output, '\n'):
match = install_pattern.match(line)
if match is None:
match = upgrade_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = match.group('version')
return reported_pkgs
def install(name=None,
refresh=False,
pkgs=None,
sources=None,
reinstall=False,
**kwargs):
'''
Install the passed package, add refresh=True to update the opkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionadded:: 2017.7.0
reinstall : False
Specifying reinstall=True will use ``opkg install --force-reinstall``
rather than simply ``opkg install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``opkg
install --force-reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2017.7.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of IPK packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
install_recommends
Whether to install the packages marked as recommended. Default is True.
only_upgrade
Only upgrade the packages (disallow downgrades), if they are already
installed. Default is False.
.. versionadded:: 2017.7.0
always_restart_services
Whether to restart services even if a reboot is required. Default is True.
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
refreshdb = salt.utils.data.is_true(refresh)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
cmd_prefix = ['opkg', 'install']
to_install = []
to_reinstall = []
to_downgrade = []
_append_noaction_if_testmode(cmd_prefix, **kwargs)
if not pkg_params:
return {}
elif pkg_type == 'file':
if reinstall:
cmd_prefix.append('--force-reinstall')
if not kwargs.get('only_upgrade', False):
cmd_prefix.append('--force-downgrade')
to_install.extend(pkg_params)
elif pkg_type == 'repository':
if not kwargs.get('install_recommends', True):
cmd_prefix.append('--no-install-recommends')
for pkgname, pkgversion in six.iteritems(pkg_params):
if (name and pkgs is None and kwargs.get('version') and
len(pkg_params) == 1):
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
version_num = pkgversion
if version_num is None:
# Don't allow downgrades if the version
# number is not specified.
if reinstall and pkgname in old:
to_reinstall.append(pkgname)
else:
to_install.append(pkgname)
else:
pkgstr = '{0}={1}'.format(pkgname, version_num)
cver = old.get(pkgname, '')
if reinstall and cver and salt.utils.versions.compare(
ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall.append(pkgstr)
elif not cver or salt.utils.versions.compare(
ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
to_install.append(pkgstr)
else:
if not kwargs.get('only_upgrade', False):
to_downgrade.append(pkgstr)
else:
# This should cause the command to fail.
to_install.append(pkgstr)
cmds = _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall)
if not cmds:
return {}
if refreshdb:
refresh_db()
errors = []
is_testmode = _is_testmode(**kwargs)
test_packages = {}
for cmd in cmds:
_execute_install_command(cmd, is_testmode, errors, test_packages)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if is_testmode:
new = copy.deepcopy(new)
new.update(test_packages)
ret = salt.utils.data.compare_dicts(old, new)
if pkg_type == 'file' and reinstall:
# For file-based packages, prepare 'to_reinstall' to have a list
# of all the package names that may have been reinstalled.
# This way, we could include reinstalled packages in 'ret'.
for pkgfile in to_install:
# Convert from file name to package name.
cmd = ['opkg', 'info', pkgfile]
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] == 0:
# Just need the package name.
pkginfo_dict = _process_info_installed_output(
out['stdout'], []
)
if pkginfo_dict:
to_reinstall.append(list(pkginfo_dict.keys())[0])
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def _parse_reported_packages_from_remove_output(output):
'''
Parses the output of "opkg remove" to determine what packages would have been
removed by an operation run with the --noaction flag.
We are looking for lines like
Removing <package> (<version>) from <Target>...
'''
reported_pkgs = {}
remove_pattern = re.compile(r'Removing\s(?P<package>.*?)\s\((?P<version>.*?)\)\sfrom\s(?P<target>.*?)...')
for line in salt.utils.itertools.split(output, '\n'):
match = remove_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = ''
return reported_pkgs
def remove(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Remove packages using ``opkg remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
remove_dependencies
Remove package and all dependencies
.. versionadded:: 2019.2.0
auto_remove_deps
Remove packages that were installed automatically to satisfy dependencies
.. versionadded:: 2019.2.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
salt '*' pkg.remove pkgs='["foo", "bar"]' remove_dependencies=True auto_remove_deps=True
'''
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 {}
cmd = ['opkg', 'remove']
_append_noaction_if_testmode(cmd, **kwargs)
if kwargs.get('remove_dependencies', False):
cmd.append('--force-removal-of-dependent-packages')
if kwargs.get('auto_remove_deps', False):
cmd.append('--autoremove')
cmd.extend(targets)
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors = [out['stderr']]
else:
errors = [out['stdout']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if _is_testmode(**kwargs):
reportedPkgs = _parse_reported_packages_from_remove_output(out['stdout'])
new = {k: v for k, v in new.items() if k not in reportedPkgs}
ret = salt.utils.data.compare_dicts(old, new)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def purge(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Package purges are not supported by opkg, this function is identical to
:mod:`pkg.remove <salt.modules.opkg.remove>`.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name, pkgs=pkgs)
def upgrade(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
Upgrades all packages via ``opkg upgrade``
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
errors = []
if salt.utils.data.is_true(refresh):
refresh_db()
old = list_pkgs()
cmd = ['opkg', 'upgrade']
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
errors.append(result)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif state != 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = _set_state(target, 'hold')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif state == 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret['comment'] = ('Package {0} is set not to be held.'
.format(target))
else:
result = _set_state(target, 'ok')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def _get_state(pkg):
'''
View package state from the opkg database
Return the state of pkg
'''
cmd = ['opkg', 'status']
cmd.append(pkg)
out = __salt__['cmd.run'](cmd, python_shell=False)
state_flag = ''
for line in salt.utils.itertools.split(out, '\n'):
if line.startswith('Status'):
_status, _state_want, state_flag, _state_status = line.split()
return state_flag
def _set_state(pkg, state):
'''
Change package state on the opkg database
The state can be any of:
- hold
- noprune
- user
- ok
- installed
- unpacked
This command is commonly used to mark a specific package to be held from
being upgraded, that is, to be kept at a certain version.
Returns a dict containing the package name, and the new and old
versions.
'''
ret = {}
valid_states = ('hold', 'noprune', 'user', 'ok', 'installed', 'unpacked')
if state not in valid_states:
raise SaltInvocationError('Invalid state: {0}'.format(state))
oldstate = _get_state(pkg)
cmd = ['opkg', 'flag']
cmd.append(state)
cmd.append(pkg)
_out = __salt__['cmd.run'](cmd, python_shell=False)
# Missing return value check due to opkg issue 160
ret[pkg] = {'old': oldstate,
'new': state}
return ret
def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
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
cmd = ['opkg', 'list-installed']
ret = {}
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
# This is a continuation of package description
if not line or line[0] == ' ':
continue
# This contains package name, version, and description.
# Extract the first two.
pkg_name, pkg_version = line.split(' - ', 2)[:2]
__salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version)
__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 list_upgrades(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
List all available package upgrades.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
ret = {}
if salt.utils.data.is_true(refresh):
refresh_db()
cmd = ['opkg', 'list-upgradable']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
if 'stdout' in call:
comment += call['stdout']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
name, _oldversion, newversion = line.split(' - ')
ret[name] = newversion
return ret
def _convert_to_standard_attr(attr):
'''
Helper function for _process_info_installed_output()
Converts an opkg attribute name to a standard attribute
name which is used across 'pkg' modules.
'''
ret_attr = ATTR_MAP.get(attr, None)
if ret_attr is None:
# All others convert to lowercase
return attr.lower()
return ret_attr
def _process_info_installed_output(out, filter_attrs):
'''
Helper function for info_installed()
Processes stdout output from a single invocation of
'opkg status'.
'''
ret = {}
name = None
attrs = {}
attr = None
for line in salt.utils.itertools.split(out, '\n'):
if line and line[0] == ' ':
# This is a continuation of the last attr
if filter_attrs is None or attr in filter_attrs:
line = line.strip()
if attrs[attr]:
# If attr is empty, don't add leading newline
attrs[attr] += '\n'
attrs[attr] += line
continue
line = line.strip()
if not line:
# Separator between different packages
if name:
ret[name] = attrs
name = None
attrs = {}
attr = None
continue
key, value = line.split(':', 1)
value = value.lstrip()
attr = _convert_to_standard_attr(key)
if attr == 'name':
name = value
elif filter_attrs is None or attr in filter_attrs:
attrs[attr] = value
if name:
ret[name] = attrs
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
.. versionadded:: 2017.7.0
:param names:
Names of the packages to get information about. If none are specified,
will return information for all installed packages.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
arch, conffiles, conflicts, depends, description, filename, group,
install_date_time_t, md5sum, packager, provides, recommends,
replaces, size, source, suggests, url, version
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed
salt '*' pkg.info_installed attr=version,packager
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> attr=version,packager
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,packager
'''
attr = kwargs.pop('attr', None)
if attr is None:
filter_attrs = None
elif isinstance(attr, six.string_types):
filter_attrs = set(attr.split(','))
else:
filter_attrs = set(attr)
ret = {}
if names:
# Specific list of names of installed packages
for name in names:
cmd = ['opkg', 'status', name]
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
else:
# All installed packages
cmd = ['opkg', 'status']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
return ret
def upgrade_available(name, **kwargs): # pylint: disable=unused-argument
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs): # pylint: disable=unused-argument
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2016.3.4
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0' '0.2.4.1-0'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] if ignore_epoch else six.text_type(x)
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
output = __salt__['cmd.run_stdout'](['opkg', '--version'],
output_loglevel='trace',
python_shell=False)
opkg_version = output.split(' ')[2].strip()
if salt.utils.versions.LooseVersion(opkg_version) >= \
salt.utils.versions.LooseVersion('0.3.4'):
cmd_compare = ['opkg', 'compare-versions']
elif salt.utils.path.which('opkg-compare-versions'):
cmd_compare = ['opkg-compare-versions']
else:
log.warning('Unable to find a compare-versions utility installed. Either upgrade opkg to '
'version > 0.3.4 (preferred) or install the older opkg-compare-versions script.')
return None
for oper, ret in (("<<", -1), ("=", 0), (">>", 1)):
cmd = cmd_compare[:]
cmd.append(_cmd_quote(pkg1))
cmd.append(oper)
cmd.append(_cmd_quote(pkg2))
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
ignore_retcode=True,
python_shell=False)
if retcode == 0:
return ret
return None
def _set_repo_option(repo, option):
'''
Set the option to repo
'''
if not option:
return
opt = option.split('=')
if len(opt) != 2:
return
if opt[0] == 'trusted':
repo['trusted'] = opt[1] == 'yes'
else:
repo[opt[0]] = opt[1]
def _set_repo_options(repo, options):
'''
Set the options to the repo.
'''
delimiters = "[", "]"
pattern = '|'.join(map(re.escape, delimiters))
for option in options:
splitted = re.split(pattern, option)
for opt in splitted:
_set_repo_option(repo, opt)
def _create_repo(line, filename):
'''
Create repo
'''
repo = {}
if line.startswith('#'):
repo['enabled'] = False
line = line[1:]
else:
repo['enabled'] = True
cols = salt.utils.args.shlex_split(line.strip())
repo['compressed'] = not cols[0] in 'src'
repo['name'] = cols[1]
repo['uri'] = cols[2]
repo['file'] = os.path.join(OPKG_CONFDIR, filename)
if len(cols) > 3:
_set_repo_options(repo, cols[3:])
return repo
def _read_repos(conf_file, repos, filename, regex):
'''
Read repos from configuration file
'''
for line in conf_file:
line = salt.utils.stringutils.to_unicode(line)
if not regex.search(line):
continue
repo = _create_repo(line, filename)
# do not store duplicated uri's
if repo['uri'] not in repos:
repos[repo['uri']] = [repo]
def list_repos(**kwargs): # pylint: disable=unused-argument
'''
Lists all repos on ``/etc/opkg/*.conf``
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos = {}
regex = re.compile(REPO_REGEXP)
for filename in os.listdir(OPKG_CONFDIR):
if not filename.endswith(".conf"):
continue
with salt.utils.files.fopen(os.path.join(OPKG_CONFDIR, filename)) as conf_file:
_read_repos(conf_file, repos, filename, regex)
return repos
def get_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Display a repo from the ``/etc/opkg/*.conf``
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo repo
'''
repos = list_repos()
if repos:
for source in six.itervalues(repos):
for sub in source:
if sub['name'] == repo:
return sub
return {}
def _del_repo_from_file(repo, filepath):
'''
Remove a repo from filepath
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
regex = re.compile(REPO_REGEXP)
for line in fhandle:
line = salt.utils.stringutils.to_unicode(line)
if regex.search(line):
if line.startswith('#'):
line = line[1:]
cols = salt.utils.args.shlex_split(line.strip())
if repo != cols[1]:
output.append(salt.utils.stringutils.to_str(line))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def _set_trusted_option_if_needed(repostr, trusted):
'''
Set trusted option to repo if needed
'''
if trusted is True:
repostr += ' [trusted=yes]'
elif trusted is False:
repostr += ' [trusted=no]'
return repostr
def _add_new_repo(repo, properties):
'''
Add a new repo entry
'''
repostr = '# ' if not properties.get('enabled') else ''
repostr += 'src/gz ' if properties.get('compressed') else 'src '
if ' ' in repo:
repostr += '"' + repo + '" '
else:
repostr += repo + ' '
repostr += properties.get('uri')
repostr = _set_trusted_option_if_needed(repostr, properties.get('trusted'))
repostr += '\n'
conffile = os.path.join(OPKG_CONFDIR, repo + '.conf')
with salt.utils.files.fopen(conffile, 'a') as fhandle:
fhandle.write(salt.utils.stringutils.to_str(repostr))
def _mod_repo_in_file(repo, repostr, filepath):
'''
Replace a repo entry in filepath with repostr
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
for line in fhandle:
cols = salt.utils.args.shlex_split(
salt.utils.stringutils.to_unicode(line).strip()
)
if repo not in cols:
output.append(line)
else:
output.append(salt.utils.stringutils.to_str(repostr + '\n'))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def del_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Delete a repo from ``/etc/opkg/*.conf``
If the file does not contain any other repo configuration, the file itself
will be deleted.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo repo
'''
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
repos = list_repos()
if repos:
deleted_from = dict()
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
deleted_from[source['file']] = 0
_del_repo_from_file(repo, source['file'])
if deleted_from:
ret = ''
for repository in repos:
source = repos[repository][0]
if source['file'] in deleted_from:
deleted_from[source['file']] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 1 and os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.\n')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
if refresh:
refresh_db()
return ret
return "Repo {0} doesn't exist in the opkg repo lists".format(repo)
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as uri is defined.
The following options are available to modify a repo definition:
repo
alias by which opkg refers to the repo.
uri
the URI to the repo.
compressed
defines (True or False) if the index file is compressed
enabled
enable or disable (True or False) repository
but do not remove if disabled.
refresh
enable or disable (True or False) auto-refresh of the repositories
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo repo uri=http://new/uri
salt '*' pkg.mod_repo repo enabled=False
'''
repos = list_repos()
found = False
uri = ''
if 'uri' in kwargs:
uri = kwargs['uri']
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
found = True
repostr = ''
if 'enabled' in kwargs and not kwargs['enabled']:
repostr += '# '
if 'compressed' in kwargs:
repostr += 'src/gz ' if kwargs['compressed'] else 'src'
else:
repostr += 'src/gz' if source['compressed'] else 'src'
repo_alias = kwargs['alias'] if 'alias' in kwargs else repo
if ' ' in repo_alias:
repostr += ' "{0}"'.format(repo_alias)
else:
repostr += ' {0}'.format(repo_alias)
repostr += ' {0}'.format(kwargs['uri'] if 'uri' in kwargs else source['uri'])
trusted = kwargs.get('trusted')
repostr = _set_trusted_option_if_needed(repostr, trusted) if trusted is not None else \
_set_trusted_option_if_needed(repostr, source.get('trusted'))
_mod_repo_in_file(repo, repostr, source['file'])
elif uri and source['uri'] == uri:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(uri, source['name']))
if not found:
# Need to add a new repo
if 'uri' not in kwargs:
raise CommandExecutionError(
'Repository \'{0}\' not found and no URI passed to create one.'.format(repo))
properties = {'uri': kwargs['uri']}
# If compressed is not defined, assume True
properties['compressed'] = kwargs['compressed'] if 'compressed' in kwargs else True
# If enabled is not defined, assume True
properties['enabled'] = kwargs['enabled'] if 'enabled' in kwargs else True
properties['trusted'] = kwargs.get('trusted')
_add_new_repo(repo, properties)
if 'refresh' in kwargs:
refresh_db()
def file_list(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
output = file_dict(*packages)
files = []
for package in list(output['packages'].values()):
files.extend(package)
return {'errors': output['errors'], 'files': files}
def file_dict(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
errors = []
ret = {}
cmd_files = ['opkg', 'files']
if not packages:
packages = list(list_pkgs().keys())
for package in packages:
files = []
cmd = cmd_files[:]
cmd.append(package)
out = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
for line in out['stdout'].splitlines():
if line.startswith('/'):
files.append(line)
elif line.startswith(' * '):
errors.append(line[3:])
break
else:
continue
if files:
ret[package] = files
return {'errors': errors, 'packages': ret}
def owner(*paths, **kwargs): # pylint: disable=unused-argument
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.opkg.version`, if a single
path is passed, a string will be returned, and if multiple paths are passed,
a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
cmd_search = ['opkg', 'search']
for path in paths:
cmd = cmd_search[:]
cmd.append(path)
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
if output:
ret[path] = output.split(' - ')[0].strip()
else:
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def version_clean(version):
'''
Clean the version string removing extra data.
There's nothing do to here for nipkg.py, therefore it will always
return the given version.
'''
return version
def check_extra_requirements(pkgname, pkgver):
'''
Check if the installed package already has the given requirements.
There's nothing do to here for nipkg.py, therefore it will always
return True.
'''
return True
|
saltstack/salt
|
salt/modules/opkg.py
|
install
|
python
|
def install(name=None,
refresh=False,
pkgs=None,
sources=None,
reinstall=False,
**kwargs):
'''
Install the passed package, add refresh=True to update the opkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionadded:: 2017.7.0
reinstall : False
Specifying reinstall=True will use ``opkg install --force-reinstall``
rather than simply ``opkg install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``opkg
install --force-reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2017.7.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of IPK packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
install_recommends
Whether to install the packages marked as recommended. Default is True.
only_upgrade
Only upgrade the packages (disallow downgrades), if they are already
installed. Default is False.
.. versionadded:: 2017.7.0
always_restart_services
Whether to restart services even if a reboot is required. Default is True.
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
refreshdb = salt.utils.data.is_true(refresh)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
cmd_prefix = ['opkg', 'install']
to_install = []
to_reinstall = []
to_downgrade = []
_append_noaction_if_testmode(cmd_prefix, **kwargs)
if not pkg_params:
return {}
elif pkg_type == 'file':
if reinstall:
cmd_prefix.append('--force-reinstall')
if not kwargs.get('only_upgrade', False):
cmd_prefix.append('--force-downgrade')
to_install.extend(pkg_params)
elif pkg_type == 'repository':
if not kwargs.get('install_recommends', True):
cmd_prefix.append('--no-install-recommends')
for pkgname, pkgversion in six.iteritems(pkg_params):
if (name and pkgs is None and kwargs.get('version') and
len(pkg_params) == 1):
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
version_num = pkgversion
if version_num is None:
# Don't allow downgrades if the version
# number is not specified.
if reinstall and pkgname in old:
to_reinstall.append(pkgname)
else:
to_install.append(pkgname)
else:
pkgstr = '{0}={1}'.format(pkgname, version_num)
cver = old.get(pkgname, '')
if reinstall and cver and salt.utils.versions.compare(
ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall.append(pkgstr)
elif not cver or salt.utils.versions.compare(
ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
to_install.append(pkgstr)
else:
if not kwargs.get('only_upgrade', False):
to_downgrade.append(pkgstr)
else:
# This should cause the command to fail.
to_install.append(pkgstr)
cmds = _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall)
if not cmds:
return {}
if refreshdb:
refresh_db()
errors = []
is_testmode = _is_testmode(**kwargs)
test_packages = {}
for cmd in cmds:
_execute_install_command(cmd, is_testmode, errors, test_packages)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if is_testmode:
new = copy.deepcopy(new)
new.update(test_packages)
ret = salt.utils.data.compare_dicts(old, new)
if pkg_type == 'file' and reinstall:
# For file-based packages, prepare 'to_reinstall' to have a list
# of all the package names that may have been reinstalled.
# This way, we could include reinstalled packages in 'ret'.
for pkgfile in to_install:
# Convert from file name to package name.
cmd = ['opkg', 'info', pkgfile]
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] == 0:
# Just need the package name.
pkginfo_dict = _process_info_installed_output(
out['stdout'], []
)
if pkginfo_dict:
to_reinstall.append(list(pkginfo_dict.keys())[0])
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
|
Install the passed package, add refresh=True to update the opkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionadded:: 2017.7.0
reinstall : False
Specifying reinstall=True will use ``opkg install --force-reinstall``
rather than simply ``opkg install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``opkg
install --force-reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2017.7.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of IPK packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
install_recommends
Whether to install the packages marked as recommended. Default is True.
only_upgrade
Only upgrade the packages (disallow downgrades), if they are already
installed. Default is False.
.. versionadded:: 2017.7.0
always_restart_services
Whether to restart services even if a reboot is required. Default is True.
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/opkg.py#L380-L587
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def is_true(value=None):\n '''\n Returns a boolean value representing the \"truth\" of the value passed. The\n rules for what is a \"True\" value are:\n\n 1. Integer/float values greater than 0\n 2. The string values \"True\" and \"true\"\n 3. Any object for which bool(obj) returns True\n '''\n # First, try int/float conversion\n try:\n value = int(value)\n except (ValueError, TypeError):\n pass\n try:\n value = float(value)\n except (ValueError, TypeError):\n pass\n\n # Now check for truthiness\n if isinstance(value, (six.integer_types, float)):\n return value > 0\n elif isinstance(value, six.string_types):\n return six.text_type(value).lower() == 'true'\n else:\n return bool(value)\n",
"def compare(ver1='', oper='==', ver2='', cmp_func=None, ignore_epoch=False):\n '''\n Compares two version numbers. Accepts a custom function to perform the\n cmp-style version comparison, otherwise uses version_cmp().\n '''\n cmp_map = {'<': (-1,), '<=': (-1, 0), '==': (0,),\n '>=': (0, 1), '>': (1,)}\n if oper not in ('!=',) and oper not in cmp_map:\n log.error('Invalid operator \\'%s\\' for version comparison', oper)\n return False\n\n if cmp_func is None:\n cmp_func = version_cmp\n\n cmp_result = cmp_func(ver1, ver2, ignore_epoch=ignore_epoch)\n if cmp_result is None:\n return False\n\n # Check if integer/long\n if not isinstance(cmp_result, numbers.Integral):\n log.error('The version comparison function did not return an '\n 'integer/long.')\n return False\n\n if oper == '!=':\n return cmp_result not in cmp_map['==']\n else:\n # Gracefully handle cmp_result not in (-1, 0, 1).\n if cmp_result < -1:\n cmp_result = -1\n elif cmp_result > 1:\n cmp_result = 1\n\n return cmp_result in cmp_map[oper]\n",
"def list_pkgs(versions_as_list=False, **kwargs):\n '''\n List the packages currently installed in a dict::\n\n {'<package_name>': '<version>'}\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.list_pkgs\n salt '*' pkg.list_pkgs versions_as_list=True\n '''\n versions_as_list = salt.utils.data.is_true(versions_as_list)\n # not yet implemented or not applicable\n if any([salt.utils.data.is_true(kwargs.get(x))\n for x in ('removed', 'purge_desired')]):\n return {}\n\n if 'pkg.list_pkgs' in __context__:\n if versions_as_list:\n return __context__['pkg.list_pkgs']\n else:\n ret = copy.deepcopy(__context__['pkg.list_pkgs'])\n __salt__['pkg_resource.stringify'](ret)\n return ret\n\n cmd = ['opkg', 'list-installed']\n ret = {}\n out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)\n for line in salt.utils.itertools.split(out, '\\n'):\n # This is a continuation of package description\n if not line or line[0] == ' ':\n continue\n\n # This contains package name, version, and description.\n # Extract the first two.\n pkg_name, pkg_version = line.split(' - ', 2)[:2]\n __salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version)\n\n __salt__['pkg_resource.sort_pkglist'](ret)\n __context__['pkg.list_pkgs'] = copy.deepcopy(ret)\n if not versions_as_list:\n __salt__['pkg_resource.stringify'](ret)\n return ret\n",
"def refresh_db(failhard=False, **kwargs): # pylint: disable=unused-argument\n '''\n Updates the opkg database to latest packages based upon repositories\n\n Returns a dict, with the keys being package databases and the values being\n the result of the update attempt. Values can be one of the following:\n\n - ``True``: Database updated successfully\n - ``False``: Problem updating database\n\n failhard\n If False, return results of failed lines as ``False`` for the package\n database that encountered the error.\n If True, raise an error with a list of the package databases that\n encountered errors.\n\n .. versionadded:: 2018.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.refresh_db\n '''\n # Remove rtag file to keep multiple refreshes from happening in pkg states\n salt.utils.pkg.clear_rtag(__opts__)\n ret = {}\n error_repos = []\n cmd = ['opkg', 'update']\n # opkg returns a non-zero retcode when there is a failure to refresh\n # from one or more repos. Due to this, ignore the retcode.\n call = __salt__['cmd.run_all'](cmd,\n output_loglevel='trace',\n python_shell=False,\n ignore_retcode=True,\n redirect_stderr=True)\n\n out = call['stdout']\n prev_line = ''\n for line in salt.utils.itertools.split(out, '\\n'):\n if 'Inflating' in line:\n key = line.strip().split()[1][:-1]\n ret[key] = True\n elif 'Updated source' in line:\n # Use the previous line.\n key = prev_line.strip().split()[1][:-1]\n ret[key] = True\n elif 'Failed to download' in line:\n key = line.strip().split()[5].split(',')[0]\n ret[key] = False\n error_repos.append(key)\n prev_line = line\n\n if failhard and error_repos:\n raise CommandExecutionError(\n 'Error getting repos: {0}'.format(', '.join(error_repos))\n )\n\n # On a non-zero exit code where no failed repos were found, raise an\n # exception because this appears to be a different kind of error.\n if call['retcode'] != 0 and not error_repos:\n raise CommandExecutionError(out)\n\n return ret\n",
"def _get_restartcheck_result(errors):\n '''\n Return restartcheck result and append errors (if any) to ``errors``\n '''\n rs_result = __salt__['restartcheck.restartcheck'](verbose=False)\n if isinstance(rs_result, dict) and 'comment' in rs_result:\n errors.append(rs_result['comment'])\n return rs_result\n",
"def _process_restartcheck_result(rs_result, **kwargs):\n '''\n Check restartcheck output to see if system/service restarts were requested\n and take appropriate action.\n '''\n if 'No packages seem to need to be restarted' in rs_result:\n return\n reboot_required = False\n for rstr in rs_result:\n if 'System restart required' in rstr:\n _update_nilrt_restart_state()\n __salt__['system.set_reboot_required_witnessed']()\n reboot_required = True\n if kwargs.get('always_restart_services', True) or not reboot_required:\n for rstr in rs_result:\n if 'System restart required' not in rstr:\n service = os.path.join('/etc/init.d', rstr)\n if os.path.exists(service):\n __salt__['cmd.run']([service, 'restart'])\n",
"def _is_testmode(**kwargs):\n '''\n Returns whether a test mode (noaction) operation was requested.\n '''\n return bool(kwargs.get('test') or __opts__.get('test'))\n",
"def _append_noaction_if_testmode(cmd, **kwargs):\n '''\n Adds the --noaction flag to the command if it's running in the test mode.\n '''\n if _is_testmode(**kwargs):\n cmd.append('--noaction')\n",
"def _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall):\n '''\n Builds a list of install commands to be executed in sequence in order to process\n each of the to_install, to_downgrade, and to_reinstall lists.\n '''\n cmds = []\n if to_install:\n cmd = copy.deepcopy(cmd_prefix)\n cmd.extend(to_install)\n cmds.append(cmd)\n if to_downgrade:\n cmd = copy.deepcopy(cmd_prefix)\n cmd.append('--force-downgrade')\n cmd.extend(to_downgrade)\n cmds.append(cmd)\n if to_reinstall:\n cmd = copy.deepcopy(cmd_prefix)\n cmd.append('--force-reinstall')\n cmd.extend(to_reinstall)\n cmds.append(cmd)\n\n return cmds\n",
"def _execute_install_command(cmd, parse_output, errors, parsed_packages):\n '''\n Executes a command for the install operation.\n If the command fails, its error output will be appended to the errors list.\n If the command succeeds and parse_output is true, updated packages will be appended\n to the parsed_packages dictionary.\n '''\n out = __salt__['cmd.run_all'](\n cmd,\n output_loglevel='trace',\n python_shell=False\n )\n if out['retcode'] != 0:\n if out['stderr']:\n errors.append(out['stderr'])\n else:\n errors.append(out['stdout'])\n elif parse_output:\n parsed_packages.update(_parse_reported_packages_from_install_output(out['stdout']))\n",
"def _process_info_installed_output(out, filter_attrs):\n '''\n Helper function for info_installed()\n\n Processes stdout output from a single invocation of\n 'opkg status'.\n '''\n ret = {}\n name = None\n attrs = {}\n attr = None\n\n for line in salt.utils.itertools.split(out, '\\n'):\n if line and line[0] == ' ':\n # This is a continuation of the last attr\n if filter_attrs is None or attr in filter_attrs:\n line = line.strip()\n if attrs[attr]:\n # If attr is empty, don't add leading newline\n attrs[attr] += '\\n'\n attrs[attr] += line\n continue\n line = line.strip()\n if not line:\n # Separator between different packages\n if name:\n ret[name] = attrs\n name = None\n attrs = {}\n attr = None\n continue\n key, value = line.split(':', 1)\n value = value.lstrip()\n attr = _convert_to_standard_attr(key)\n if attr == 'name':\n name = value\n elif filter_attrs is None or attr in filter_attrs:\n attrs[attr] = value\n\n if name:\n ret[name] = attrs\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Opkg
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
.. versionadded: 2016.3.0
.. note::
For version comparison support on opkg < 0.3.4, the ``opkg-utils`` package
must be installed.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import os
import re
import logging
import errno
# Import salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.itertools
import salt.utils.path
import salt.utils.pkg
import salt.utils.stringutils
import salt.utils.versions
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import shlex_quote as _cmd_quote # pylint: disable=import-error
from salt.ext.six.moves import map # pylint: disable=import-error,redefined-builtin
REPO_REGEXP = r'^#?\s*(src|src/gz)\s+([^\s<>]+|"[^<>]+")\s+[^\s<>]+'
OPKG_CONFDIR = '/etc/opkg'
ATTR_MAP = {
'Architecture': 'arch',
'Homepage': 'url',
'Installed-Time': 'install_date_time_t',
'Maintainer': 'packager',
'Package': 'name',
'Section': 'group'
}
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
NILRT_RESTARTCHECK_STATE_PATH = '/var/lib/salt/restartcheck_state'
def _update_nilrt_restart_state():
'''
NILRT systems determine whether to reboot after various package operations
including but not limited to kernel module installs/removals by checking
specific file md5sums & timestamps. These files are touched/modified by
the post-install/post-remove functions of their respective packages.
The opkg module uses this function to store/update those file timestamps
and checksums to be used later by the restartcheck module.
'''
__salt__['cmd.shell']('stat -c %Y /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.timestamp'
.format(NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.md5sum'
.format(NILRT_RESTARTCHECK_STATE_PATH))
# We can't assume nisysapi.ini always exists like modules.dep
nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'
if os.path.exists(nisysapi_path):
__salt__['cmd.shell']('stat -c %Y {0} >{1}/nisysapi.ini.timestamp'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0} >{1}/nisysapi.ini.md5sum'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
# Expert plugin files get added to a conf.d dir, so keep track of the total
# no. of files, their timestamps and content hashes
nisysapi_conf_d_path = "/usr/lib/{0}/nisysapi/conf.d/experts/".format(
'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'
)
if os.path.exists(nisysapi_conf_d_path):
with salt.utils.files.fopen('{0}/sysapi.conf.d.count'.format(
NILRT_RESTARTCHECK_STATE_PATH), 'w') as fcount:
fcount.write(str(len(os.listdir(nisysapi_conf_d_path))))
for fexpert in os.listdir(nisysapi_conf_d_path):
__salt__['cmd.shell']('stat -c %Y {0}/{1} >{2}/{1}.timestamp'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0}/{1} >{2}/{1}.md5sum'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
def _get_restartcheck_result(errors):
'''
Return restartcheck result and append errors (if any) to ``errors``
'''
rs_result = __salt__['restartcheck.restartcheck'](verbose=False)
if isinstance(rs_result, dict) and 'comment' in rs_result:
errors.append(rs_result['comment'])
return rs_result
def _process_restartcheck_result(rs_result, **kwargs):
'''
Check restartcheck output to see if system/service restarts were requested
and take appropriate action.
'''
if 'No packages seem to need to be restarted' in rs_result:
return
reboot_required = False
for rstr in rs_result:
if 'System restart required' in rstr:
_update_nilrt_restart_state()
__salt__['system.set_reboot_required_witnessed']()
reboot_required = True
if kwargs.get('always_restart_services', True) or not reboot_required:
for rstr in rs_result:
if 'System restart required' not in rstr:
service = os.path.join('/etc/init.d', rstr)
if os.path.exists(service):
__salt__['cmd.run']([service, 'restart'])
def __virtual__():
'''
Confirm this module is on a nilrt based system
'''
if __grains__.get('os_family') == 'NILinuxRT':
try:
os.makedirs(NILRT_RESTARTCHECK_STATE_PATH)
except OSError as exc:
if exc.errno != errno.EEXIST:
return False, 'Error creating {0} (-{1}): {2}'.format(
NILRT_RESTARTCHECK_STATE_PATH,
exc.errno,
exc.strerror)
# populate state dir if empty
if not os.listdir(NILRT_RESTARTCHECK_STATE_PATH):
_update_nilrt_restart_state()
return __virtualname__
if os.path.isdir(OPKG_CONFDIR):
return __virtualname__
return False, "Module opkg only works on OpenEmbedded based systems"
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
if not names:
return ''
ret = {}
for name in names:
ret[name] = ''
# Refresh before looking for the latest version available
if refresh:
refresh_db()
cmd = ['opkg', 'list-upgradable']
out = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
try:
name, _oldversion, newversion = line.split(' - ')
if name in names:
ret[name] = newversion
except ValueError:
pass
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = latest_version
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(failhard=False, **kwargs): # pylint: disable=unused-argument
'''
Updates the opkg database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
failhard
If False, return results of failed lines as ``False`` for the package
database that encountered the error.
If True, raise an error with a list of the package databases that
encountered errors.
.. versionadded:: 2018.3.0
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
error_repos = []
cmd = ['opkg', 'update']
# opkg returns a non-zero retcode when there is a failure to refresh
# from one or more repos. Due to this, ignore the retcode.
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True,
redirect_stderr=True)
out = call['stdout']
prev_line = ''
for line in salt.utils.itertools.split(out, '\n'):
if 'Inflating' in line:
key = line.strip().split()[1][:-1]
ret[key] = True
elif 'Updated source' in line:
# Use the previous line.
key = prev_line.strip().split()[1][:-1]
ret[key] = True
elif 'Failed to download' in line:
key = line.strip().split()[5].split(',')[0]
ret[key] = False
error_repos.append(key)
prev_line = line
if failhard and error_repos:
raise CommandExecutionError(
'Error getting repos: {0}'.format(', '.join(error_repos))
)
# On a non-zero exit code where no failed repos were found, raise an
# exception because this appears to be a different kind of error.
if call['retcode'] != 0 and not error_repos:
raise CommandExecutionError(out)
return ret
def _is_testmode(**kwargs):
'''
Returns whether a test mode (noaction) operation was requested.
'''
return bool(kwargs.get('test') or __opts__.get('test'))
def _append_noaction_if_testmode(cmd, **kwargs):
'''
Adds the --noaction flag to the command if it's running in the test mode.
'''
if _is_testmode(**kwargs):
cmd.append('--noaction')
def _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall):
'''
Builds a list of install commands to be executed in sequence in order to process
each of the to_install, to_downgrade, and to_reinstall lists.
'''
cmds = []
if to_install:
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(to_install)
cmds.append(cmd)
if to_downgrade:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-downgrade')
cmd.extend(to_downgrade)
cmds.append(cmd)
if to_reinstall:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-reinstall')
cmd.extend(to_reinstall)
cmds.append(cmd)
return cmds
def _parse_reported_packages_from_install_output(output):
'''
Parses the output of "opkg install" to determine what packages would have been
installed by an operation run with the --noaction flag.
We are looking for lines like:
Installing <package> (<version>) on <target>
or
Upgrading <package> from <oldVersion> to <version> on root
'''
reported_pkgs = {}
install_pattern = re.compile(r'Installing\s(?P<package>.*?)\s\((?P<version>.*?)\)\son\s(?P<target>.*?)')
upgrade_pattern = re.compile(r'Upgrading\s(?P<package>.*?)\sfrom\s(?P<oldVersion>.*?)\sto\s(?P<version>.*?)\son\s(?P<target>.*?)')
for line in salt.utils.itertools.split(output, '\n'):
match = install_pattern.match(line)
if match is None:
match = upgrade_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = match.group('version')
return reported_pkgs
def _execute_install_command(cmd, parse_output, errors, parsed_packages):
'''
Executes a command for the install operation.
If the command fails, its error output will be appended to the errors list.
If the command succeeds and parse_output is true, updated packages will be appended
to the parsed_packages dictionary.
'''
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors.append(out['stderr'])
else:
errors.append(out['stdout'])
elif parse_output:
parsed_packages.update(_parse_reported_packages_from_install_output(out['stdout']))
def _parse_reported_packages_from_remove_output(output):
'''
Parses the output of "opkg remove" to determine what packages would have been
removed by an operation run with the --noaction flag.
We are looking for lines like
Removing <package> (<version>) from <Target>...
'''
reported_pkgs = {}
remove_pattern = re.compile(r'Removing\s(?P<package>.*?)\s\((?P<version>.*?)\)\sfrom\s(?P<target>.*?)...')
for line in salt.utils.itertools.split(output, '\n'):
match = remove_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = ''
return reported_pkgs
def remove(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Remove packages using ``opkg remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
remove_dependencies
Remove package and all dependencies
.. versionadded:: 2019.2.0
auto_remove_deps
Remove packages that were installed automatically to satisfy dependencies
.. versionadded:: 2019.2.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
salt '*' pkg.remove pkgs='["foo", "bar"]' remove_dependencies=True auto_remove_deps=True
'''
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 {}
cmd = ['opkg', 'remove']
_append_noaction_if_testmode(cmd, **kwargs)
if kwargs.get('remove_dependencies', False):
cmd.append('--force-removal-of-dependent-packages')
if kwargs.get('auto_remove_deps', False):
cmd.append('--autoremove')
cmd.extend(targets)
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors = [out['stderr']]
else:
errors = [out['stdout']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if _is_testmode(**kwargs):
reportedPkgs = _parse_reported_packages_from_remove_output(out['stdout'])
new = {k: v for k, v in new.items() if k not in reportedPkgs}
ret = salt.utils.data.compare_dicts(old, new)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def purge(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Package purges are not supported by opkg, this function is identical to
:mod:`pkg.remove <salt.modules.opkg.remove>`.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name, pkgs=pkgs)
def upgrade(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
Upgrades all packages via ``opkg upgrade``
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
errors = []
if salt.utils.data.is_true(refresh):
refresh_db()
old = list_pkgs()
cmd = ['opkg', 'upgrade']
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
errors.append(result)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif state != 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = _set_state(target, 'hold')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif state == 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret['comment'] = ('Package {0} is set not to be held.'
.format(target))
else:
result = _set_state(target, 'ok')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def _get_state(pkg):
'''
View package state from the opkg database
Return the state of pkg
'''
cmd = ['opkg', 'status']
cmd.append(pkg)
out = __salt__['cmd.run'](cmd, python_shell=False)
state_flag = ''
for line in salt.utils.itertools.split(out, '\n'):
if line.startswith('Status'):
_status, _state_want, state_flag, _state_status = line.split()
return state_flag
def _set_state(pkg, state):
'''
Change package state on the opkg database
The state can be any of:
- hold
- noprune
- user
- ok
- installed
- unpacked
This command is commonly used to mark a specific package to be held from
being upgraded, that is, to be kept at a certain version.
Returns a dict containing the package name, and the new and old
versions.
'''
ret = {}
valid_states = ('hold', 'noprune', 'user', 'ok', 'installed', 'unpacked')
if state not in valid_states:
raise SaltInvocationError('Invalid state: {0}'.format(state))
oldstate = _get_state(pkg)
cmd = ['opkg', 'flag']
cmd.append(state)
cmd.append(pkg)
_out = __salt__['cmd.run'](cmd, python_shell=False)
# Missing return value check due to opkg issue 160
ret[pkg] = {'old': oldstate,
'new': state}
return ret
def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
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
cmd = ['opkg', 'list-installed']
ret = {}
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
# This is a continuation of package description
if not line or line[0] == ' ':
continue
# This contains package name, version, and description.
# Extract the first two.
pkg_name, pkg_version = line.split(' - ', 2)[:2]
__salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version)
__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 list_upgrades(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
List all available package upgrades.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
ret = {}
if salt.utils.data.is_true(refresh):
refresh_db()
cmd = ['opkg', 'list-upgradable']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
if 'stdout' in call:
comment += call['stdout']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
name, _oldversion, newversion = line.split(' - ')
ret[name] = newversion
return ret
def _convert_to_standard_attr(attr):
'''
Helper function for _process_info_installed_output()
Converts an opkg attribute name to a standard attribute
name which is used across 'pkg' modules.
'''
ret_attr = ATTR_MAP.get(attr, None)
if ret_attr is None:
# All others convert to lowercase
return attr.lower()
return ret_attr
def _process_info_installed_output(out, filter_attrs):
'''
Helper function for info_installed()
Processes stdout output from a single invocation of
'opkg status'.
'''
ret = {}
name = None
attrs = {}
attr = None
for line in salt.utils.itertools.split(out, '\n'):
if line and line[0] == ' ':
# This is a continuation of the last attr
if filter_attrs is None or attr in filter_attrs:
line = line.strip()
if attrs[attr]:
# If attr is empty, don't add leading newline
attrs[attr] += '\n'
attrs[attr] += line
continue
line = line.strip()
if not line:
# Separator between different packages
if name:
ret[name] = attrs
name = None
attrs = {}
attr = None
continue
key, value = line.split(':', 1)
value = value.lstrip()
attr = _convert_to_standard_attr(key)
if attr == 'name':
name = value
elif filter_attrs is None or attr in filter_attrs:
attrs[attr] = value
if name:
ret[name] = attrs
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
.. versionadded:: 2017.7.0
:param names:
Names of the packages to get information about. If none are specified,
will return information for all installed packages.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
arch, conffiles, conflicts, depends, description, filename, group,
install_date_time_t, md5sum, packager, provides, recommends,
replaces, size, source, suggests, url, version
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed
salt '*' pkg.info_installed attr=version,packager
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> attr=version,packager
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,packager
'''
attr = kwargs.pop('attr', None)
if attr is None:
filter_attrs = None
elif isinstance(attr, six.string_types):
filter_attrs = set(attr.split(','))
else:
filter_attrs = set(attr)
ret = {}
if names:
# Specific list of names of installed packages
for name in names:
cmd = ['opkg', 'status', name]
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
else:
# All installed packages
cmd = ['opkg', 'status']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
return ret
def upgrade_available(name, **kwargs): # pylint: disable=unused-argument
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs): # pylint: disable=unused-argument
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2016.3.4
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0' '0.2.4.1-0'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] if ignore_epoch else six.text_type(x)
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
output = __salt__['cmd.run_stdout'](['opkg', '--version'],
output_loglevel='trace',
python_shell=False)
opkg_version = output.split(' ')[2].strip()
if salt.utils.versions.LooseVersion(opkg_version) >= \
salt.utils.versions.LooseVersion('0.3.4'):
cmd_compare = ['opkg', 'compare-versions']
elif salt.utils.path.which('opkg-compare-versions'):
cmd_compare = ['opkg-compare-versions']
else:
log.warning('Unable to find a compare-versions utility installed. Either upgrade opkg to '
'version > 0.3.4 (preferred) or install the older opkg-compare-versions script.')
return None
for oper, ret in (("<<", -1), ("=", 0), (">>", 1)):
cmd = cmd_compare[:]
cmd.append(_cmd_quote(pkg1))
cmd.append(oper)
cmd.append(_cmd_quote(pkg2))
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
ignore_retcode=True,
python_shell=False)
if retcode == 0:
return ret
return None
def _set_repo_option(repo, option):
'''
Set the option to repo
'''
if not option:
return
opt = option.split('=')
if len(opt) != 2:
return
if opt[0] == 'trusted':
repo['trusted'] = opt[1] == 'yes'
else:
repo[opt[0]] = opt[1]
def _set_repo_options(repo, options):
'''
Set the options to the repo.
'''
delimiters = "[", "]"
pattern = '|'.join(map(re.escape, delimiters))
for option in options:
splitted = re.split(pattern, option)
for opt in splitted:
_set_repo_option(repo, opt)
def _create_repo(line, filename):
'''
Create repo
'''
repo = {}
if line.startswith('#'):
repo['enabled'] = False
line = line[1:]
else:
repo['enabled'] = True
cols = salt.utils.args.shlex_split(line.strip())
repo['compressed'] = not cols[0] in 'src'
repo['name'] = cols[1]
repo['uri'] = cols[2]
repo['file'] = os.path.join(OPKG_CONFDIR, filename)
if len(cols) > 3:
_set_repo_options(repo, cols[3:])
return repo
def _read_repos(conf_file, repos, filename, regex):
'''
Read repos from configuration file
'''
for line in conf_file:
line = salt.utils.stringutils.to_unicode(line)
if not regex.search(line):
continue
repo = _create_repo(line, filename)
# do not store duplicated uri's
if repo['uri'] not in repos:
repos[repo['uri']] = [repo]
def list_repos(**kwargs): # pylint: disable=unused-argument
'''
Lists all repos on ``/etc/opkg/*.conf``
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos = {}
regex = re.compile(REPO_REGEXP)
for filename in os.listdir(OPKG_CONFDIR):
if not filename.endswith(".conf"):
continue
with salt.utils.files.fopen(os.path.join(OPKG_CONFDIR, filename)) as conf_file:
_read_repos(conf_file, repos, filename, regex)
return repos
def get_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Display a repo from the ``/etc/opkg/*.conf``
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo repo
'''
repos = list_repos()
if repos:
for source in six.itervalues(repos):
for sub in source:
if sub['name'] == repo:
return sub
return {}
def _del_repo_from_file(repo, filepath):
'''
Remove a repo from filepath
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
regex = re.compile(REPO_REGEXP)
for line in fhandle:
line = salt.utils.stringutils.to_unicode(line)
if regex.search(line):
if line.startswith('#'):
line = line[1:]
cols = salt.utils.args.shlex_split(line.strip())
if repo != cols[1]:
output.append(salt.utils.stringutils.to_str(line))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def _set_trusted_option_if_needed(repostr, trusted):
'''
Set trusted option to repo if needed
'''
if trusted is True:
repostr += ' [trusted=yes]'
elif trusted is False:
repostr += ' [trusted=no]'
return repostr
def _add_new_repo(repo, properties):
'''
Add a new repo entry
'''
repostr = '# ' if not properties.get('enabled') else ''
repostr += 'src/gz ' if properties.get('compressed') else 'src '
if ' ' in repo:
repostr += '"' + repo + '" '
else:
repostr += repo + ' '
repostr += properties.get('uri')
repostr = _set_trusted_option_if_needed(repostr, properties.get('trusted'))
repostr += '\n'
conffile = os.path.join(OPKG_CONFDIR, repo + '.conf')
with salt.utils.files.fopen(conffile, 'a') as fhandle:
fhandle.write(salt.utils.stringutils.to_str(repostr))
def _mod_repo_in_file(repo, repostr, filepath):
'''
Replace a repo entry in filepath with repostr
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
for line in fhandle:
cols = salt.utils.args.shlex_split(
salt.utils.stringutils.to_unicode(line).strip()
)
if repo not in cols:
output.append(line)
else:
output.append(salt.utils.stringutils.to_str(repostr + '\n'))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def del_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Delete a repo from ``/etc/opkg/*.conf``
If the file does not contain any other repo configuration, the file itself
will be deleted.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo repo
'''
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
repos = list_repos()
if repos:
deleted_from = dict()
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
deleted_from[source['file']] = 0
_del_repo_from_file(repo, source['file'])
if deleted_from:
ret = ''
for repository in repos:
source = repos[repository][0]
if source['file'] in deleted_from:
deleted_from[source['file']] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 1 and os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.\n')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
if refresh:
refresh_db()
return ret
return "Repo {0} doesn't exist in the opkg repo lists".format(repo)
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as uri is defined.
The following options are available to modify a repo definition:
repo
alias by which opkg refers to the repo.
uri
the URI to the repo.
compressed
defines (True or False) if the index file is compressed
enabled
enable or disable (True or False) repository
but do not remove if disabled.
refresh
enable or disable (True or False) auto-refresh of the repositories
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo repo uri=http://new/uri
salt '*' pkg.mod_repo repo enabled=False
'''
repos = list_repos()
found = False
uri = ''
if 'uri' in kwargs:
uri = kwargs['uri']
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
found = True
repostr = ''
if 'enabled' in kwargs and not kwargs['enabled']:
repostr += '# '
if 'compressed' in kwargs:
repostr += 'src/gz ' if kwargs['compressed'] else 'src'
else:
repostr += 'src/gz' if source['compressed'] else 'src'
repo_alias = kwargs['alias'] if 'alias' in kwargs else repo
if ' ' in repo_alias:
repostr += ' "{0}"'.format(repo_alias)
else:
repostr += ' {0}'.format(repo_alias)
repostr += ' {0}'.format(kwargs['uri'] if 'uri' in kwargs else source['uri'])
trusted = kwargs.get('trusted')
repostr = _set_trusted_option_if_needed(repostr, trusted) if trusted is not None else \
_set_trusted_option_if_needed(repostr, source.get('trusted'))
_mod_repo_in_file(repo, repostr, source['file'])
elif uri and source['uri'] == uri:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(uri, source['name']))
if not found:
# Need to add a new repo
if 'uri' not in kwargs:
raise CommandExecutionError(
'Repository \'{0}\' not found and no URI passed to create one.'.format(repo))
properties = {'uri': kwargs['uri']}
# If compressed is not defined, assume True
properties['compressed'] = kwargs['compressed'] if 'compressed' in kwargs else True
# If enabled is not defined, assume True
properties['enabled'] = kwargs['enabled'] if 'enabled' in kwargs else True
properties['trusted'] = kwargs.get('trusted')
_add_new_repo(repo, properties)
if 'refresh' in kwargs:
refresh_db()
def file_list(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
output = file_dict(*packages)
files = []
for package in list(output['packages'].values()):
files.extend(package)
return {'errors': output['errors'], 'files': files}
def file_dict(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
errors = []
ret = {}
cmd_files = ['opkg', 'files']
if not packages:
packages = list(list_pkgs().keys())
for package in packages:
files = []
cmd = cmd_files[:]
cmd.append(package)
out = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
for line in out['stdout'].splitlines():
if line.startswith('/'):
files.append(line)
elif line.startswith(' * '):
errors.append(line[3:])
break
else:
continue
if files:
ret[package] = files
return {'errors': errors, 'packages': ret}
def owner(*paths, **kwargs): # pylint: disable=unused-argument
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.opkg.version`, if a single
path is passed, a string will be returned, and if multiple paths are passed,
a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
cmd_search = ['opkg', 'search']
for path in paths:
cmd = cmd_search[:]
cmd.append(path)
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
if output:
ret[path] = output.split(' - ')[0].strip()
else:
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def version_clean(version):
'''
Clean the version string removing extra data.
There's nothing do to here for nipkg.py, therefore it will always
return the given version.
'''
return version
def check_extra_requirements(pkgname, pkgver):
'''
Check if the installed package already has the given requirements.
There's nothing do to here for nipkg.py, therefore it will always
return True.
'''
return True
|
saltstack/salt
|
salt/modules/opkg.py
|
_parse_reported_packages_from_remove_output
|
python
|
def _parse_reported_packages_from_remove_output(output):
'''
Parses the output of "opkg remove" to determine what packages would have been
removed by an operation run with the --noaction flag.
We are looking for lines like
Removing <package> (<version>) from <Target>...
'''
reported_pkgs = {}
remove_pattern = re.compile(r'Removing\s(?P<package>.*?)\s\((?P<version>.*?)\)\sfrom\s(?P<target>.*?)...')
for line in salt.utils.itertools.split(output, '\n'):
match = remove_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = ''
return reported_pkgs
|
Parses the output of "opkg remove" to determine what packages would have been
removed by an operation run with the --noaction flag.
We are looking for lines like
Removing <package> (<version>) from <Target>...
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/opkg.py#L590-L605
| null |
# -*- coding: utf-8 -*-
'''
Support for Opkg
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
.. versionadded: 2016.3.0
.. note::
For version comparison support on opkg < 0.3.4, the ``opkg-utils`` package
must be installed.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import os
import re
import logging
import errno
# Import salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.itertools
import salt.utils.path
import salt.utils.pkg
import salt.utils.stringutils
import salt.utils.versions
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import shlex_quote as _cmd_quote # pylint: disable=import-error
from salt.ext.six.moves import map # pylint: disable=import-error,redefined-builtin
REPO_REGEXP = r'^#?\s*(src|src/gz)\s+([^\s<>]+|"[^<>]+")\s+[^\s<>]+'
OPKG_CONFDIR = '/etc/opkg'
ATTR_MAP = {
'Architecture': 'arch',
'Homepage': 'url',
'Installed-Time': 'install_date_time_t',
'Maintainer': 'packager',
'Package': 'name',
'Section': 'group'
}
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
NILRT_RESTARTCHECK_STATE_PATH = '/var/lib/salt/restartcheck_state'
def _update_nilrt_restart_state():
'''
NILRT systems determine whether to reboot after various package operations
including but not limited to kernel module installs/removals by checking
specific file md5sums & timestamps. These files are touched/modified by
the post-install/post-remove functions of their respective packages.
The opkg module uses this function to store/update those file timestamps
and checksums to be used later by the restartcheck module.
'''
__salt__['cmd.shell']('stat -c %Y /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.timestamp'
.format(NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.md5sum'
.format(NILRT_RESTARTCHECK_STATE_PATH))
# We can't assume nisysapi.ini always exists like modules.dep
nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'
if os.path.exists(nisysapi_path):
__salt__['cmd.shell']('stat -c %Y {0} >{1}/nisysapi.ini.timestamp'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0} >{1}/nisysapi.ini.md5sum'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
# Expert plugin files get added to a conf.d dir, so keep track of the total
# no. of files, their timestamps and content hashes
nisysapi_conf_d_path = "/usr/lib/{0}/nisysapi/conf.d/experts/".format(
'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'
)
if os.path.exists(nisysapi_conf_d_path):
with salt.utils.files.fopen('{0}/sysapi.conf.d.count'.format(
NILRT_RESTARTCHECK_STATE_PATH), 'w') as fcount:
fcount.write(str(len(os.listdir(nisysapi_conf_d_path))))
for fexpert in os.listdir(nisysapi_conf_d_path):
__salt__['cmd.shell']('stat -c %Y {0}/{1} >{2}/{1}.timestamp'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0}/{1} >{2}/{1}.md5sum'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
def _get_restartcheck_result(errors):
'''
Return restartcheck result and append errors (if any) to ``errors``
'''
rs_result = __salt__['restartcheck.restartcheck'](verbose=False)
if isinstance(rs_result, dict) and 'comment' in rs_result:
errors.append(rs_result['comment'])
return rs_result
def _process_restartcheck_result(rs_result, **kwargs):
'''
Check restartcheck output to see if system/service restarts were requested
and take appropriate action.
'''
if 'No packages seem to need to be restarted' in rs_result:
return
reboot_required = False
for rstr in rs_result:
if 'System restart required' in rstr:
_update_nilrt_restart_state()
__salt__['system.set_reboot_required_witnessed']()
reboot_required = True
if kwargs.get('always_restart_services', True) or not reboot_required:
for rstr in rs_result:
if 'System restart required' not in rstr:
service = os.path.join('/etc/init.d', rstr)
if os.path.exists(service):
__salt__['cmd.run']([service, 'restart'])
def __virtual__():
'''
Confirm this module is on a nilrt based system
'''
if __grains__.get('os_family') == 'NILinuxRT':
try:
os.makedirs(NILRT_RESTARTCHECK_STATE_PATH)
except OSError as exc:
if exc.errno != errno.EEXIST:
return False, 'Error creating {0} (-{1}): {2}'.format(
NILRT_RESTARTCHECK_STATE_PATH,
exc.errno,
exc.strerror)
# populate state dir if empty
if not os.listdir(NILRT_RESTARTCHECK_STATE_PATH):
_update_nilrt_restart_state()
return __virtualname__
if os.path.isdir(OPKG_CONFDIR):
return __virtualname__
return False, "Module opkg only works on OpenEmbedded based systems"
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
if not names:
return ''
ret = {}
for name in names:
ret[name] = ''
# Refresh before looking for the latest version available
if refresh:
refresh_db()
cmd = ['opkg', 'list-upgradable']
out = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
try:
name, _oldversion, newversion = line.split(' - ')
if name in names:
ret[name] = newversion
except ValueError:
pass
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = latest_version
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(failhard=False, **kwargs): # pylint: disable=unused-argument
'''
Updates the opkg database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
failhard
If False, return results of failed lines as ``False`` for the package
database that encountered the error.
If True, raise an error with a list of the package databases that
encountered errors.
.. versionadded:: 2018.3.0
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
error_repos = []
cmd = ['opkg', 'update']
# opkg returns a non-zero retcode when there is a failure to refresh
# from one or more repos. Due to this, ignore the retcode.
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True,
redirect_stderr=True)
out = call['stdout']
prev_line = ''
for line in salt.utils.itertools.split(out, '\n'):
if 'Inflating' in line:
key = line.strip().split()[1][:-1]
ret[key] = True
elif 'Updated source' in line:
# Use the previous line.
key = prev_line.strip().split()[1][:-1]
ret[key] = True
elif 'Failed to download' in line:
key = line.strip().split()[5].split(',')[0]
ret[key] = False
error_repos.append(key)
prev_line = line
if failhard and error_repos:
raise CommandExecutionError(
'Error getting repos: {0}'.format(', '.join(error_repos))
)
# On a non-zero exit code where no failed repos were found, raise an
# exception because this appears to be a different kind of error.
if call['retcode'] != 0 and not error_repos:
raise CommandExecutionError(out)
return ret
def _is_testmode(**kwargs):
'''
Returns whether a test mode (noaction) operation was requested.
'''
return bool(kwargs.get('test') or __opts__.get('test'))
def _append_noaction_if_testmode(cmd, **kwargs):
'''
Adds the --noaction flag to the command if it's running in the test mode.
'''
if _is_testmode(**kwargs):
cmd.append('--noaction')
def _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall):
'''
Builds a list of install commands to be executed in sequence in order to process
each of the to_install, to_downgrade, and to_reinstall lists.
'''
cmds = []
if to_install:
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(to_install)
cmds.append(cmd)
if to_downgrade:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-downgrade')
cmd.extend(to_downgrade)
cmds.append(cmd)
if to_reinstall:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-reinstall')
cmd.extend(to_reinstall)
cmds.append(cmd)
return cmds
def _parse_reported_packages_from_install_output(output):
'''
Parses the output of "opkg install" to determine what packages would have been
installed by an operation run with the --noaction flag.
We are looking for lines like:
Installing <package> (<version>) on <target>
or
Upgrading <package> from <oldVersion> to <version> on root
'''
reported_pkgs = {}
install_pattern = re.compile(r'Installing\s(?P<package>.*?)\s\((?P<version>.*?)\)\son\s(?P<target>.*?)')
upgrade_pattern = re.compile(r'Upgrading\s(?P<package>.*?)\sfrom\s(?P<oldVersion>.*?)\sto\s(?P<version>.*?)\son\s(?P<target>.*?)')
for line in salt.utils.itertools.split(output, '\n'):
match = install_pattern.match(line)
if match is None:
match = upgrade_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = match.group('version')
return reported_pkgs
def _execute_install_command(cmd, parse_output, errors, parsed_packages):
'''
Executes a command for the install operation.
If the command fails, its error output will be appended to the errors list.
If the command succeeds and parse_output is true, updated packages will be appended
to the parsed_packages dictionary.
'''
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors.append(out['stderr'])
else:
errors.append(out['stdout'])
elif parse_output:
parsed_packages.update(_parse_reported_packages_from_install_output(out['stdout']))
def install(name=None,
refresh=False,
pkgs=None,
sources=None,
reinstall=False,
**kwargs):
'''
Install the passed package, add refresh=True to update the opkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionadded:: 2017.7.0
reinstall : False
Specifying reinstall=True will use ``opkg install --force-reinstall``
rather than simply ``opkg install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``opkg
install --force-reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2017.7.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of IPK packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
install_recommends
Whether to install the packages marked as recommended. Default is True.
only_upgrade
Only upgrade the packages (disallow downgrades), if they are already
installed. Default is False.
.. versionadded:: 2017.7.0
always_restart_services
Whether to restart services even if a reboot is required. Default is True.
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
refreshdb = salt.utils.data.is_true(refresh)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
cmd_prefix = ['opkg', 'install']
to_install = []
to_reinstall = []
to_downgrade = []
_append_noaction_if_testmode(cmd_prefix, **kwargs)
if not pkg_params:
return {}
elif pkg_type == 'file':
if reinstall:
cmd_prefix.append('--force-reinstall')
if not kwargs.get('only_upgrade', False):
cmd_prefix.append('--force-downgrade')
to_install.extend(pkg_params)
elif pkg_type == 'repository':
if not kwargs.get('install_recommends', True):
cmd_prefix.append('--no-install-recommends')
for pkgname, pkgversion in six.iteritems(pkg_params):
if (name and pkgs is None and kwargs.get('version') and
len(pkg_params) == 1):
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
version_num = pkgversion
if version_num is None:
# Don't allow downgrades if the version
# number is not specified.
if reinstall and pkgname in old:
to_reinstall.append(pkgname)
else:
to_install.append(pkgname)
else:
pkgstr = '{0}={1}'.format(pkgname, version_num)
cver = old.get(pkgname, '')
if reinstall and cver and salt.utils.versions.compare(
ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall.append(pkgstr)
elif not cver or salt.utils.versions.compare(
ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
to_install.append(pkgstr)
else:
if not kwargs.get('only_upgrade', False):
to_downgrade.append(pkgstr)
else:
# This should cause the command to fail.
to_install.append(pkgstr)
cmds = _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall)
if not cmds:
return {}
if refreshdb:
refresh_db()
errors = []
is_testmode = _is_testmode(**kwargs)
test_packages = {}
for cmd in cmds:
_execute_install_command(cmd, is_testmode, errors, test_packages)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if is_testmode:
new = copy.deepcopy(new)
new.update(test_packages)
ret = salt.utils.data.compare_dicts(old, new)
if pkg_type == 'file' and reinstall:
# For file-based packages, prepare 'to_reinstall' to have a list
# of all the package names that may have been reinstalled.
# This way, we could include reinstalled packages in 'ret'.
for pkgfile in to_install:
# Convert from file name to package name.
cmd = ['opkg', 'info', pkgfile]
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] == 0:
# Just need the package name.
pkginfo_dict = _process_info_installed_output(
out['stdout'], []
)
if pkginfo_dict:
to_reinstall.append(list(pkginfo_dict.keys())[0])
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def remove(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Remove packages using ``opkg remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
remove_dependencies
Remove package and all dependencies
.. versionadded:: 2019.2.0
auto_remove_deps
Remove packages that were installed automatically to satisfy dependencies
.. versionadded:: 2019.2.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
salt '*' pkg.remove pkgs='["foo", "bar"]' remove_dependencies=True auto_remove_deps=True
'''
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 {}
cmd = ['opkg', 'remove']
_append_noaction_if_testmode(cmd, **kwargs)
if kwargs.get('remove_dependencies', False):
cmd.append('--force-removal-of-dependent-packages')
if kwargs.get('auto_remove_deps', False):
cmd.append('--autoremove')
cmd.extend(targets)
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors = [out['stderr']]
else:
errors = [out['stdout']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if _is_testmode(**kwargs):
reportedPkgs = _parse_reported_packages_from_remove_output(out['stdout'])
new = {k: v for k, v in new.items() if k not in reportedPkgs}
ret = salt.utils.data.compare_dicts(old, new)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def purge(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Package purges are not supported by opkg, this function is identical to
:mod:`pkg.remove <salt.modules.opkg.remove>`.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name, pkgs=pkgs)
def upgrade(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
Upgrades all packages via ``opkg upgrade``
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
errors = []
if salt.utils.data.is_true(refresh):
refresh_db()
old = list_pkgs()
cmd = ['opkg', 'upgrade']
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
errors.append(result)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif state != 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = _set_state(target, 'hold')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif state == 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret['comment'] = ('Package {0} is set not to be held.'
.format(target))
else:
result = _set_state(target, 'ok')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def _get_state(pkg):
'''
View package state from the opkg database
Return the state of pkg
'''
cmd = ['opkg', 'status']
cmd.append(pkg)
out = __salt__['cmd.run'](cmd, python_shell=False)
state_flag = ''
for line in salt.utils.itertools.split(out, '\n'):
if line.startswith('Status'):
_status, _state_want, state_flag, _state_status = line.split()
return state_flag
def _set_state(pkg, state):
'''
Change package state on the opkg database
The state can be any of:
- hold
- noprune
- user
- ok
- installed
- unpacked
This command is commonly used to mark a specific package to be held from
being upgraded, that is, to be kept at a certain version.
Returns a dict containing the package name, and the new and old
versions.
'''
ret = {}
valid_states = ('hold', 'noprune', 'user', 'ok', 'installed', 'unpacked')
if state not in valid_states:
raise SaltInvocationError('Invalid state: {0}'.format(state))
oldstate = _get_state(pkg)
cmd = ['opkg', 'flag']
cmd.append(state)
cmd.append(pkg)
_out = __salt__['cmd.run'](cmd, python_shell=False)
# Missing return value check due to opkg issue 160
ret[pkg] = {'old': oldstate,
'new': state}
return ret
def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
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
cmd = ['opkg', 'list-installed']
ret = {}
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
# This is a continuation of package description
if not line or line[0] == ' ':
continue
# This contains package name, version, and description.
# Extract the first two.
pkg_name, pkg_version = line.split(' - ', 2)[:2]
__salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version)
__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 list_upgrades(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
List all available package upgrades.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
ret = {}
if salt.utils.data.is_true(refresh):
refresh_db()
cmd = ['opkg', 'list-upgradable']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
if 'stdout' in call:
comment += call['stdout']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
name, _oldversion, newversion = line.split(' - ')
ret[name] = newversion
return ret
def _convert_to_standard_attr(attr):
'''
Helper function for _process_info_installed_output()
Converts an opkg attribute name to a standard attribute
name which is used across 'pkg' modules.
'''
ret_attr = ATTR_MAP.get(attr, None)
if ret_attr is None:
# All others convert to lowercase
return attr.lower()
return ret_attr
def _process_info_installed_output(out, filter_attrs):
'''
Helper function for info_installed()
Processes stdout output from a single invocation of
'opkg status'.
'''
ret = {}
name = None
attrs = {}
attr = None
for line in salt.utils.itertools.split(out, '\n'):
if line and line[0] == ' ':
# This is a continuation of the last attr
if filter_attrs is None or attr in filter_attrs:
line = line.strip()
if attrs[attr]:
# If attr is empty, don't add leading newline
attrs[attr] += '\n'
attrs[attr] += line
continue
line = line.strip()
if not line:
# Separator between different packages
if name:
ret[name] = attrs
name = None
attrs = {}
attr = None
continue
key, value = line.split(':', 1)
value = value.lstrip()
attr = _convert_to_standard_attr(key)
if attr == 'name':
name = value
elif filter_attrs is None or attr in filter_attrs:
attrs[attr] = value
if name:
ret[name] = attrs
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
.. versionadded:: 2017.7.0
:param names:
Names of the packages to get information about. If none are specified,
will return information for all installed packages.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
arch, conffiles, conflicts, depends, description, filename, group,
install_date_time_t, md5sum, packager, provides, recommends,
replaces, size, source, suggests, url, version
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed
salt '*' pkg.info_installed attr=version,packager
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> attr=version,packager
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,packager
'''
attr = kwargs.pop('attr', None)
if attr is None:
filter_attrs = None
elif isinstance(attr, six.string_types):
filter_attrs = set(attr.split(','))
else:
filter_attrs = set(attr)
ret = {}
if names:
# Specific list of names of installed packages
for name in names:
cmd = ['opkg', 'status', name]
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
else:
# All installed packages
cmd = ['opkg', 'status']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
return ret
def upgrade_available(name, **kwargs): # pylint: disable=unused-argument
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs): # pylint: disable=unused-argument
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2016.3.4
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0' '0.2.4.1-0'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] if ignore_epoch else six.text_type(x)
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
output = __salt__['cmd.run_stdout'](['opkg', '--version'],
output_loglevel='trace',
python_shell=False)
opkg_version = output.split(' ')[2].strip()
if salt.utils.versions.LooseVersion(opkg_version) >= \
salt.utils.versions.LooseVersion('0.3.4'):
cmd_compare = ['opkg', 'compare-versions']
elif salt.utils.path.which('opkg-compare-versions'):
cmd_compare = ['opkg-compare-versions']
else:
log.warning('Unable to find a compare-versions utility installed. Either upgrade opkg to '
'version > 0.3.4 (preferred) or install the older opkg-compare-versions script.')
return None
for oper, ret in (("<<", -1), ("=", 0), (">>", 1)):
cmd = cmd_compare[:]
cmd.append(_cmd_quote(pkg1))
cmd.append(oper)
cmd.append(_cmd_quote(pkg2))
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
ignore_retcode=True,
python_shell=False)
if retcode == 0:
return ret
return None
def _set_repo_option(repo, option):
'''
Set the option to repo
'''
if not option:
return
opt = option.split('=')
if len(opt) != 2:
return
if opt[0] == 'trusted':
repo['trusted'] = opt[1] == 'yes'
else:
repo[opt[0]] = opt[1]
def _set_repo_options(repo, options):
'''
Set the options to the repo.
'''
delimiters = "[", "]"
pattern = '|'.join(map(re.escape, delimiters))
for option in options:
splitted = re.split(pattern, option)
for opt in splitted:
_set_repo_option(repo, opt)
def _create_repo(line, filename):
'''
Create repo
'''
repo = {}
if line.startswith('#'):
repo['enabled'] = False
line = line[1:]
else:
repo['enabled'] = True
cols = salt.utils.args.shlex_split(line.strip())
repo['compressed'] = not cols[0] in 'src'
repo['name'] = cols[1]
repo['uri'] = cols[2]
repo['file'] = os.path.join(OPKG_CONFDIR, filename)
if len(cols) > 3:
_set_repo_options(repo, cols[3:])
return repo
def _read_repos(conf_file, repos, filename, regex):
'''
Read repos from configuration file
'''
for line in conf_file:
line = salt.utils.stringutils.to_unicode(line)
if not regex.search(line):
continue
repo = _create_repo(line, filename)
# do not store duplicated uri's
if repo['uri'] not in repos:
repos[repo['uri']] = [repo]
def list_repos(**kwargs): # pylint: disable=unused-argument
'''
Lists all repos on ``/etc/opkg/*.conf``
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos = {}
regex = re.compile(REPO_REGEXP)
for filename in os.listdir(OPKG_CONFDIR):
if not filename.endswith(".conf"):
continue
with salt.utils.files.fopen(os.path.join(OPKG_CONFDIR, filename)) as conf_file:
_read_repos(conf_file, repos, filename, regex)
return repos
def get_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Display a repo from the ``/etc/opkg/*.conf``
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo repo
'''
repos = list_repos()
if repos:
for source in six.itervalues(repos):
for sub in source:
if sub['name'] == repo:
return sub
return {}
def _del_repo_from_file(repo, filepath):
'''
Remove a repo from filepath
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
regex = re.compile(REPO_REGEXP)
for line in fhandle:
line = salt.utils.stringutils.to_unicode(line)
if regex.search(line):
if line.startswith('#'):
line = line[1:]
cols = salt.utils.args.shlex_split(line.strip())
if repo != cols[1]:
output.append(salt.utils.stringutils.to_str(line))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def _set_trusted_option_if_needed(repostr, trusted):
'''
Set trusted option to repo if needed
'''
if trusted is True:
repostr += ' [trusted=yes]'
elif trusted is False:
repostr += ' [trusted=no]'
return repostr
def _add_new_repo(repo, properties):
'''
Add a new repo entry
'''
repostr = '# ' if not properties.get('enabled') else ''
repostr += 'src/gz ' if properties.get('compressed') else 'src '
if ' ' in repo:
repostr += '"' + repo + '" '
else:
repostr += repo + ' '
repostr += properties.get('uri')
repostr = _set_trusted_option_if_needed(repostr, properties.get('trusted'))
repostr += '\n'
conffile = os.path.join(OPKG_CONFDIR, repo + '.conf')
with salt.utils.files.fopen(conffile, 'a') as fhandle:
fhandle.write(salt.utils.stringutils.to_str(repostr))
def _mod_repo_in_file(repo, repostr, filepath):
'''
Replace a repo entry in filepath with repostr
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
for line in fhandle:
cols = salt.utils.args.shlex_split(
salt.utils.stringutils.to_unicode(line).strip()
)
if repo not in cols:
output.append(line)
else:
output.append(salt.utils.stringutils.to_str(repostr + '\n'))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def del_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Delete a repo from ``/etc/opkg/*.conf``
If the file does not contain any other repo configuration, the file itself
will be deleted.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo repo
'''
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
repos = list_repos()
if repos:
deleted_from = dict()
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
deleted_from[source['file']] = 0
_del_repo_from_file(repo, source['file'])
if deleted_from:
ret = ''
for repository in repos:
source = repos[repository][0]
if source['file'] in deleted_from:
deleted_from[source['file']] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 1 and os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.\n')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
if refresh:
refresh_db()
return ret
return "Repo {0} doesn't exist in the opkg repo lists".format(repo)
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as uri is defined.
The following options are available to modify a repo definition:
repo
alias by which opkg refers to the repo.
uri
the URI to the repo.
compressed
defines (True or False) if the index file is compressed
enabled
enable or disable (True or False) repository
but do not remove if disabled.
refresh
enable or disable (True or False) auto-refresh of the repositories
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo repo uri=http://new/uri
salt '*' pkg.mod_repo repo enabled=False
'''
repos = list_repos()
found = False
uri = ''
if 'uri' in kwargs:
uri = kwargs['uri']
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
found = True
repostr = ''
if 'enabled' in kwargs and not kwargs['enabled']:
repostr += '# '
if 'compressed' in kwargs:
repostr += 'src/gz ' if kwargs['compressed'] else 'src'
else:
repostr += 'src/gz' if source['compressed'] else 'src'
repo_alias = kwargs['alias'] if 'alias' in kwargs else repo
if ' ' in repo_alias:
repostr += ' "{0}"'.format(repo_alias)
else:
repostr += ' {0}'.format(repo_alias)
repostr += ' {0}'.format(kwargs['uri'] if 'uri' in kwargs else source['uri'])
trusted = kwargs.get('trusted')
repostr = _set_trusted_option_if_needed(repostr, trusted) if trusted is not None else \
_set_trusted_option_if_needed(repostr, source.get('trusted'))
_mod_repo_in_file(repo, repostr, source['file'])
elif uri and source['uri'] == uri:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(uri, source['name']))
if not found:
# Need to add a new repo
if 'uri' not in kwargs:
raise CommandExecutionError(
'Repository \'{0}\' not found and no URI passed to create one.'.format(repo))
properties = {'uri': kwargs['uri']}
# If compressed is not defined, assume True
properties['compressed'] = kwargs['compressed'] if 'compressed' in kwargs else True
# If enabled is not defined, assume True
properties['enabled'] = kwargs['enabled'] if 'enabled' in kwargs else True
properties['trusted'] = kwargs.get('trusted')
_add_new_repo(repo, properties)
if 'refresh' in kwargs:
refresh_db()
def file_list(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
output = file_dict(*packages)
files = []
for package in list(output['packages'].values()):
files.extend(package)
return {'errors': output['errors'], 'files': files}
def file_dict(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
errors = []
ret = {}
cmd_files = ['opkg', 'files']
if not packages:
packages = list(list_pkgs().keys())
for package in packages:
files = []
cmd = cmd_files[:]
cmd.append(package)
out = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
for line in out['stdout'].splitlines():
if line.startswith('/'):
files.append(line)
elif line.startswith(' * '):
errors.append(line[3:])
break
else:
continue
if files:
ret[package] = files
return {'errors': errors, 'packages': ret}
def owner(*paths, **kwargs): # pylint: disable=unused-argument
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.opkg.version`, if a single
path is passed, a string will be returned, and if multiple paths are passed,
a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
cmd_search = ['opkg', 'search']
for path in paths:
cmd = cmd_search[:]
cmd.append(path)
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
if output:
ret[path] = output.split(' - ')[0].strip()
else:
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def version_clean(version):
'''
Clean the version string removing extra data.
There's nothing do to here for nipkg.py, therefore it will always
return the given version.
'''
return version
def check_extra_requirements(pkgname, pkgver):
'''
Check if the installed package already has the given requirements.
There's nothing do to here for nipkg.py, therefore it will always
return True.
'''
return True
|
saltstack/salt
|
salt/modules/opkg.py
|
remove
|
python
|
def remove(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Remove packages using ``opkg remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
remove_dependencies
Remove package and all dependencies
.. versionadded:: 2019.2.0
auto_remove_deps
Remove packages that were installed automatically to satisfy dependencies
.. versionadded:: 2019.2.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
salt '*' pkg.remove pkgs='["foo", "bar"]' remove_dependencies=True auto_remove_deps=True
'''
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 {}
cmd = ['opkg', 'remove']
_append_noaction_if_testmode(cmd, **kwargs)
if kwargs.get('remove_dependencies', False):
cmd.append('--force-removal-of-dependent-packages')
if kwargs.get('auto_remove_deps', False):
cmd.append('--autoremove')
cmd.extend(targets)
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors = [out['stderr']]
else:
errors = [out['stdout']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if _is_testmode(**kwargs):
reportedPkgs = _parse_reported_packages_from_remove_output(out['stdout'])
new = {k: v for k, v in new.items() if k not in reportedPkgs}
ret = salt.utils.data.compare_dicts(old, new)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
|
Remove packages using ``opkg remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
remove_dependencies
Remove package and all dependencies
.. versionadded:: 2019.2.0
auto_remove_deps
Remove packages that were installed automatically to satisfy dependencies
.. versionadded:: 2019.2.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
salt '*' pkg.remove pkgs='["foo", "bar"]' remove_dependencies=True auto_remove_deps=True
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/opkg.py#L608-L690
|
[
"def list_pkgs(versions_as_list=False, **kwargs):\n '''\n List the packages currently installed in a dict::\n\n {'<package_name>': '<version>'}\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.list_pkgs\n salt '*' pkg.list_pkgs versions_as_list=True\n '''\n versions_as_list = salt.utils.data.is_true(versions_as_list)\n # not yet implemented or not applicable\n if any([salt.utils.data.is_true(kwargs.get(x))\n for x in ('removed', 'purge_desired')]):\n return {}\n\n if 'pkg.list_pkgs' in __context__:\n if versions_as_list:\n return __context__['pkg.list_pkgs']\n else:\n ret = copy.deepcopy(__context__['pkg.list_pkgs'])\n __salt__['pkg_resource.stringify'](ret)\n return ret\n\n cmd = ['opkg', 'list-installed']\n ret = {}\n out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)\n for line in salt.utils.itertools.split(out, '\\n'):\n # This is a continuation of package description\n if not line or line[0] == ' ':\n continue\n\n # This contains package name, version, and description.\n # Extract the first two.\n pkg_name, pkg_version = line.split(' - ', 2)[:2]\n __salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version)\n\n __salt__['pkg_resource.sort_pkglist'](ret)\n __context__['pkg.list_pkgs'] = copy.deepcopy(ret)\n if not versions_as_list:\n __salt__['pkg_resource.stringify'](ret)\n return ret\n",
"def _get_restartcheck_result(errors):\n '''\n Return restartcheck result and append errors (if any) to ``errors``\n '''\n rs_result = __salt__['restartcheck.restartcheck'](verbose=False)\n if isinstance(rs_result, dict) and 'comment' in rs_result:\n errors.append(rs_result['comment'])\n return rs_result\n",
"def _process_restartcheck_result(rs_result, **kwargs):\n '''\n Check restartcheck output to see if system/service restarts were requested\n and take appropriate action.\n '''\n if 'No packages seem to need to be restarted' in rs_result:\n return\n reboot_required = False\n for rstr in rs_result:\n if 'System restart required' in rstr:\n _update_nilrt_restart_state()\n __salt__['system.set_reboot_required_witnessed']()\n reboot_required = True\n if kwargs.get('always_restart_services', True) or not reboot_required:\n for rstr in rs_result:\n if 'System restart required' not in rstr:\n service = os.path.join('/etc/init.d', rstr)\n if os.path.exists(service):\n __salt__['cmd.run']([service, 'restart'])\n",
"def _is_testmode(**kwargs):\n '''\n Returns whether a test mode (noaction) operation was requested.\n '''\n return bool(kwargs.get('test') or __opts__.get('test'))\n",
"def _append_noaction_if_testmode(cmd, **kwargs):\n '''\n Adds the --noaction flag to the command if it's running in the test mode.\n '''\n if _is_testmode(**kwargs):\n cmd.append('--noaction')\n",
"def _parse_reported_packages_from_remove_output(output):\n '''\n Parses the output of \"opkg remove\" to determine what packages would have been\n removed by an operation run with the --noaction flag.\n\n We are looking for lines like\n Removing <package> (<version>) from <Target>...\n '''\n reported_pkgs = {}\n remove_pattern = re.compile(r'Removing\\s(?P<package>.*?)\\s\\((?P<version>.*?)\\)\\sfrom\\s(?P<target>.*?)...')\n for line in salt.utils.itertools.split(output, '\\n'):\n match = remove_pattern.match(line)\n if match:\n reported_pkgs[match.group('package')] = ''\n\n return reported_pkgs\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Opkg
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
.. versionadded: 2016.3.0
.. note::
For version comparison support on opkg < 0.3.4, the ``opkg-utils`` package
must be installed.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import os
import re
import logging
import errno
# Import salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.itertools
import salt.utils.path
import salt.utils.pkg
import salt.utils.stringutils
import salt.utils.versions
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import shlex_quote as _cmd_quote # pylint: disable=import-error
from salt.ext.six.moves import map # pylint: disable=import-error,redefined-builtin
REPO_REGEXP = r'^#?\s*(src|src/gz)\s+([^\s<>]+|"[^<>]+")\s+[^\s<>]+'
OPKG_CONFDIR = '/etc/opkg'
ATTR_MAP = {
'Architecture': 'arch',
'Homepage': 'url',
'Installed-Time': 'install_date_time_t',
'Maintainer': 'packager',
'Package': 'name',
'Section': 'group'
}
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
NILRT_RESTARTCHECK_STATE_PATH = '/var/lib/salt/restartcheck_state'
def _update_nilrt_restart_state():
'''
NILRT systems determine whether to reboot after various package operations
including but not limited to kernel module installs/removals by checking
specific file md5sums & timestamps. These files are touched/modified by
the post-install/post-remove functions of their respective packages.
The opkg module uses this function to store/update those file timestamps
and checksums to be used later by the restartcheck module.
'''
__salt__['cmd.shell']('stat -c %Y /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.timestamp'
.format(NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.md5sum'
.format(NILRT_RESTARTCHECK_STATE_PATH))
# We can't assume nisysapi.ini always exists like modules.dep
nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'
if os.path.exists(nisysapi_path):
__salt__['cmd.shell']('stat -c %Y {0} >{1}/nisysapi.ini.timestamp'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0} >{1}/nisysapi.ini.md5sum'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
# Expert plugin files get added to a conf.d dir, so keep track of the total
# no. of files, their timestamps and content hashes
nisysapi_conf_d_path = "/usr/lib/{0}/nisysapi/conf.d/experts/".format(
'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'
)
if os.path.exists(nisysapi_conf_d_path):
with salt.utils.files.fopen('{0}/sysapi.conf.d.count'.format(
NILRT_RESTARTCHECK_STATE_PATH), 'w') as fcount:
fcount.write(str(len(os.listdir(nisysapi_conf_d_path))))
for fexpert in os.listdir(nisysapi_conf_d_path):
__salt__['cmd.shell']('stat -c %Y {0}/{1} >{2}/{1}.timestamp'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0}/{1} >{2}/{1}.md5sum'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
def _get_restartcheck_result(errors):
'''
Return restartcheck result and append errors (if any) to ``errors``
'''
rs_result = __salt__['restartcheck.restartcheck'](verbose=False)
if isinstance(rs_result, dict) and 'comment' in rs_result:
errors.append(rs_result['comment'])
return rs_result
def _process_restartcheck_result(rs_result, **kwargs):
'''
Check restartcheck output to see if system/service restarts were requested
and take appropriate action.
'''
if 'No packages seem to need to be restarted' in rs_result:
return
reboot_required = False
for rstr in rs_result:
if 'System restart required' in rstr:
_update_nilrt_restart_state()
__salt__['system.set_reboot_required_witnessed']()
reboot_required = True
if kwargs.get('always_restart_services', True) or not reboot_required:
for rstr in rs_result:
if 'System restart required' not in rstr:
service = os.path.join('/etc/init.d', rstr)
if os.path.exists(service):
__salt__['cmd.run']([service, 'restart'])
def __virtual__():
'''
Confirm this module is on a nilrt based system
'''
if __grains__.get('os_family') == 'NILinuxRT':
try:
os.makedirs(NILRT_RESTARTCHECK_STATE_PATH)
except OSError as exc:
if exc.errno != errno.EEXIST:
return False, 'Error creating {0} (-{1}): {2}'.format(
NILRT_RESTARTCHECK_STATE_PATH,
exc.errno,
exc.strerror)
# populate state dir if empty
if not os.listdir(NILRT_RESTARTCHECK_STATE_PATH):
_update_nilrt_restart_state()
return __virtualname__
if os.path.isdir(OPKG_CONFDIR):
return __virtualname__
return False, "Module opkg only works on OpenEmbedded based systems"
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
if not names:
return ''
ret = {}
for name in names:
ret[name] = ''
# Refresh before looking for the latest version available
if refresh:
refresh_db()
cmd = ['opkg', 'list-upgradable']
out = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
try:
name, _oldversion, newversion = line.split(' - ')
if name in names:
ret[name] = newversion
except ValueError:
pass
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = latest_version
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(failhard=False, **kwargs): # pylint: disable=unused-argument
'''
Updates the opkg database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
failhard
If False, return results of failed lines as ``False`` for the package
database that encountered the error.
If True, raise an error with a list of the package databases that
encountered errors.
.. versionadded:: 2018.3.0
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
error_repos = []
cmd = ['opkg', 'update']
# opkg returns a non-zero retcode when there is a failure to refresh
# from one or more repos. Due to this, ignore the retcode.
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True,
redirect_stderr=True)
out = call['stdout']
prev_line = ''
for line in salt.utils.itertools.split(out, '\n'):
if 'Inflating' in line:
key = line.strip().split()[1][:-1]
ret[key] = True
elif 'Updated source' in line:
# Use the previous line.
key = prev_line.strip().split()[1][:-1]
ret[key] = True
elif 'Failed to download' in line:
key = line.strip().split()[5].split(',')[0]
ret[key] = False
error_repos.append(key)
prev_line = line
if failhard and error_repos:
raise CommandExecutionError(
'Error getting repos: {0}'.format(', '.join(error_repos))
)
# On a non-zero exit code where no failed repos were found, raise an
# exception because this appears to be a different kind of error.
if call['retcode'] != 0 and not error_repos:
raise CommandExecutionError(out)
return ret
def _is_testmode(**kwargs):
'''
Returns whether a test mode (noaction) operation was requested.
'''
return bool(kwargs.get('test') or __opts__.get('test'))
def _append_noaction_if_testmode(cmd, **kwargs):
'''
Adds the --noaction flag to the command if it's running in the test mode.
'''
if _is_testmode(**kwargs):
cmd.append('--noaction')
def _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall):
'''
Builds a list of install commands to be executed in sequence in order to process
each of the to_install, to_downgrade, and to_reinstall lists.
'''
cmds = []
if to_install:
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(to_install)
cmds.append(cmd)
if to_downgrade:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-downgrade')
cmd.extend(to_downgrade)
cmds.append(cmd)
if to_reinstall:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-reinstall')
cmd.extend(to_reinstall)
cmds.append(cmd)
return cmds
def _parse_reported_packages_from_install_output(output):
'''
Parses the output of "opkg install" to determine what packages would have been
installed by an operation run with the --noaction flag.
We are looking for lines like:
Installing <package> (<version>) on <target>
or
Upgrading <package> from <oldVersion> to <version> on root
'''
reported_pkgs = {}
install_pattern = re.compile(r'Installing\s(?P<package>.*?)\s\((?P<version>.*?)\)\son\s(?P<target>.*?)')
upgrade_pattern = re.compile(r'Upgrading\s(?P<package>.*?)\sfrom\s(?P<oldVersion>.*?)\sto\s(?P<version>.*?)\son\s(?P<target>.*?)')
for line in salt.utils.itertools.split(output, '\n'):
match = install_pattern.match(line)
if match is None:
match = upgrade_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = match.group('version')
return reported_pkgs
def _execute_install_command(cmd, parse_output, errors, parsed_packages):
'''
Executes a command for the install operation.
If the command fails, its error output will be appended to the errors list.
If the command succeeds and parse_output is true, updated packages will be appended
to the parsed_packages dictionary.
'''
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors.append(out['stderr'])
else:
errors.append(out['stdout'])
elif parse_output:
parsed_packages.update(_parse_reported_packages_from_install_output(out['stdout']))
def install(name=None,
refresh=False,
pkgs=None,
sources=None,
reinstall=False,
**kwargs):
'''
Install the passed package, add refresh=True to update the opkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionadded:: 2017.7.0
reinstall : False
Specifying reinstall=True will use ``opkg install --force-reinstall``
rather than simply ``opkg install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``opkg
install --force-reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2017.7.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of IPK packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
install_recommends
Whether to install the packages marked as recommended. Default is True.
only_upgrade
Only upgrade the packages (disallow downgrades), if they are already
installed. Default is False.
.. versionadded:: 2017.7.0
always_restart_services
Whether to restart services even if a reboot is required. Default is True.
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
refreshdb = salt.utils.data.is_true(refresh)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
cmd_prefix = ['opkg', 'install']
to_install = []
to_reinstall = []
to_downgrade = []
_append_noaction_if_testmode(cmd_prefix, **kwargs)
if not pkg_params:
return {}
elif pkg_type == 'file':
if reinstall:
cmd_prefix.append('--force-reinstall')
if not kwargs.get('only_upgrade', False):
cmd_prefix.append('--force-downgrade')
to_install.extend(pkg_params)
elif pkg_type == 'repository':
if not kwargs.get('install_recommends', True):
cmd_prefix.append('--no-install-recommends')
for pkgname, pkgversion in six.iteritems(pkg_params):
if (name and pkgs is None and kwargs.get('version') and
len(pkg_params) == 1):
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
version_num = pkgversion
if version_num is None:
# Don't allow downgrades if the version
# number is not specified.
if reinstall and pkgname in old:
to_reinstall.append(pkgname)
else:
to_install.append(pkgname)
else:
pkgstr = '{0}={1}'.format(pkgname, version_num)
cver = old.get(pkgname, '')
if reinstall and cver and salt.utils.versions.compare(
ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall.append(pkgstr)
elif not cver or salt.utils.versions.compare(
ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
to_install.append(pkgstr)
else:
if not kwargs.get('only_upgrade', False):
to_downgrade.append(pkgstr)
else:
# This should cause the command to fail.
to_install.append(pkgstr)
cmds = _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall)
if not cmds:
return {}
if refreshdb:
refresh_db()
errors = []
is_testmode = _is_testmode(**kwargs)
test_packages = {}
for cmd in cmds:
_execute_install_command(cmd, is_testmode, errors, test_packages)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if is_testmode:
new = copy.deepcopy(new)
new.update(test_packages)
ret = salt.utils.data.compare_dicts(old, new)
if pkg_type == 'file' and reinstall:
# For file-based packages, prepare 'to_reinstall' to have a list
# of all the package names that may have been reinstalled.
# This way, we could include reinstalled packages in 'ret'.
for pkgfile in to_install:
# Convert from file name to package name.
cmd = ['opkg', 'info', pkgfile]
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] == 0:
# Just need the package name.
pkginfo_dict = _process_info_installed_output(
out['stdout'], []
)
if pkginfo_dict:
to_reinstall.append(list(pkginfo_dict.keys())[0])
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def _parse_reported_packages_from_remove_output(output):
'''
Parses the output of "opkg remove" to determine what packages would have been
removed by an operation run with the --noaction flag.
We are looking for lines like
Removing <package> (<version>) from <Target>...
'''
reported_pkgs = {}
remove_pattern = re.compile(r'Removing\s(?P<package>.*?)\s\((?P<version>.*?)\)\sfrom\s(?P<target>.*?)...')
for line in salt.utils.itertools.split(output, '\n'):
match = remove_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = ''
return reported_pkgs
def purge(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Package purges are not supported by opkg, this function is identical to
:mod:`pkg.remove <salt.modules.opkg.remove>`.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name, pkgs=pkgs)
def upgrade(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
Upgrades all packages via ``opkg upgrade``
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
errors = []
if salt.utils.data.is_true(refresh):
refresh_db()
old = list_pkgs()
cmd = ['opkg', 'upgrade']
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
errors.append(result)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif state != 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = _set_state(target, 'hold')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif state == 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret['comment'] = ('Package {0} is set not to be held.'
.format(target))
else:
result = _set_state(target, 'ok')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def _get_state(pkg):
'''
View package state from the opkg database
Return the state of pkg
'''
cmd = ['opkg', 'status']
cmd.append(pkg)
out = __salt__['cmd.run'](cmd, python_shell=False)
state_flag = ''
for line in salt.utils.itertools.split(out, '\n'):
if line.startswith('Status'):
_status, _state_want, state_flag, _state_status = line.split()
return state_flag
def _set_state(pkg, state):
'''
Change package state on the opkg database
The state can be any of:
- hold
- noprune
- user
- ok
- installed
- unpacked
This command is commonly used to mark a specific package to be held from
being upgraded, that is, to be kept at a certain version.
Returns a dict containing the package name, and the new and old
versions.
'''
ret = {}
valid_states = ('hold', 'noprune', 'user', 'ok', 'installed', 'unpacked')
if state not in valid_states:
raise SaltInvocationError('Invalid state: {0}'.format(state))
oldstate = _get_state(pkg)
cmd = ['opkg', 'flag']
cmd.append(state)
cmd.append(pkg)
_out = __salt__['cmd.run'](cmd, python_shell=False)
# Missing return value check due to opkg issue 160
ret[pkg] = {'old': oldstate,
'new': state}
return ret
def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
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
cmd = ['opkg', 'list-installed']
ret = {}
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
# This is a continuation of package description
if not line or line[0] == ' ':
continue
# This contains package name, version, and description.
# Extract the first two.
pkg_name, pkg_version = line.split(' - ', 2)[:2]
__salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version)
__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 list_upgrades(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
List all available package upgrades.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
ret = {}
if salt.utils.data.is_true(refresh):
refresh_db()
cmd = ['opkg', 'list-upgradable']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
if 'stdout' in call:
comment += call['stdout']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
name, _oldversion, newversion = line.split(' - ')
ret[name] = newversion
return ret
def _convert_to_standard_attr(attr):
'''
Helper function for _process_info_installed_output()
Converts an opkg attribute name to a standard attribute
name which is used across 'pkg' modules.
'''
ret_attr = ATTR_MAP.get(attr, None)
if ret_attr is None:
# All others convert to lowercase
return attr.lower()
return ret_attr
def _process_info_installed_output(out, filter_attrs):
'''
Helper function for info_installed()
Processes stdout output from a single invocation of
'opkg status'.
'''
ret = {}
name = None
attrs = {}
attr = None
for line in salt.utils.itertools.split(out, '\n'):
if line and line[0] == ' ':
# This is a continuation of the last attr
if filter_attrs is None or attr in filter_attrs:
line = line.strip()
if attrs[attr]:
# If attr is empty, don't add leading newline
attrs[attr] += '\n'
attrs[attr] += line
continue
line = line.strip()
if not line:
# Separator between different packages
if name:
ret[name] = attrs
name = None
attrs = {}
attr = None
continue
key, value = line.split(':', 1)
value = value.lstrip()
attr = _convert_to_standard_attr(key)
if attr == 'name':
name = value
elif filter_attrs is None or attr in filter_attrs:
attrs[attr] = value
if name:
ret[name] = attrs
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
.. versionadded:: 2017.7.0
:param names:
Names of the packages to get information about. If none are specified,
will return information for all installed packages.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
arch, conffiles, conflicts, depends, description, filename, group,
install_date_time_t, md5sum, packager, provides, recommends,
replaces, size, source, suggests, url, version
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed
salt '*' pkg.info_installed attr=version,packager
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> attr=version,packager
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,packager
'''
attr = kwargs.pop('attr', None)
if attr is None:
filter_attrs = None
elif isinstance(attr, six.string_types):
filter_attrs = set(attr.split(','))
else:
filter_attrs = set(attr)
ret = {}
if names:
# Specific list of names of installed packages
for name in names:
cmd = ['opkg', 'status', name]
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
else:
# All installed packages
cmd = ['opkg', 'status']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
return ret
def upgrade_available(name, **kwargs): # pylint: disable=unused-argument
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs): # pylint: disable=unused-argument
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2016.3.4
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0' '0.2.4.1-0'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] if ignore_epoch else six.text_type(x)
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
output = __salt__['cmd.run_stdout'](['opkg', '--version'],
output_loglevel='trace',
python_shell=False)
opkg_version = output.split(' ')[2].strip()
if salt.utils.versions.LooseVersion(opkg_version) >= \
salt.utils.versions.LooseVersion('0.3.4'):
cmd_compare = ['opkg', 'compare-versions']
elif salt.utils.path.which('opkg-compare-versions'):
cmd_compare = ['opkg-compare-versions']
else:
log.warning('Unable to find a compare-versions utility installed. Either upgrade opkg to '
'version > 0.3.4 (preferred) or install the older opkg-compare-versions script.')
return None
for oper, ret in (("<<", -1), ("=", 0), (">>", 1)):
cmd = cmd_compare[:]
cmd.append(_cmd_quote(pkg1))
cmd.append(oper)
cmd.append(_cmd_quote(pkg2))
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
ignore_retcode=True,
python_shell=False)
if retcode == 0:
return ret
return None
def _set_repo_option(repo, option):
'''
Set the option to repo
'''
if not option:
return
opt = option.split('=')
if len(opt) != 2:
return
if opt[0] == 'trusted':
repo['trusted'] = opt[1] == 'yes'
else:
repo[opt[0]] = opt[1]
def _set_repo_options(repo, options):
'''
Set the options to the repo.
'''
delimiters = "[", "]"
pattern = '|'.join(map(re.escape, delimiters))
for option in options:
splitted = re.split(pattern, option)
for opt in splitted:
_set_repo_option(repo, opt)
def _create_repo(line, filename):
'''
Create repo
'''
repo = {}
if line.startswith('#'):
repo['enabled'] = False
line = line[1:]
else:
repo['enabled'] = True
cols = salt.utils.args.shlex_split(line.strip())
repo['compressed'] = not cols[0] in 'src'
repo['name'] = cols[1]
repo['uri'] = cols[2]
repo['file'] = os.path.join(OPKG_CONFDIR, filename)
if len(cols) > 3:
_set_repo_options(repo, cols[3:])
return repo
def _read_repos(conf_file, repos, filename, regex):
'''
Read repos from configuration file
'''
for line in conf_file:
line = salt.utils.stringutils.to_unicode(line)
if not regex.search(line):
continue
repo = _create_repo(line, filename)
# do not store duplicated uri's
if repo['uri'] not in repos:
repos[repo['uri']] = [repo]
def list_repos(**kwargs): # pylint: disable=unused-argument
'''
Lists all repos on ``/etc/opkg/*.conf``
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos = {}
regex = re.compile(REPO_REGEXP)
for filename in os.listdir(OPKG_CONFDIR):
if not filename.endswith(".conf"):
continue
with salt.utils.files.fopen(os.path.join(OPKG_CONFDIR, filename)) as conf_file:
_read_repos(conf_file, repos, filename, regex)
return repos
def get_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Display a repo from the ``/etc/opkg/*.conf``
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo repo
'''
repos = list_repos()
if repos:
for source in six.itervalues(repos):
for sub in source:
if sub['name'] == repo:
return sub
return {}
def _del_repo_from_file(repo, filepath):
'''
Remove a repo from filepath
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
regex = re.compile(REPO_REGEXP)
for line in fhandle:
line = salt.utils.stringutils.to_unicode(line)
if regex.search(line):
if line.startswith('#'):
line = line[1:]
cols = salt.utils.args.shlex_split(line.strip())
if repo != cols[1]:
output.append(salt.utils.stringutils.to_str(line))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def _set_trusted_option_if_needed(repostr, trusted):
'''
Set trusted option to repo if needed
'''
if trusted is True:
repostr += ' [trusted=yes]'
elif trusted is False:
repostr += ' [trusted=no]'
return repostr
def _add_new_repo(repo, properties):
'''
Add a new repo entry
'''
repostr = '# ' if not properties.get('enabled') else ''
repostr += 'src/gz ' if properties.get('compressed') else 'src '
if ' ' in repo:
repostr += '"' + repo + '" '
else:
repostr += repo + ' '
repostr += properties.get('uri')
repostr = _set_trusted_option_if_needed(repostr, properties.get('trusted'))
repostr += '\n'
conffile = os.path.join(OPKG_CONFDIR, repo + '.conf')
with salt.utils.files.fopen(conffile, 'a') as fhandle:
fhandle.write(salt.utils.stringutils.to_str(repostr))
def _mod_repo_in_file(repo, repostr, filepath):
'''
Replace a repo entry in filepath with repostr
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
for line in fhandle:
cols = salt.utils.args.shlex_split(
salt.utils.stringutils.to_unicode(line).strip()
)
if repo not in cols:
output.append(line)
else:
output.append(salt.utils.stringutils.to_str(repostr + '\n'))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def del_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Delete a repo from ``/etc/opkg/*.conf``
If the file does not contain any other repo configuration, the file itself
will be deleted.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo repo
'''
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
repos = list_repos()
if repos:
deleted_from = dict()
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
deleted_from[source['file']] = 0
_del_repo_from_file(repo, source['file'])
if deleted_from:
ret = ''
for repository in repos:
source = repos[repository][0]
if source['file'] in deleted_from:
deleted_from[source['file']] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 1 and os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.\n')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
if refresh:
refresh_db()
return ret
return "Repo {0} doesn't exist in the opkg repo lists".format(repo)
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as uri is defined.
The following options are available to modify a repo definition:
repo
alias by which opkg refers to the repo.
uri
the URI to the repo.
compressed
defines (True or False) if the index file is compressed
enabled
enable or disable (True or False) repository
but do not remove if disabled.
refresh
enable or disable (True or False) auto-refresh of the repositories
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo repo uri=http://new/uri
salt '*' pkg.mod_repo repo enabled=False
'''
repos = list_repos()
found = False
uri = ''
if 'uri' in kwargs:
uri = kwargs['uri']
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
found = True
repostr = ''
if 'enabled' in kwargs and not kwargs['enabled']:
repostr += '# '
if 'compressed' in kwargs:
repostr += 'src/gz ' if kwargs['compressed'] else 'src'
else:
repostr += 'src/gz' if source['compressed'] else 'src'
repo_alias = kwargs['alias'] if 'alias' in kwargs else repo
if ' ' in repo_alias:
repostr += ' "{0}"'.format(repo_alias)
else:
repostr += ' {0}'.format(repo_alias)
repostr += ' {0}'.format(kwargs['uri'] if 'uri' in kwargs else source['uri'])
trusted = kwargs.get('trusted')
repostr = _set_trusted_option_if_needed(repostr, trusted) if trusted is not None else \
_set_trusted_option_if_needed(repostr, source.get('trusted'))
_mod_repo_in_file(repo, repostr, source['file'])
elif uri and source['uri'] == uri:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(uri, source['name']))
if not found:
# Need to add a new repo
if 'uri' not in kwargs:
raise CommandExecutionError(
'Repository \'{0}\' not found and no URI passed to create one.'.format(repo))
properties = {'uri': kwargs['uri']}
# If compressed is not defined, assume True
properties['compressed'] = kwargs['compressed'] if 'compressed' in kwargs else True
# If enabled is not defined, assume True
properties['enabled'] = kwargs['enabled'] if 'enabled' in kwargs else True
properties['trusted'] = kwargs.get('trusted')
_add_new_repo(repo, properties)
if 'refresh' in kwargs:
refresh_db()
def file_list(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
output = file_dict(*packages)
files = []
for package in list(output['packages'].values()):
files.extend(package)
return {'errors': output['errors'], 'files': files}
def file_dict(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
errors = []
ret = {}
cmd_files = ['opkg', 'files']
if not packages:
packages = list(list_pkgs().keys())
for package in packages:
files = []
cmd = cmd_files[:]
cmd.append(package)
out = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
for line in out['stdout'].splitlines():
if line.startswith('/'):
files.append(line)
elif line.startswith(' * '):
errors.append(line[3:])
break
else:
continue
if files:
ret[package] = files
return {'errors': errors, 'packages': ret}
def owner(*paths, **kwargs): # pylint: disable=unused-argument
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.opkg.version`, if a single
path is passed, a string will be returned, and if multiple paths are passed,
a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
cmd_search = ['opkg', 'search']
for path in paths:
cmd = cmd_search[:]
cmd.append(path)
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
if output:
ret[path] = output.split(' - ')[0].strip()
else:
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def version_clean(version):
'''
Clean the version string removing extra data.
There's nothing do to here for nipkg.py, therefore it will always
return the given version.
'''
return version
def check_extra_requirements(pkgname, pkgver):
'''
Check if the installed package already has the given requirements.
There's nothing do to here for nipkg.py, therefore it will always
return True.
'''
return True
|
saltstack/salt
|
salt/modules/opkg.py
|
upgrade
|
python
|
def upgrade(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
Upgrades all packages via ``opkg upgrade``
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
errors = []
if salt.utils.data.is_true(refresh):
refresh_db()
old = list_pkgs()
cmd = ['opkg', 'upgrade']
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
errors.append(result)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
|
Upgrades all packages via ``opkg upgrade``
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/opkg.py#L722-L773
|
[
"def is_true(value=None):\n '''\n Returns a boolean value representing the \"truth\" of the value passed. The\n rules for what is a \"True\" value are:\n\n 1. Integer/float values greater than 0\n 2. The string values \"True\" and \"true\"\n 3. Any object for which bool(obj) returns True\n '''\n # First, try int/float conversion\n try:\n value = int(value)\n except (ValueError, TypeError):\n pass\n try:\n value = float(value)\n except (ValueError, TypeError):\n pass\n\n # Now check for truthiness\n if isinstance(value, (six.integer_types, float)):\n return value > 0\n elif isinstance(value, six.string_types):\n return six.text_type(value).lower() == 'true'\n else:\n return bool(value)\n",
"def list_pkgs(versions_as_list=False, **kwargs):\n '''\n List the packages currently installed in a dict::\n\n {'<package_name>': '<version>'}\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.list_pkgs\n salt '*' pkg.list_pkgs versions_as_list=True\n '''\n versions_as_list = salt.utils.data.is_true(versions_as_list)\n # not yet implemented or not applicable\n if any([salt.utils.data.is_true(kwargs.get(x))\n for x in ('removed', 'purge_desired')]):\n return {}\n\n if 'pkg.list_pkgs' in __context__:\n if versions_as_list:\n return __context__['pkg.list_pkgs']\n else:\n ret = copy.deepcopy(__context__['pkg.list_pkgs'])\n __salt__['pkg_resource.stringify'](ret)\n return ret\n\n cmd = ['opkg', 'list-installed']\n ret = {}\n out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)\n for line in salt.utils.itertools.split(out, '\\n'):\n # This is a continuation of package description\n if not line or line[0] == ' ':\n continue\n\n # This contains package name, version, and description.\n # Extract the first two.\n pkg_name, pkg_version = line.split(' - ', 2)[:2]\n __salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version)\n\n __salt__['pkg_resource.sort_pkglist'](ret)\n __context__['pkg.list_pkgs'] = copy.deepcopy(ret)\n if not versions_as_list:\n __salt__['pkg_resource.stringify'](ret)\n return ret\n",
"def refresh_db(failhard=False, **kwargs): # pylint: disable=unused-argument\n '''\n Updates the opkg database to latest packages based upon repositories\n\n Returns a dict, with the keys being package databases and the values being\n the result of the update attempt. Values can be one of the following:\n\n - ``True``: Database updated successfully\n - ``False``: Problem updating database\n\n failhard\n If False, return results of failed lines as ``False`` for the package\n database that encountered the error.\n If True, raise an error with a list of the package databases that\n encountered errors.\n\n .. versionadded:: 2018.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.refresh_db\n '''\n # Remove rtag file to keep multiple refreshes from happening in pkg states\n salt.utils.pkg.clear_rtag(__opts__)\n ret = {}\n error_repos = []\n cmd = ['opkg', 'update']\n # opkg returns a non-zero retcode when there is a failure to refresh\n # from one or more repos. Due to this, ignore the retcode.\n call = __salt__['cmd.run_all'](cmd,\n output_loglevel='trace',\n python_shell=False,\n ignore_retcode=True,\n redirect_stderr=True)\n\n out = call['stdout']\n prev_line = ''\n for line in salt.utils.itertools.split(out, '\\n'):\n if 'Inflating' in line:\n key = line.strip().split()[1][:-1]\n ret[key] = True\n elif 'Updated source' in line:\n # Use the previous line.\n key = prev_line.strip().split()[1][:-1]\n ret[key] = True\n elif 'Failed to download' in line:\n key = line.strip().split()[5].split(',')[0]\n ret[key] = False\n error_repos.append(key)\n prev_line = line\n\n if failhard and error_repos:\n raise CommandExecutionError(\n 'Error getting repos: {0}'.format(', '.join(error_repos))\n )\n\n # On a non-zero exit code where no failed repos were found, raise an\n # exception because this appears to be a different kind of error.\n if call['retcode'] != 0 and not error_repos:\n raise CommandExecutionError(out)\n\n return ret\n",
"def _get_restartcheck_result(errors):\n '''\n Return restartcheck result and append errors (if any) to ``errors``\n '''\n rs_result = __salt__['restartcheck.restartcheck'](verbose=False)\n if isinstance(rs_result, dict) and 'comment' in rs_result:\n errors.append(rs_result['comment'])\n return rs_result\n",
"def _process_restartcheck_result(rs_result, **kwargs):\n '''\n Check restartcheck output to see if system/service restarts were requested\n and take appropriate action.\n '''\n if 'No packages seem to need to be restarted' in rs_result:\n return\n reboot_required = False\n for rstr in rs_result:\n if 'System restart required' in rstr:\n _update_nilrt_restart_state()\n __salt__['system.set_reboot_required_witnessed']()\n reboot_required = True\n if kwargs.get('always_restart_services', True) or not reboot_required:\n for rstr in rs_result:\n if 'System restart required' not in rstr:\n service = os.path.join('/etc/init.d', rstr)\n if os.path.exists(service):\n __salt__['cmd.run']([service, 'restart'])\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Opkg
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
.. versionadded: 2016.3.0
.. note::
For version comparison support on opkg < 0.3.4, the ``opkg-utils`` package
must be installed.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import os
import re
import logging
import errno
# Import salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.itertools
import salt.utils.path
import salt.utils.pkg
import salt.utils.stringutils
import salt.utils.versions
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import shlex_quote as _cmd_quote # pylint: disable=import-error
from salt.ext.six.moves import map # pylint: disable=import-error,redefined-builtin
REPO_REGEXP = r'^#?\s*(src|src/gz)\s+([^\s<>]+|"[^<>]+")\s+[^\s<>]+'
OPKG_CONFDIR = '/etc/opkg'
ATTR_MAP = {
'Architecture': 'arch',
'Homepage': 'url',
'Installed-Time': 'install_date_time_t',
'Maintainer': 'packager',
'Package': 'name',
'Section': 'group'
}
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
NILRT_RESTARTCHECK_STATE_PATH = '/var/lib/salt/restartcheck_state'
def _update_nilrt_restart_state():
'''
NILRT systems determine whether to reboot after various package operations
including but not limited to kernel module installs/removals by checking
specific file md5sums & timestamps. These files are touched/modified by
the post-install/post-remove functions of their respective packages.
The opkg module uses this function to store/update those file timestamps
and checksums to be used later by the restartcheck module.
'''
__salt__['cmd.shell']('stat -c %Y /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.timestamp'
.format(NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.md5sum'
.format(NILRT_RESTARTCHECK_STATE_PATH))
# We can't assume nisysapi.ini always exists like modules.dep
nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'
if os.path.exists(nisysapi_path):
__salt__['cmd.shell']('stat -c %Y {0} >{1}/nisysapi.ini.timestamp'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0} >{1}/nisysapi.ini.md5sum'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
# Expert plugin files get added to a conf.d dir, so keep track of the total
# no. of files, their timestamps and content hashes
nisysapi_conf_d_path = "/usr/lib/{0}/nisysapi/conf.d/experts/".format(
'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'
)
if os.path.exists(nisysapi_conf_d_path):
with salt.utils.files.fopen('{0}/sysapi.conf.d.count'.format(
NILRT_RESTARTCHECK_STATE_PATH), 'w') as fcount:
fcount.write(str(len(os.listdir(nisysapi_conf_d_path))))
for fexpert in os.listdir(nisysapi_conf_d_path):
__salt__['cmd.shell']('stat -c %Y {0}/{1} >{2}/{1}.timestamp'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0}/{1} >{2}/{1}.md5sum'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
def _get_restartcheck_result(errors):
'''
Return restartcheck result and append errors (if any) to ``errors``
'''
rs_result = __salt__['restartcheck.restartcheck'](verbose=False)
if isinstance(rs_result, dict) and 'comment' in rs_result:
errors.append(rs_result['comment'])
return rs_result
def _process_restartcheck_result(rs_result, **kwargs):
'''
Check restartcheck output to see if system/service restarts were requested
and take appropriate action.
'''
if 'No packages seem to need to be restarted' in rs_result:
return
reboot_required = False
for rstr in rs_result:
if 'System restart required' in rstr:
_update_nilrt_restart_state()
__salt__['system.set_reboot_required_witnessed']()
reboot_required = True
if kwargs.get('always_restart_services', True) or not reboot_required:
for rstr in rs_result:
if 'System restart required' not in rstr:
service = os.path.join('/etc/init.d', rstr)
if os.path.exists(service):
__salt__['cmd.run']([service, 'restart'])
def __virtual__():
'''
Confirm this module is on a nilrt based system
'''
if __grains__.get('os_family') == 'NILinuxRT':
try:
os.makedirs(NILRT_RESTARTCHECK_STATE_PATH)
except OSError as exc:
if exc.errno != errno.EEXIST:
return False, 'Error creating {0} (-{1}): {2}'.format(
NILRT_RESTARTCHECK_STATE_PATH,
exc.errno,
exc.strerror)
# populate state dir if empty
if not os.listdir(NILRT_RESTARTCHECK_STATE_PATH):
_update_nilrt_restart_state()
return __virtualname__
if os.path.isdir(OPKG_CONFDIR):
return __virtualname__
return False, "Module opkg only works on OpenEmbedded based systems"
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
if not names:
return ''
ret = {}
for name in names:
ret[name] = ''
# Refresh before looking for the latest version available
if refresh:
refresh_db()
cmd = ['opkg', 'list-upgradable']
out = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
try:
name, _oldversion, newversion = line.split(' - ')
if name in names:
ret[name] = newversion
except ValueError:
pass
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = latest_version
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(failhard=False, **kwargs): # pylint: disable=unused-argument
'''
Updates the opkg database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
failhard
If False, return results of failed lines as ``False`` for the package
database that encountered the error.
If True, raise an error with a list of the package databases that
encountered errors.
.. versionadded:: 2018.3.0
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
error_repos = []
cmd = ['opkg', 'update']
# opkg returns a non-zero retcode when there is a failure to refresh
# from one or more repos. Due to this, ignore the retcode.
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True,
redirect_stderr=True)
out = call['stdout']
prev_line = ''
for line in salt.utils.itertools.split(out, '\n'):
if 'Inflating' in line:
key = line.strip().split()[1][:-1]
ret[key] = True
elif 'Updated source' in line:
# Use the previous line.
key = prev_line.strip().split()[1][:-1]
ret[key] = True
elif 'Failed to download' in line:
key = line.strip().split()[5].split(',')[0]
ret[key] = False
error_repos.append(key)
prev_line = line
if failhard and error_repos:
raise CommandExecutionError(
'Error getting repos: {0}'.format(', '.join(error_repos))
)
# On a non-zero exit code where no failed repos were found, raise an
# exception because this appears to be a different kind of error.
if call['retcode'] != 0 and not error_repos:
raise CommandExecutionError(out)
return ret
def _is_testmode(**kwargs):
'''
Returns whether a test mode (noaction) operation was requested.
'''
return bool(kwargs.get('test') or __opts__.get('test'))
def _append_noaction_if_testmode(cmd, **kwargs):
'''
Adds the --noaction flag to the command if it's running in the test mode.
'''
if _is_testmode(**kwargs):
cmd.append('--noaction')
def _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall):
'''
Builds a list of install commands to be executed in sequence in order to process
each of the to_install, to_downgrade, and to_reinstall lists.
'''
cmds = []
if to_install:
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(to_install)
cmds.append(cmd)
if to_downgrade:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-downgrade')
cmd.extend(to_downgrade)
cmds.append(cmd)
if to_reinstall:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-reinstall')
cmd.extend(to_reinstall)
cmds.append(cmd)
return cmds
def _parse_reported_packages_from_install_output(output):
'''
Parses the output of "opkg install" to determine what packages would have been
installed by an operation run with the --noaction flag.
We are looking for lines like:
Installing <package> (<version>) on <target>
or
Upgrading <package> from <oldVersion> to <version> on root
'''
reported_pkgs = {}
install_pattern = re.compile(r'Installing\s(?P<package>.*?)\s\((?P<version>.*?)\)\son\s(?P<target>.*?)')
upgrade_pattern = re.compile(r'Upgrading\s(?P<package>.*?)\sfrom\s(?P<oldVersion>.*?)\sto\s(?P<version>.*?)\son\s(?P<target>.*?)')
for line in salt.utils.itertools.split(output, '\n'):
match = install_pattern.match(line)
if match is None:
match = upgrade_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = match.group('version')
return reported_pkgs
def _execute_install_command(cmd, parse_output, errors, parsed_packages):
'''
Executes a command for the install operation.
If the command fails, its error output will be appended to the errors list.
If the command succeeds and parse_output is true, updated packages will be appended
to the parsed_packages dictionary.
'''
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors.append(out['stderr'])
else:
errors.append(out['stdout'])
elif parse_output:
parsed_packages.update(_parse_reported_packages_from_install_output(out['stdout']))
def install(name=None,
refresh=False,
pkgs=None,
sources=None,
reinstall=False,
**kwargs):
'''
Install the passed package, add refresh=True to update the opkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionadded:: 2017.7.0
reinstall : False
Specifying reinstall=True will use ``opkg install --force-reinstall``
rather than simply ``opkg install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``opkg
install --force-reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2017.7.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of IPK packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
install_recommends
Whether to install the packages marked as recommended. Default is True.
only_upgrade
Only upgrade the packages (disallow downgrades), if they are already
installed. Default is False.
.. versionadded:: 2017.7.0
always_restart_services
Whether to restart services even if a reboot is required. Default is True.
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
refreshdb = salt.utils.data.is_true(refresh)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
cmd_prefix = ['opkg', 'install']
to_install = []
to_reinstall = []
to_downgrade = []
_append_noaction_if_testmode(cmd_prefix, **kwargs)
if not pkg_params:
return {}
elif pkg_type == 'file':
if reinstall:
cmd_prefix.append('--force-reinstall')
if not kwargs.get('only_upgrade', False):
cmd_prefix.append('--force-downgrade')
to_install.extend(pkg_params)
elif pkg_type == 'repository':
if not kwargs.get('install_recommends', True):
cmd_prefix.append('--no-install-recommends')
for pkgname, pkgversion in six.iteritems(pkg_params):
if (name and pkgs is None and kwargs.get('version') and
len(pkg_params) == 1):
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
version_num = pkgversion
if version_num is None:
# Don't allow downgrades if the version
# number is not specified.
if reinstall and pkgname in old:
to_reinstall.append(pkgname)
else:
to_install.append(pkgname)
else:
pkgstr = '{0}={1}'.format(pkgname, version_num)
cver = old.get(pkgname, '')
if reinstall and cver and salt.utils.versions.compare(
ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall.append(pkgstr)
elif not cver or salt.utils.versions.compare(
ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
to_install.append(pkgstr)
else:
if not kwargs.get('only_upgrade', False):
to_downgrade.append(pkgstr)
else:
# This should cause the command to fail.
to_install.append(pkgstr)
cmds = _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall)
if not cmds:
return {}
if refreshdb:
refresh_db()
errors = []
is_testmode = _is_testmode(**kwargs)
test_packages = {}
for cmd in cmds:
_execute_install_command(cmd, is_testmode, errors, test_packages)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if is_testmode:
new = copy.deepcopy(new)
new.update(test_packages)
ret = salt.utils.data.compare_dicts(old, new)
if pkg_type == 'file' and reinstall:
# For file-based packages, prepare 'to_reinstall' to have a list
# of all the package names that may have been reinstalled.
# This way, we could include reinstalled packages in 'ret'.
for pkgfile in to_install:
# Convert from file name to package name.
cmd = ['opkg', 'info', pkgfile]
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] == 0:
# Just need the package name.
pkginfo_dict = _process_info_installed_output(
out['stdout'], []
)
if pkginfo_dict:
to_reinstall.append(list(pkginfo_dict.keys())[0])
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def _parse_reported_packages_from_remove_output(output):
'''
Parses the output of "opkg remove" to determine what packages would have been
removed by an operation run with the --noaction flag.
We are looking for lines like
Removing <package> (<version>) from <Target>...
'''
reported_pkgs = {}
remove_pattern = re.compile(r'Removing\s(?P<package>.*?)\s\((?P<version>.*?)\)\sfrom\s(?P<target>.*?)...')
for line in salt.utils.itertools.split(output, '\n'):
match = remove_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = ''
return reported_pkgs
def remove(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Remove packages using ``opkg remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
remove_dependencies
Remove package and all dependencies
.. versionadded:: 2019.2.0
auto_remove_deps
Remove packages that were installed automatically to satisfy dependencies
.. versionadded:: 2019.2.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
salt '*' pkg.remove pkgs='["foo", "bar"]' remove_dependencies=True auto_remove_deps=True
'''
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 {}
cmd = ['opkg', 'remove']
_append_noaction_if_testmode(cmd, **kwargs)
if kwargs.get('remove_dependencies', False):
cmd.append('--force-removal-of-dependent-packages')
if kwargs.get('auto_remove_deps', False):
cmd.append('--autoremove')
cmd.extend(targets)
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors = [out['stderr']]
else:
errors = [out['stdout']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if _is_testmode(**kwargs):
reportedPkgs = _parse_reported_packages_from_remove_output(out['stdout'])
new = {k: v for k, v in new.items() if k not in reportedPkgs}
ret = salt.utils.data.compare_dicts(old, new)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def purge(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Package purges are not supported by opkg, this function is identical to
:mod:`pkg.remove <salt.modules.opkg.remove>`.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name, pkgs=pkgs)
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif state != 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = _set_state(target, 'hold')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif state == 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret['comment'] = ('Package {0} is set not to be held.'
.format(target))
else:
result = _set_state(target, 'ok')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def _get_state(pkg):
'''
View package state from the opkg database
Return the state of pkg
'''
cmd = ['opkg', 'status']
cmd.append(pkg)
out = __salt__['cmd.run'](cmd, python_shell=False)
state_flag = ''
for line in salt.utils.itertools.split(out, '\n'):
if line.startswith('Status'):
_status, _state_want, state_flag, _state_status = line.split()
return state_flag
def _set_state(pkg, state):
'''
Change package state on the opkg database
The state can be any of:
- hold
- noprune
- user
- ok
- installed
- unpacked
This command is commonly used to mark a specific package to be held from
being upgraded, that is, to be kept at a certain version.
Returns a dict containing the package name, and the new and old
versions.
'''
ret = {}
valid_states = ('hold', 'noprune', 'user', 'ok', 'installed', 'unpacked')
if state not in valid_states:
raise SaltInvocationError('Invalid state: {0}'.format(state))
oldstate = _get_state(pkg)
cmd = ['opkg', 'flag']
cmd.append(state)
cmd.append(pkg)
_out = __salt__['cmd.run'](cmd, python_shell=False)
# Missing return value check due to opkg issue 160
ret[pkg] = {'old': oldstate,
'new': state}
return ret
def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
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
cmd = ['opkg', 'list-installed']
ret = {}
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
# This is a continuation of package description
if not line or line[0] == ' ':
continue
# This contains package name, version, and description.
# Extract the first two.
pkg_name, pkg_version = line.split(' - ', 2)[:2]
__salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version)
__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 list_upgrades(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
List all available package upgrades.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
ret = {}
if salt.utils.data.is_true(refresh):
refresh_db()
cmd = ['opkg', 'list-upgradable']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
if 'stdout' in call:
comment += call['stdout']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
name, _oldversion, newversion = line.split(' - ')
ret[name] = newversion
return ret
def _convert_to_standard_attr(attr):
'''
Helper function for _process_info_installed_output()
Converts an opkg attribute name to a standard attribute
name which is used across 'pkg' modules.
'''
ret_attr = ATTR_MAP.get(attr, None)
if ret_attr is None:
# All others convert to lowercase
return attr.lower()
return ret_attr
def _process_info_installed_output(out, filter_attrs):
'''
Helper function for info_installed()
Processes stdout output from a single invocation of
'opkg status'.
'''
ret = {}
name = None
attrs = {}
attr = None
for line in salt.utils.itertools.split(out, '\n'):
if line and line[0] == ' ':
# This is a continuation of the last attr
if filter_attrs is None or attr in filter_attrs:
line = line.strip()
if attrs[attr]:
# If attr is empty, don't add leading newline
attrs[attr] += '\n'
attrs[attr] += line
continue
line = line.strip()
if not line:
# Separator between different packages
if name:
ret[name] = attrs
name = None
attrs = {}
attr = None
continue
key, value = line.split(':', 1)
value = value.lstrip()
attr = _convert_to_standard_attr(key)
if attr == 'name':
name = value
elif filter_attrs is None or attr in filter_attrs:
attrs[attr] = value
if name:
ret[name] = attrs
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
.. versionadded:: 2017.7.0
:param names:
Names of the packages to get information about. If none are specified,
will return information for all installed packages.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
arch, conffiles, conflicts, depends, description, filename, group,
install_date_time_t, md5sum, packager, provides, recommends,
replaces, size, source, suggests, url, version
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed
salt '*' pkg.info_installed attr=version,packager
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> attr=version,packager
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,packager
'''
attr = kwargs.pop('attr', None)
if attr is None:
filter_attrs = None
elif isinstance(attr, six.string_types):
filter_attrs = set(attr.split(','))
else:
filter_attrs = set(attr)
ret = {}
if names:
# Specific list of names of installed packages
for name in names:
cmd = ['opkg', 'status', name]
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
else:
# All installed packages
cmd = ['opkg', 'status']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
return ret
def upgrade_available(name, **kwargs): # pylint: disable=unused-argument
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs): # pylint: disable=unused-argument
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2016.3.4
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0' '0.2.4.1-0'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] if ignore_epoch else six.text_type(x)
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
output = __salt__['cmd.run_stdout'](['opkg', '--version'],
output_loglevel='trace',
python_shell=False)
opkg_version = output.split(' ')[2].strip()
if salt.utils.versions.LooseVersion(opkg_version) >= \
salt.utils.versions.LooseVersion('0.3.4'):
cmd_compare = ['opkg', 'compare-versions']
elif salt.utils.path.which('opkg-compare-versions'):
cmd_compare = ['opkg-compare-versions']
else:
log.warning('Unable to find a compare-versions utility installed. Either upgrade opkg to '
'version > 0.3.4 (preferred) or install the older opkg-compare-versions script.')
return None
for oper, ret in (("<<", -1), ("=", 0), (">>", 1)):
cmd = cmd_compare[:]
cmd.append(_cmd_quote(pkg1))
cmd.append(oper)
cmd.append(_cmd_quote(pkg2))
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
ignore_retcode=True,
python_shell=False)
if retcode == 0:
return ret
return None
def _set_repo_option(repo, option):
'''
Set the option to repo
'''
if not option:
return
opt = option.split('=')
if len(opt) != 2:
return
if opt[0] == 'trusted':
repo['trusted'] = opt[1] == 'yes'
else:
repo[opt[0]] = opt[1]
def _set_repo_options(repo, options):
'''
Set the options to the repo.
'''
delimiters = "[", "]"
pattern = '|'.join(map(re.escape, delimiters))
for option in options:
splitted = re.split(pattern, option)
for opt in splitted:
_set_repo_option(repo, opt)
def _create_repo(line, filename):
'''
Create repo
'''
repo = {}
if line.startswith('#'):
repo['enabled'] = False
line = line[1:]
else:
repo['enabled'] = True
cols = salt.utils.args.shlex_split(line.strip())
repo['compressed'] = not cols[0] in 'src'
repo['name'] = cols[1]
repo['uri'] = cols[2]
repo['file'] = os.path.join(OPKG_CONFDIR, filename)
if len(cols) > 3:
_set_repo_options(repo, cols[3:])
return repo
def _read_repos(conf_file, repos, filename, regex):
'''
Read repos from configuration file
'''
for line in conf_file:
line = salt.utils.stringutils.to_unicode(line)
if not regex.search(line):
continue
repo = _create_repo(line, filename)
# do not store duplicated uri's
if repo['uri'] not in repos:
repos[repo['uri']] = [repo]
def list_repos(**kwargs): # pylint: disable=unused-argument
'''
Lists all repos on ``/etc/opkg/*.conf``
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos = {}
regex = re.compile(REPO_REGEXP)
for filename in os.listdir(OPKG_CONFDIR):
if not filename.endswith(".conf"):
continue
with salt.utils.files.fopen(os.path.join(OPKG_CONFDIR, filename)) as conf_file:
_read_repos(conf_file, repos, filename, regex)
return repos
def get_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Display a repo from the ``/etc/opkg/*.conf``
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo repo
'''
repos = list_repos()
if repos:
for source in six.itervalues(repos):
for sub in source:
if sub['name'] == repo:
return sub
return {}
def _del_repo_from_file(repo, filepath):
'''
Remove a repo from filepath
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
regex = re.compile(REPO_REGEXP)
for line in fhandle:
line = salt.utils.stringutils.to_unicode(line)
if regex.search(line):
if line.startswith('#'):
line = line[1:]
cols = salt.utils.args.shlex_split(line.strip())
if repo != cols[1]:
output.append(salt.utils.stringutils.to_str(line))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def _set_trusted_option_if_needed(repostr, trusted):
'''
Set trusted option to repo if needed
'''
if trusted is True:
repostr += ' [trusted=yes]'
elif trusted is False:
repostr += ' [trusted=no]'
return repostr
def _add_new_repo(repo, properties):
'''
Add a new repo entry
'''
repostr = '# ' if not properties.get('enabled') else ''
repostr += 'src/gz ' if properties.get('compressed') else 'src '
if ' ' in repo:
repostr += '"' + repo + '" '
else:
repostr += repo + ' '
repostr += properties.get('uri')
repostr = _set_trusted_option_if_needed(repostr, properties.get('trusted'))
repostr += '\n'
conffile = os.path.join(OPKG_CONFDIR, repo + '.conf')
with salt.utils.files.fopen(conffile, 'a') as fhandle:
fhandle.write(salt.utils.stringutils.to_str(repostr))
def _mod_repo_in_file(repo, repostr, filepath):
'''
Replace a repo entry in filepath with repostr
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
for line in fhandle:
cols = salt.utils.args.shlex_split(
salt.utils.stringutils.to_unicode(line).strip()
)
if repo not in cols:
output.append(line)
else:
output.append(salt.utils.stringutils.to_str(repostr + '\n'))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def del_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Delete a repo from ``/etc/opkg/*.conf``
If the file does not contain any other repo configuration, the file itself
will be deleted.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo repo
'''
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
repos = list_repos()
if repos:
deleted_from = dict()
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
deleted_from[source['file']] = 0
_del_repo_from_file(repo, source['file'])
if deleted_from:
ret = ''
for repository in repos:
source = repos[repository][0]
if source['file'] in deleted_from:
deleted_from[source['file']] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 1 and os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.\n')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
if refresh:
refresh_db()
return ret
return "Repo {0} doesn't exist in the opkg repo lists".format(repo)
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as uri is defined.
The following options are available to modify a repo definition:
repo
alias by which opkg refers to the repo.
uri
the URI to the repo.
compressed
defines (True or False) if the index file is compressed
enabled
enable or disable (True or False) repository
but do not remove if disabled.
refresh
enable or disable (True or False) auto-refresh of the repositories
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo repo uri=http://new/uri
salt '*' pkg.mod_repo repo enabled=False
'''
repos = list_repos()
found = False
uri = ''
if 'uri' in kwargs:
uri = kwargs['uri']
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
found = True
repostr = ''
if 'enabled' in kwargs and not kwargs['enabled']:
repostr += '# '
if 'compressed' in kwargs:
repostr += 'src/gz ' if kwargs['compressed'] else 'src'
else:
repostr += 'src/gz' if source['compressed'] else 'src'
repo_alias = kwargs['alias'] if 'alias' in kwargs else repo
if ' ' in repo_alias:
repostr += ' "{0}"'.format(repo_alias)
else:
repostr += ' {0}'.format(repo_alias)
repostr += ' {0}'.format(kwargs['uri'] if 'uri' in kwargs else source['uri'])
trusted = kwargs.get('trusted')
repostr = _set_trusted_option_if_needed(repostr, trusted) if trusted is not None else \
_set_trusted_option_if_needed(repostr, source.get('trusted'))
_mod_repo_in_file(repo, repostr, source['file'])
elif uri and source['uri'] == uri:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(uri, source['name']))
if not found:
# Need to add a new repo
if 'uri' not in kwargs:
raise CommandExecutionError(
'Repository \'{0}\' not found and no URI passed to create one.'.format(repo))
properties = {'uri': kwargs['uri']}
# If compressed is not defined, assume True
properties['compressed'] = kwargs['compressed'] if 'compressed' in kwargs else True
# If enabled is not defined, assume True
properties['enabled'] = kwargs['enabled'] if 'enabled' in kwargs else True
properties['trusted'] = kwargs.get('trusted')
_add_new_repo(repo, properties)
if 'refresh' in kwargs:
refresh_db()
def file_list(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
output = file_dict(*packages)
files = []
for package in list(output['packages'].values()):
files.extend(package)
return {'errors': output['errors'], 'files': files}
def file_dict(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
errors = []
ret = {}
cmd_files = ['opkg', 'files']
if not packages:
packages = list(list_pkgs().keys())
for package in packages:
files = []
cmd = cmd_files[:]
cmd.append(package)
out = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
for line in out['stdout'].splitlines():
if line.startswith('/'):
files.append(line)
elif line.startswith(' * '):
errors.append(line[3:])
break
else:
continue
if files:
ret[package] = files
return {'errors': errors, 'packages': ret}
def owner(*paths, **kwargs): # pylint: disable=unused-argument
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.opkg.version`, if a single
path is passed, a string will be returned, and if multiple paths are passed,
a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
cmd_search = ['opkg', 'search']
for path in paths:
cmd = cmd_search[:]
cmd.append(path)
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
if output:
ret[path] = output.split(' - ')[0].strip()
else:
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def version_clean(version):
'''
Clean the version string removing extra data.
There's nothing do to here for nipkg.py, therefore it will always
return the given version.
'''
return version
def check_extra_requirements(pkgname, pkgver):
'''
Check if the installed package already has the given requirements.
There's nothing do to here for nipkg.py, therefore it will always
return True.
'''
return True
|
saltstack/salt
|
salt/modules/opkg.py
|
hold
|
python
|
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif state != 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = _set_state(target, 'hold')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
|
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/opkg.py#L776-L844
|
[
"def _get_state(pkg):\n '''\n View package state from the opkg database\n\n Return the state of pkg\n '''\n cmd = ['opkg', 'status']\n cmd.append(pkg)\n out = __salt__['cmd.run'](cmd, python_shell=False)\n state_flag = ''\n for line in salt.utils.itertools.split(out, '\\n'):\n if line.startswith('Status'):\n _status, _state_want, state_flag, _state_status = line.split()\n\n return state_flag\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Opkg
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
.. versionadded: 2016.3.0
.. note::
For version comparison support on opkg < 0.3.4, the ``opkg-utils`` package
must be installed.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import os
import re
import logging
import errno
# Import salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.itertools
import salt.utils.path
import salt.utils.pkg
import salt.utils.stringutils
import salt.utils.versions
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import shlex_quote as _cmd_quote # pylint: disable=import-error
from salt.ext.six.moves import map # pylint: disable=import-error,redefined-builtin
REPO_REGEXP = r'^#?\s*(src|src/gz)\s+([^\s<>]+|"[^<>]+")\s+[^\s<>]+'
OPKG_CONFDIR = '/etc/opkg'
ATTR_MAP = {
'Architecture': 'arch',
'Homepage': 'url',
'Installed-Time': 'install_date_time_t',
'Maintainer': 'packager',
'Package': 'name',
'Section': 'group'
}
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
NILRT_RESTARTCHECK_STATE_PATH = '/var/lib/salt/restartcheck_state'
def _update_nilrt_restart_state():
'''
NILRT systems determine whether to reboot after various package operations
including but not limited to kernel module installs/removals by checking
specific file md5sums & timestamps. These files are touched/modified by
the post-install/post-remove functions of their respective packages.
The opkg module uses this function to store/update those file timestamps
and checksums to be used later by the restartcheck module.
'''
__salt__['cmd.shell']('stat -c %Y /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.timestamp'
.format(NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.md5sum'
.format(NILRT_RESTARTCHECK_STATE_PATH))
# We can't assume nisysapi.ini always exists like modules.dep
nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'
if os.path.exists(nisysapi_path):
__salt__['cmd.shell']('stat -c %Y {0} >{1}/nisysapi.ini.timestamp'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0} >{1}/nisysapi.ini.md5sum'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
# Expert plugin files get added to a conf.d dir, so keep track of the total
# no. of files, their timestamps and content hashes
nisysapi_conf_d_path = "/usr/lib/{0}/nisysapi/conf.d/experts/".format(
'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'
)
if os.path.exists(nisysapi_conf_d_path):
with salt.utils.files.fopen('{0}/sysapi.conf.d.count'.format(
NILRT_RESTARTCHECK_STATE_PATH), 'w') as fcount:
fcount.write(str(len(os.listdir(nisysapi_conf_d_path))))
for fexpert in os.listdir(nisysapi_conf_d_path):
__salt__['cmd.shell']('stat -c %Y {0}/{1} >{2}/{1}.timestamp'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0}/{1} >{2}/{1}.md5sum'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
def _get_restartcheck_result(errors):
'''
Return restartcheck result and append errors (if any) to ``errors``
'''
rs_result = __salt__['restartcheck.restartcheck'](verbose=False)
if isinstance(rs_result, dict) and 'comment' in rs_result:
errors.append(rs_result['comment'])
return rs_result
def _process_restartcheck_result(rs_result, **kwargs):
'''
Check restartcheck output to see if system/service restarts were requested
and take appropriate action.
'''
if 'No packages seem to need to be restarted' in rs_result:
return
reboot_required = False
for rstr in rs_result:
if 'System restart required' in rstr:
_update_nilrt_restart_state()
__salt__['system.set_reboot_required_witnessed']()
reboot_required = True
if kwargs.get('always_restart_services', True) or not reboot_required:
for rstr in rs_result:
if 'System restart required' not in rstr:
service = os.path.join('/etc/init.d', rstr)
if os.path.exists(service):
__salt__['cmd.run']([service, 'restart'])
def __virtual__():
'''
Confirm this module is on a nilrt based system
'''
if __grains__.get('os_family') == 'NILinuxRT':
try:
os.makedirs(NILRT_RESTARTCHECK_STATE_PATH)
except OSError as exc:
if exc.errno != errno.EEXIST:
return False, 'Error creating {0} (-{1}): {2}'.format(
NILRT_RESTARTCHECK_STATE_PATH,
exc.errno,
exc.strerror)
# populate state dir if empty
if not os.listdir(NILRT_RESTARTCHECK_STATE_PATH):
_update_nilrt_restart_state()
return __virtualname__
if os.path.isdir(OPKG_CONFDIR):
return __virtualname__
return False, "Module opkg only works on OpenEmbedded based systems"
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
if not names:
return ''
ret = {}
for name in names:
ret[name] = ''
# Refresh before looking for the latest version available
if refresh:
refresh_db()
cmd = ['opkg', 'list-upgradable']
out = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
try:
name, _oldversion, newversion = line.split(' - ')
if name in names:
ret[name] = newversion
except ValueError:
pass
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = latest_version
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(failhard=False, **kwargs): # pylint: disable=unused-argument
'''
Updates the opkg database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
failhard
If False, return results of failed lines as ``False`` for the package
database that encountered the error.
If True, raise an error with a list of the package databases that
encountered errors.
.. versionadded:: 2018.3.0
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
error_repos = []
cmd = ['opkg', 'update']
# opkg returns a non-zero retcode when there is a failure to refresh
# from one or more repos. Due to this, ignore the retcode.
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True,
redirect_stderr=True)
out = call['stdout']
prev_line = ''
for line in salt.utils.itertools.split(out, '\n'):
if 'Inflating' in line:
key = line.strip().split()[1][:-1]
ret[key] = True
elif 'Updated source' in line:
# Use the previous line.
key = prev_line.strip().split()[1][:-1]
ret[key] = True
elif 'Failed to download' in line:
key = line.strip().split()[5].split(',')[0]
ret[key] = False
error_repos.append(key)
prev_line = line
if failhard and error_repos:
raise CommandExecutionError(
'Error getting repos: {0}'.format(', '.join(error_repos))
)
# On a non-zero exit code where no failed repos were found, raise an
# exception because this appears to be a different kind of error.
if call['retcode'] != 0 and not error_repos:
raise CommandExecutionError(out)
return ret
def _is_testmode(**kwargs):
'''
Returns whether a test mode (noaction) operation was requested.
'''
return bool(kwargs.get('test') or __opts__.get('test'))
def _append_noaction_if_testmode(cmd, **kwargs):
'''
Adds the --noaction flag to the command if it's running in the test mode.
'''
if _is_testmode(**kwargs):
cmd.append('--noaction')
def _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall):
'''
Builds a list of install commands to be executed in sequence in order to process
each of the to_install, to_downgrade, and to_reinstall lists.
'''
cmds = []
if to_install:
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(to_install)
cmds.append(cmd)
if to_downgrade:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-downgrade')
cmd.extend(to_downgrade)
cmds.append(cmd)
if to_reinstall:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-reinstall')
cmd.extend(to_reinstall)
cmds.append(cmd)
return cmds
def _parse_reported_packages_from_install_output(output):
'''
Parses the output of "opkg install" to determine what packages would have been
installed by an operation run with the --noaction flag.
We are looking for lines like:
Installing <package> (<version>) on <target>
or
Upgrading <package> from <oldVersion> to <version> on root
'''
reported_pkgs = {}
install_pattern = re.compile(r'Installing\s(?P<package>.*?)\s\((?P<version>.*?)\)\son\s(?P<target>.*?)')
upgrade_pattern = re.compile(r'Upgrading\s(?P<package>.*?)\sfrom\s(?P<oldVersion>.*?)\sto\s(?P<version>.*?)\son\s(?P<target>.*?)')
for line in salt.utils.itertools.split(output, '\n'):
match = install_pattern.match(line)
if match is None:
match = upgrade_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = match.group('version')
return reported_pkgs
def _execute_install_command(cmd, parse_output, errors, parsed_packages):
'''
Executes a command for the install operation.
If the command fails, its error output will be appended to the errors list.
If the command succeeds and parse_output is true, updated packages will be appended
to the parsed_packages dictionary.
'''
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors.append(out['stderr'])
else:
errors.append(out['stdout'])
elif parse_output:
parsed_packages.update(_parse_reported_packages_from_install_output(out['stdout']))
def install(name=None,
refresh=False,
pkgs=None,
sources=None,
reinstall=False,
**kwargs):
'''
Install the passed package, add refresh=True to update the opkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionadded:: 2017.7.0
reinstall : False
Specifying reinstall=True will use ``opkg install --force-reinstall``
rather than simply ``opkg install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``opkg
install --force-reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2017.7.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of IPK packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
install_recommends
Whether to install the packages marked as recommended. Default is True.
only_upgrade
Only upgrade the packages (disallow downgrades), if they are already
installed. Default is False.
.. versionadded:: 2017.7.0
always_restart_services
Whether to restart services even if a reboot is required. Default is True.
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
refreshdb = salt.utils.data.is_true(refresh)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
cmd_prefix = ['opkg', 'install']
to_install = []
to_reinstall = []
to_downgrade = []
_append_noaction_if_testmode(cmd_prefix, **kwargs)
if not pkg_params:
return {}
elif pkg_type == 'file':
if reinstall:
cmd_prefix.append('--force-reinstall')
if not kwargs.get('only_upgrade', False):
cmd_prefix.append('--force-downgrade')
to_install.extend(pkg_params)
elif pkg_type == 'repository':
if not kwargs.get('install_recommends', True):
cmd_prefix.append('--no-install-recommends')
for pkgname, pkgversion in six.iteritems(pkg_params):
if (name and pkgs is None and kwargs.get('version') and
len(pkg_params) == 1):
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
version_num = pkgversion
if version_num is None:
# Don't allow downgrades if the version
# number is not specified.
if reinstall and pkgname in old:
to_reinstall.append(pkgname)
else:
to_install.append(pkgname)
else:
pkgstr = '{0}={1}'.format(pkgname, version_num)
cver = old.get(pkgname, '')
if reinstall and cver and salt.utils.versions.compare(
ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall.append(pkgstr)
elif not cver or salt.utils.versions.compare(
ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
to_install.append(pkgstr)
else:
if not kwargs.get('only_upgrade', False):
to_downgrade.append(pkgstr)
else:
# This should cause the command to fail.
to_install.append(pkgstr)
cmds = _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall)
if not cmds:
return {}
if refreshdb:
refresh_db()
errors = []
is_testmode = _is_testmode(**kwargs)
test_packages = {}
for cmd in cmds:
_execute_install_command(cmd, is_testmode, errors, test_packages)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if is_testmode:
new = copy.deepcopy(new)
new.update(test_packages)
ret = salt.utils.data.compare_dicts(old, new)
if pkg_type == 'file' and reinstall:
# For file-based packages, prepare 'to_reinstall' to have a list
# of all the package names that may have been reinstalled.
# This way, we could include reinstalled packages in 'ret'.
for pkgfile in to_install:
# Convert from file name to package name.
cmd = ['opkg', 'info', pkgfile]
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] == 0:
# Just need the package name.
pkginfo_dict = _process_info_installed_output(
out['stdout'], []
)
if pkginfo_dict:
to_reinstall.append(list(pkginfo_dict.keys())[0])
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def _parse_reported_packages_from_remove_output(output):
'''
Parses the output of "opkg remove" to determine what packages would have been
removed by an operation run with the --noaction flag.
We are looking for lines like
Removing <package> (<version>) from <Target>...
'''
reported_pkgs = {}
remove_pattern = re.compile(r'Removing\s(?P<package>.*?)\s\((?P<version>.*?)\)\sfrom\s(?P<target>.*?)...')
for line in salt.utils.itertools.split(output, '\n'):
match = remove_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = ''
return reported_pkgs
def remove(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Remove packages using ``opkg remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
remove_dependencies
Remove package and all dependencies
.. versionadded:: 2019.2.0
auto_remove_deps
Remove packages that were installed automatically to satisfy dependencies
.. versionadded:: 2019.2.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
salt '*' pkg.remove pkgs='["foo", "bar"]' remove_dependencies=True auto_remove_deps=True
'''
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 {}
cmd = ['opkg', 'remove']
_append_noaction_if_testmode(cmd, **kwargs)
if kwargs.get('remove_dependencies', False):
cmd.append('--force-removal-of-dependent-packages')
if kwargs.get('auto_remove_deps', False):
cmd.append('--autoremove')
cmd.extend(targets)
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors = [out['stderr']]
else:
errors = [out['stdout']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if _is_testmode(**kwargs):
reportedPkgs = _parse_reported_packages_from_remove_output(out['stdout'])
new = {k: v for k, v in new.items() if k not in reportedPkgs}
ret = salt.utils.data.compare_dicts(old, new)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def purge(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Package purges are not supported by opkg, this function is identical to
:mod:`pkg.remove <salt.modules.opkg.remove>`.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name, pkgs=pkgs)
def upgrade(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
Upgrades all packages via ``opkg upgrade``
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
errors = []
if salt.utils.data.is_true(refresh):
refresh_db()
old = list_pkgs()
cmd = ['opkg', 'upgrade']
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
errors.append(result)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif state == 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret['comment'] = ('Package {0} is set not to be held.'
.format(target))
else:
result = _set_state(target, 'ok')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def _get_state(pkg):
'''
View package state from the opkg database
Return the state of pkg
'''
cmd = ['opkg', 'status']
cmd.append(pkg)
out = __salt__['cmd.run'](cmd, python_shell=False)
state_flag = ''
for line in salt.utils.itertools.split(out, '\n'):
if line.startswith('Status'):
_status, _state_want, state_flag, _state_status = line.split()
return state_flag
def _set_state(pkg, state):
'''
Change package state on the opkg database
The state can be any of:
- hold
- noprune
- user
- ok
- installed
- unpacked
This command is commonly used to mark a specific package to be held from
being upgraded, that is, to be kept at a certain version.
Returns a dict containing the package name, and the new and old
versions.
'''
ret = {}
valid_states = ('hold', 'noprune', 'user', 'ok', 'installed', 'unpacked')
if state not in valid_states:
raise SaltInvocationError('Invalid state: {0}'.format(state))
oldstate = _get_state(pkg)
cmd = ['opkg', 'flag']
cmd.append(state)
cmd.append(pkg)
_out = __salt__['cmd.run'](cmd, python_shell=False)
# Missing return value check due to opkg issue 160
ret[pkg] = {'old': oldstate,
'new': state}
return ret
def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
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
cmd = ['opkg', 'list-installed']
ret = {}
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
# This is a continuation of package description
if not line or line[0] == ' ':
continue
# This contains package name, version, and description.
# Extract the first two.
pkg_name, pkg_version = line.split(' - ', 2)[:2]
__salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version)
__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 list_upgrades(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
List all available package upgrades.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
ret = {}
if salt.utils.data.is_true(refresh):
refresh_db()
cmd = ['opkg', 'list-upgradable']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
if 'stdout' in call:
comment += call['stdout']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
name, _oldversion, newversion = line.split(' - ')
ret[name] = newversion
return ret
def _convert_to_standard_attr(attr):
'''
Helper function for _process_info_installed_output()
Converts an opkg attribute name to a standard attribute
name which is used across 'pkg' modules.
'''
ret_attr = ATTR_MAP.get(attr, None)
if ret_attr is None:
# All others convert to lowercase
return attr.lower()
return ret_attr
def _process_info_installed_output(out, filter_attrs):
'''
Helper function for info_installed()
Processes stdout output from a single invocation of
'opkg status'.
'''
ret = {}
name = None
attrs = {}
attr = None
for line in salt.utils.itertools.split(out, '\n'):
if line and line[0] == ' ':
# This is a continuation of the last attr
if filter_attrs is None or attr in filter_attrs:
line = line.strip()
if attrs[attr]:
# If attr is empty, don't add leading newline
attrs[attr] += '\n'
attrs[attr] += line
continue
line = line.strip()
if not line:
# Separator between different packages
if name:
ret[name] = attrs
name = None
attrs = {}
attr = None
continue
key, value = line.split(':', 1)
value = value.lstrip()
attr = _convert_to_standard_attr(key)
if attr == 'name':
name = value
elif filter_attrs is None or attr in filter_attrs:
attrs[attr] = value
if name:
ret[name] = attrs
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
.. versionadded:: 2017.7.0
:param names:
Names of the packages to get information about. If none are specified,
will return information for all installed packages.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
arch, conffiles, conflicts, depends, description, filename, group,
install_date_time_t, md5sum, packager, provides, recommends,
replaces, size, source, suggests, url, version
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed
salt '*' pkg.info_installed attr=version,packager
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> attr=version,packager
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,packager
'''
attr = kwargs.pop('attr', None)
if attr is None:
filter_attrs = None
elif isinstance(attr, six.string_types):
filter_attrs = set(attr.split(','))
else:
filter_attrs = set(attr)
ret = {}
if names:
# Specific list of names of installed packages
for name in names:
cmd = ['opkg', 'status', name]
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
else:
# All installed packages
cmd = ['opkg', 'status']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
return ret
def upgrade_available(name, **kwargs): # pylint: disable=unused-argument
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs): # pylint: disable=unused-argument
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2016.3.4
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0' '0.2.4.1-0'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] if ignore_epoch else six.text_type(x)
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
output = __salt__['cmd.run_stdout'](['opkg', '--version'],
output_loglevel='trace',
python_shell=False)
opkg_version = output.split(' ')[2].strip()
if salt.utils.versions.LooseVersion(opkg_version) >= \
salt.utils.versions.LooseVersion('0.3.4'):
cmd_compare = ['opkg', 'compare-versions']
elif salt.utils.path.which('opkg-compare-versions'):
cmd_compare = ['opkg-compare-versions']
else:
log.warning('Unable to find a compare-versions utility installed. Either upgrade opkg to '
'version > 0.3.4 (preferred) or install the older opkg-compare-versions script.')
return None
for oper, ret in (("<<", -1), ("=", 0), (">>", 1)):
cmd = cmd_compare[:]
cmd.append(_cmd_quote(pkg1))
cmd.append(oper)
cmd.append(_cmd_quote(pkg2))
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
ignore_retcode=True,
python_shell=False)
if retcode == 0:
return ret
return None
def _set_repo_option(repo, option):
'''
Set the option to repo
'''
if not option:
return
opt = option.split('=')
if len(opt) != 2:
return
if opt[0] == 'trusted':
repo['trusted'] = opt[1] == 'yes'
else:
repo[opt[0]] = opt[1]
def _set_repo_options(repo, options):
'''
Set the options to the repo.
'''
delimiters = "[", "]"
pattern = '|'.join(map(re.escape, delimiters))
for option in options:
splitted = re.split(pattern, option)
for opt in splitted:
_set_repo_option(repo, opt)
def _create_repo(line, filename):
'''
Create repo
'''
repo = {}
if line.startswith('#'):
repo['enabled'] = False
line = line[1:]
else:
repo['enabled'] = True
cols = salt.utils.args.shlex_split(line.strip())
repo['compressed'] = not cols[0] in 'src'
repo['name'] = cols[1]
repo['uri'] = cols[2]
repo['file'] = os.path.join(OPKG_CONFDIR, filename)
if len(cols) > 3:
_set_repo_options(repo, cols[3:])
return repo
def _read_repos(conf_file, repos, filename, regex):
'''
Read repos from configuration file
'''
for line in conf_file:
line = salt.utils.stringutils.to_unicode(line)
if not regex.search(line):
continue
repo = _create_repo(line, filename)
# do not store duplicated uri's
if repo['uri'] not in repos:
repos[repo['uri']] = [repo]
def list_repos(**kwargs): # pylint: disable=unused-argument
'''
Lists all repos on ``/etc/opkg/*.conf``
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos = {}
regex = re.compile(REPO_REGEXP)
for filename in os.listdir(OPKG_CONFDIR):
if not filename.endswith(".conf"):
continue
with salt.utils.files.fopen(os.path.join(OPKG_CONFDIR, filename)) as conf_file:
_read_repos(conf_file, repos, filename, regex)
return repos
def get_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Display a repo from the ``/etc/opkg/*.conf``
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo repo
'''
repos = list_repos()
if repos:
for source in six.itervalues(repos):
for sub in source:
if sub['name'] == repo:
return sub
return {}
def _del_repo_from_file(repo, filepath):
'''
Remove a repo from filepath
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
regex = re.compile(REPO_REGEXP)
for line in fhandle:
line = salt.utils.stringutils.to_unicode(line)
if regex.search(line):
if line.startswith('#'):
line = line[1:]
cols = salt.utils.args.shlex_split(line.strip())
if repo != cols[1]:
output.append(salt.utils.stringutils.to_str(line))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def _set_trusted_option_if_needed(repostr, trusted):
'''
Set trusted option to repo if needed
'''
if trusted is True:
repostr += ' [trusted=yes]'
elif trusted is False:
repostr += ' [trusted=no]'
return repostr
def _add_new_repo(repo, properties):
'''
Add a new repo entry
'''
repostr = '# ' if not properties.get('enabled') else ''
repostr += 'src/gz ' if properties.get('compressed') else 'src '
if ' ' in repo:
repostr += '"' + repo + '" '
else:
repostr += repo + ' '
repostr += properties.get('uri')
repostr = _set_trusted_option_if_needed(repostr, properties.get('trusted'))
repostr += '\n'
conffile = os.path.join(OPKG_CONFDIR, repo + '.conf')
with salt.utils.files.fopen(conffile, 'a') as fhandle:
fhandle.write(salt.utils.stringutils.to_str(repostr))
def _mod_repo_in_file(repo, repostr, filepath):
'''
Replace a repo entry in filepath with repostr
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
for line in fhandle:
cols = salt.utils.args.shlex_split(
salt.utils.stringutils.to_unicode(line).strip()
)
if repo not in cols:
output.append(line)
else:
output.append(salt.utils.stringutils.to_str(repostr + '\n'))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def del_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Delete a repo from ``/etc/opkg/*.conf``
If the file does not contain any other repo configuration, the file itself
will be deleted.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo repo
'''
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
repos = list_repos()
if repos:
deleted_from = dict()
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
deleted_from[source['file']] = 0
_del_repo_from_file(repo, source['file'])
if deleted_from:
ret = ''
for repository in repos:
source = repos[repository][0]
if source['file'] in deleted_from:
deleted_from[source['file']] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 1 and os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.\n')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
if refresh:
refresh_db()
return ret
return "Repo {0} doesn't exist in the opkg repo lists".format(repo)
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as uri is defined.
The following options are available to modify a repo definition:
repo
alias by which opkg refers to the repo.
uri
the URI to the repo.
compressed
defines (True or False) if the index file is compressed
enabled
enable or disable (True or False) repository
but do not remove if disabled.
refresh
enable or disable (True or False) auto-refresh of the repositories
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo repo uri=http://new/uri
salt '*' pkg.mod_repo repo enabled=False
'''
repos = list_repos()
found = False
uri = ''
if 'uri' in kwargs:
uri = kwargs['uri']
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
found = True
repostr = ''
if 'enabled' in kwargs and not kwargs['enabled']:
repostr += '# '
if 'compressed' in kwargs:
repostr += 'src/gz ' if kwargs['compressed'] else 'src'
else:
repostr += 'src/gz' if source['compressed'] else 'src'
repo_alias = kwargs['alias'] if 'alias' in kwargs else repo
if ' ' in repo_alias:
repostr += ' "{0}"'.format(repo_alias)
else:
repostr += ' {0}'.format(repo_alias)
repostr += ' {0}'.format(kwargs['uri'] if 'uri' in kwargs else source['uri'])
trusted = kwargs.get('trusted')
repostr = _set_trusted_option_if_needed(repostr, trusted) if trusted is not None else \
_set_trusted_option_if_needed(repostr, source.get('trusted'))
_mod_repo_in_file(repo, repostr, source['file'])
elif uri and source['uri'] == uri:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(uri, source['name']))
if not found:
# Need to add a new repo
if 'uri' not in kwargs:
raise CommandExecutionError(
'Repository \'{0}\' not found and no URI passed to create one.'.format(repo))
properties = {'uri': kwargs['uri']}
# If compressed is not defined, assume True
properties['compressed'] = kwargs['compressed'] if 'compressed' in kwargs else True
# If enabled is not defined, assume True
properties['enabled'] = kwargs['enabled'] if 'enabled' in kwargs else True
properties['trusted'] = kwargs.get('trusted')
_add_new_repo(repo, properties)
if 'refresh' in kwargs:
refresh_db()
def file_list(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
output = file_dict(*packages)
files = []
for package in list(output['packages'].values()):
files.extend(package)
return {'errors': output['errors'], 'files': files}
def file_dict(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
errors = []
ret = {}
cmd_files = ['opkg', 'files']
if not packages:
packages = list(list_pkgs().keys())
for package in packages:
files = []
cmd = cmd_files[:]
cmd.append(package)
out = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
for line in out['stdout'].splitlines():
if line.startswith('/'):
files.append(line)
elif line.startswith(' * '):
errors.append(line[3:])
break
else:
continue
if files:
ret[package] = files
return {'errors': errors, 'packages': ret}
def owner(*paths, **kwargs): # pylint: disable=unused-argument
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.opkg.version`, if a single
path is passed, a string will be returned, and if multiple paths are passed,
a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
cmd_search = ['opkg', 'search']
for path in paths:
cmd = cmd_search[:]
cmd.append(path)
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
if output:
ret[path] = output.split(' - ')[0].strip()
else:
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def version_clean(version):
'''
Clean the version string removing extra data.
There's nothing do to here for nipkg.py, therefore it will always
return the given version.
'''
return version
def check_extra_requirements(pkgname, pkgver):
'''
Check if the installed package already has the given requirements.
There's nothing do to here for nipkg.py, therefore it will always
return True.
'''
return True
|
saltstack/salt
|
salt/modules/opkg.py
|
_get_state
|
python
|
def _get_state(pkg):
'''
View package state from the opkg database
Return the state of pkg
'''
cmd = ['opkg', 'status']
cmd.append(pkg)
out = __salt__['cmd.run'](cmd, python_shell=False)
state_flag = ''
for line in salt.utils.itertools.split(out, '\n'):
if line.startswith('Status'):
_status, _state_want, state_flag, _state_status = line.split()
return state_flag
|
View package state from the opkg database
Return the state of pkg
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/opkg.py#L919-L933
|
[
"def split(orig, sep=None):\n '''\n Generator function for iterating through large strings, particularly useful\n as a replacement for str.splitlines().\n\n See http://stackoverflow.com/a/3865367\n '''\n exp = re.compile(r'\\s+' if sep is None else re.escape(sep))\n pos = 0\n length = len(orig)\n while True:\n match = exp.search(orig, pos)\n if not match:\n if pos < length or sep is not None:\n val = orig[pos:]\n if val:\n # Only yield a value if the slice was not an empty string,\n # because if it is then we've reached the end. This keeps\n # us from yielding an extra blank value at the end.\n yield val\n break\n if pos < match.start() or sep is not None:\n yield orig[pos:match.start()]\n pos = match.end()\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Opkg
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
.. versionadded: 2016.3.0
.. note::
For version comparison support on opkg < 0.3.4, the ``opkg-utils`` package
must be installed.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import os
import re
import logging
import errno
# Import salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.itertools
import salt.utils.path
import salt.utils.pkg
import salt.utils.stringutils
import salt.utils.versions
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import shlex_quote as _cmd_quote # pylint: disable=import-error
from salt.ext.six.moves import map # pylint: disable=import-error,redefined-builtin
REPO_REGEXP = r'^#?\s*(src|src/gz)\s+([^\s<>]+|"[^<>]+")\s+[^\s<>]+'
OPKG_CONFDIR = '/etc/opkg'
ATTR_MAP = {
'Architecture': 'arch',
'Homepage': 'url',
'Installed-Time': 'install_date_time_t',
'Maintainer': 'packager',
'Package': 'name',
'Section': 'group'
}
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
NILRT_RESTARTCHECK_STATE_PATH = '/var/lib/salt/restartcheck_state'
def _update_nilrt_restart_state():
'''
NILRT systems determine whether to reboot after various package operations
including but not limited to kernel module installs/removals by checking
specific file md5sums & timestamps. These files are touched/modified by
the post-install/post-remove functions of their respective packages.
The opkg module uses this function to store/update those file timestamps
and checksums to be used later by the restartcheck module.
'''
__salt__['cmd.shell']('stat -c %Y /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.timestamp'
.format(NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.md5sum'
.format(NILRT_RESTARTCHECK_STATE_PATH))
# We can't assume nisysapi.ini always exists like modules.dep
nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'
if os.path.exists(nisysapi_path):
__salt__['cmd.shell']('stat -c %Y {0} >{1}/nisysapi.ini.timestamp'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0} >{1}/nisysapi.ini.md5sum'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
# Expert plugin files get added to a conf.d dir, so keep track of the total
# no. of files, their timestamps and content hashes
nisysapi_conf_d_path = "/usr/lib/{0}/nisysapi/conf.d/experts/".format(
'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'
)
if os.path.exists(nisysapi_conf_d_path):
with salt.utils.files.fopen('{0}/sysapi.conf.d.count'.format(
NILRT_RESTARTCHECK_STATE_PATH), 'w') as fcount:
fcount.write(str(len(os.listdir(nisysapi_conf_d_path))))
for fexpert in os.listdir(nisysapi_conf_d_path):
__salt__['cmd.shell']('stat -c %Y {0}/{1} >{2}/{1}.timestamp'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0}/{1} >{2}/{1}.md5sum'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
def _get_restartcheck_result(errors):
'''
Return restartcheck result and append errors (if any) to ``errors``
'''
rs_result = __salt__['restartcheck.restartcheck'](verbose=False)
if isinstance(rs_result, dict) and 'comment' in rs_result:
errors.append(rs_result['comment'])
return rs_result
def _process_restartcheck_result(rs_result, **kwargs):
'''
Check restartcheck output to see if system/service restarts were requested
and take appropriate action.
'''
if 'No packages seem to need to be restarted' in rs_result:
return
reboot_required = False
for rstr in rs_result:
if 'System restart required' in rstr:
_update_nilrt_restart_state()
__salt__['system.set_reboot_required_witnessed']()
reboot_required = True
if kwargs.get('always_restart_services', True) or not reboot_required:
for rstr in rs_result:
if 'System restart required' not in rstr:
service = os.path.join('/etc/init.d', rstr)
if os.path.exists(service):
__salt__['cmd.run']([service, 'restart'])
def __virtual__():
'''
Confirm this module is on a nilrt based system
'''
if __grains__.get('os_family') == 'NILinuxRT':
try:
os.makedirs(NILRT_RESTARTCHECK_STATE_PATH)
except OSError as exc:
if exc.errno != errno.EEXIST:
return False, 'Error creating {0} (-{1}): {2}'.format(
NILRT_RESTARTCHECK_STATE_PATH,
exc.errno,
exc.strerror)
# populate state dir if empty
if not os.listdir(NILRT_RESTARTCHECK_STATE_PATH):
_update_nilrt_restart_state()
return __virtualname__
if os.path.isdir(OPKG_CONFDIR):
return __virtualname__
return False, "Module opkg only works on OpenEmbedded based systems"
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
if not names:
return ''
ret = {}
for name in names:
ret[name] = ''
# Refresh before looking for the latest version available
if refresh:
refresh_db()
cmd = ['opkg', 'list-upgradable']
out = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
try:
name, _oldversion, newversion = line.split(' - ')
if name in names:
ret[name] = newversion
except ValueError:
pass
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = latest_version
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(failhard=False, **kwargs): # pylint: disable=unused-argument
'''
Updates the opkg database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
failhard
If False, return results of failed lines as ``False`` for the package
database that encountered the error.
If True, raise an error with a list of the package databases that
encountered errors.
.. versionadded:: 2018.3.0
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
error_repos = []
cmd = ['opkg', 'update']
# opkg returns a non-zero retcode when there is a failure to refresh
# from one or more repos. Due to this, ignore the retcode.
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True,
redirect_stderr=True)
out = call['stdout']
prev_line = ''
for line in salt.utils.itertools.split(out, '\n'):
if 'Inflating' in line:
key = line.strip().split()[1][:-1]
ret[key] = True
elif 'Updated source' in line:
# Use the previous line.
key = prev_line.strip().split()[1][:-1]
ret[key] = True
elif 'Failed to download' in line:
key = line.strip().split()[5].split(',')[0]
ret[key] = False
error_repos.append(key)
prev_line = line
if failhard and error_repos:
raise CommandExecutionError(
'Error getting repos: {0}'.format(', '.join(error_repos))
)
# On a non-zero exit code where no failed repos were found, raise an
# exception because this appears to be a different kind of error.
if call['retcode'] != 0 and not error_repos:
raise CommandExecutionError(out)
return ret
def _is_testmode(**kwargs):
'''
Returns whether a test mode (noaction) operation was requested.
'''
return bool(kwargs.get('test') or __opts__.get('test'))
def _append_noaction_if_testmode(cmd, **kwargs):
'''
Adds the --noaction flag to the command if it's running in the test mode.
'''
if _is_testmode(**kwargs):
cmd.append('--noaction')
def _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall):
'''
Builds a list of install commands to be executed in sequence in order to process
each of the to_install, to_downgrade, and to_reinstall lists.
'''
cmds = []
if to_install:
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(to_install)
cmds.append(cmd)
if to_downgrade:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-downgrade')
cmd.extend(to_downgrade)
cmds.append(cmd)
if to_reinstall:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-reinstall')
cmd.extend(to_reinstall)
cmds.append(cmd)
return cmds
def _parse_reported_packages_from_install_output(output):
'''
Parses the output of "opkg install" to determine what packages would have been
installed by an operation run with the --noaction flag.
We are looking for lines like:
Installing <package> (<version>) on <target>
or
Upgrading <package> from <oldVersion> to <version> on root
'''
reported_pkgs = {}
install_pattern = re.compile(r'Installing\s(?P<package>.*?)\s\((?P<version>.*?)\)\son\s(?P<target>.*?)')
upgrade_pattern = re.compile(r'Upgrading\s(?P<package>.*?)\sfrom\s(?P<oldVersion>.*?)\sto\s(?P<version>.*?)\son\s(?P<target>.*?)')
for line in salt.utils.itertools.split(output, '\n'):
match = install_pattern.match(line)
if match is None:
match = upgrade_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = match.group('version')
return reported_pkgs
def _execute_install_command(cmd, parse_output, errors, parsed_packages):
'''
Executes a command for the install operation.
If the command fails, its error output will be appended to the errors list.
If the command succeeds and parse_output is true, updated packages will be appended
to the parsed_packages dictionary.
'''
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors.append(out['stderr'])
else:
errors.append(out['stdout'])
elif parse_output:
parsed_packages.update(_parse_reported_packages_from_install_output(out['stdout']))
def install(name=None,
refresh=False,
pkgs=None,
sources=None,
reinstall=False,
**kwargs):
'''
Install the passed package, add refresh=True to update the opkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionadded:: 2017.7.0
reinstall : False
Specifying reinstall=True will use ``opkg install --force-reinstall``
rather than simply ``opkg install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``opkg
install --force-reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2017.7.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of IPK packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
install_recommends
Whether to install the packages marked as recommended. Default is True.
only_upgrade
Only upgrade the packages (disallow downgrades), if they are already
installed. Default is False.
.. versionadded:: 2017.7.0
always_restart_services
Whether to restart services even if a reboot is required. Default is True.
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
refreshdb = salt.utils.data.is_true(refresh)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
cmd_prefix = ['opkg', 'install']
to_install = []
to_reinstall = []
to_downgrade = []
_append_noaction_if_testmode(cmd_prefix, **kwargs)
if not pkg_params:
return {}
elif pkg_type == 'file':
if reinstall:
cmd_prefix.append('--force-reinstall')
if not kwargs.get('only_upgrade', False):
cmd_prefix.append('--force-downgrade')
to_install.extend(pkg_params)
elif pkg_type == 'repository':
if not kwargs.get('install_recommends', True):
cmd_prefix.append('--no-install-recommends')
for pkgname, pkgversion in six.iteritems(pkg_params):
if (name and pkgs is None and kwargs.get('version') and
len(pkg_params) == 1):
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
version_num = pkgversion
if version_num is None:
# Don't allow downgrades if the version
# number is not specified.
if reinstall and pkgname in old:
to_reinstall.append(pkgname)
else:
to_install.append(pkgname)
else:
pkgstr = '{0}={1}'.format(pkgname, version_num)
cver = old.get(pkgname, '')
if reinstall and cver and salt.utils.versions.compare(
ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall.append(pkgstr)
elif not cver or salt.utils.versions.compare(
ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
to_install.append(pkgstr)
else:
if not kwargs.get('only_upgrade', False):
to_downgrade.append(pkgstr)
else:
# This should cause the command to fail.
to_install.append(pkgstr)
cmds = _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall)
if not cmds:
return {}
if refreshdb:
refresh_db()
errors = []
is_testmode = _is_testmode(**kwargs)
test_packages = {}
for cmd in cmds:
_execute_install_command(cmd, is_testmode, errors, test_packages)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if is_testmode:
new = copy.deepcopy(new)
new.update(test_packages)
ret = salt.utils.data.compare_dicts(old, new)
if pkg_type == 'file' and reinstall:
# For file-based packages, prepare 'to_reinstall' to have a list
# of all the package names that may have been reinstalled.
# This way, we could include reinstalled packages in 'ret'.
for pkgfile in to_install:
# Convert from file name to package name.
cmd = ['opkg', 'info', pkgfile]
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] == 0:
# Just need the package name.
pkginfo_dict = _process_info_installed_output(
out['stdout'], []
)
if pkginfo_dict:
to_reinstall.append(list(pkginfo_dict.keys())[0])
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def _parse_reported_packages_from_remove_output(output):
'''
Parses the output of "opkg remove" to determine what packages would have been
removed by an operation run with the --noaction flag.
We are looking for lines like
Removing <package> (<version>) from <Target>...
'''
reported_pkgs = {}
remove_pattern = re.compile(r'Removing\s(?P<package>.*?)\s\((?P<version>.*?)\)\sfrom\s(?P<target>.*?)...')
for line in salt.utils.itertools.split(output, '\n'):
match = remove_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = ''
return reported_pkgs
def remove(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Remove packages using ``opkg remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
remove_dependencies
Remove package and all dependencies
.. versionadded:: 2019.2.0
auto_remove_deps
Remove packages that were installed automatically to satisfy dependencies
.. versionadded:: 2019.2.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
salt '*' pkg.remove pkgs='["foo", "bar"]' remove_dependencies=True auto_remove_deps=True
'''
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 {}
cmd = ['opkg', 'remove']
_append_noaction_if_testmode(cmd, **kwargs)
if kwargs.get('remove_dependencies', False):
cmd.append('--force-removal-of-dependent-packages')
if kwargs.get('auto_remove_deps', False):
cmd.append('--autoremove')
cmd.extend(targets)
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors = [out['stderr']]
else:
errors = [out['stdout']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if _is_testmode(**kwargs):
reportedPkgs = _parse_reported_packages_from_remove_output(out['stdout'])
new = {k: v for k, v in new.items() if k not in reportedPkgs}
ret = salt.utils.data.compare_dicts(old, new)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def purge(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Package purges are not supported by opkg, this function is identical to
:mod:`pkg.remove <salt.modules.opkg.remove>`.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name, pkgs=pkgs)
def upgrade(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
Upgrades all packages via ``opkg upgrade``
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
errors = []
if salt.utils.data.is_true(refresh):
refresh_db()
old = list_pkgs()
cmd = ['opkg', 'upgrade']
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
errors.append(result)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif state != 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = _set_state(target, 'hold')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif state == 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret['comment'] = ('Package {0} is set not to be held.'
.format(target))
else:
result = _set_state(target, 'ok')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def _set_state(pkg, state):
'''
Change package state on the opkg database
The state can be any of:
- hold
- noprune
- user
- ok
- installed
- unpacked
This command is commonly used to mark a specific package to be held from
being upgraded, that is, to be kept at a certain version.
Returns a dict containing the package name, and the new and old
versions.
'''
ret = {}
valid_states = ('hold', 'noprune', 'user', 'ok', 'installed', 'unpacked')
if state not in valid_states:
raise SaltInvocationError('Invalid state: {0}'.format(state))
oldstate = _get_state(pkg)
cmd = ['opkg', 'flag']
cmd.append(state)
cmd.append(pkg)
_out = __salt__['cmd.run'](cmd, python_shell=False)
# Missing return value check due to opkg issue 160
ret[pkg] = {'old': oldstate,
'new': state}
return ret
def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
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
cmd = ['opkg', 'list-installed']
ret = {}
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
# This is a continuation of package description
if not line or line[0] == ' ':
continue
# This contains package name, version, and description.
# Extract the first two.
pkg_name, pkg_version = line.split(' - ', 2)[:2]
__salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version)
__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 list_upgrades(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
List all available package upgrades.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
ret = {}
if salt.utils.data.is_true(refresh):
refresh_db()
cmd = ['opkg', 'list-upgradable']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
if 'stdout' in call:
comment += call['stdout']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
name, _oldversion, newversion = line.split(' - ')
ret[name] = newversion
return ret
def _convert_to_standard_attr(attr):
'''
Helper function for _process_info_installed_output()
Converts an opkg attribute name to a standard attribute
name which is used across 'pkg' modules.
'''
ret_attr = ATTR_MAP.get(attr, None)
if ret_attr is None:
# All others convert to lowercase
return attr.lower()
return ret_attr
def _process_info_installed_output(out, filter_attrs):
'''
Helper function for info_installed()
Processes stdout output from a single invocation of
'opkg status'.
'''
ret = {}
name = None
attrs = {}
attr = None
for line in salt.utils.itertools.split(out, '\n'):
if line and line[0] == ' ':
# This is a continuation of the last attr
if filter_attrs is None or attr in filter_attrs:
line = line.strip()
if attrs[attr]:
# If attr is empty, don't add leading newline
attrs[attr] += '\n'
attrs[attr] += line
continue
line = line.strip()
if not line:
# Separator between different packages
if name:
ret[name] = attrs
name = None
attrs = {}
attr = None
continue
key, value = line.split(':', 1)
value = value.lstrip()
attr = _convert_to_standard_attr(key)
if attr == 'name':
name = value
elif filter_attrs is None or attr in filter_attrs:
attrs[attr] = value
if name:
ret[name] = attrs
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
.. versionadded:: 2017.7.0
:param names:
Names of the packages to get information about. If none are specified,
will return information for all installed packages.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
arch, conffiles, conflicts, depends, description, filename, group,
install_date_time_t, md5sum, packager, provides, recommends,
replaces, size, source, suggests, url, version
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed
salt '*' pkg.info_installed attr=version,packager
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> attr=version,packager
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,packager
'''
attr = kwargs.pop('attr', None)
if attr is None:
filter_attrs = None
elif isinstance(attr, six.string_types):
filter_attrs = set(attr.split(','))
else:
filter_attrs = set(attr)
ret = {}
if names:
# Specific list of names of installed packages
for name in names:
cmd = ['opkg', 'status', name]
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
else:
# All installed packages
cmd = ['opkg', 'status']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
return ret
def upgrade_available(name, **kwargs): # pylint: disable=unused-argument
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs): # pylint: disable=unused-argument
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2016.3.4
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0' '0.2.4.1-0'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] if ignore_epoch else six.text_type(x)
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
output = __salt__['cmd.run_stdout'](['opkg', '--version'],
output_loglevel='trace',
python_shell=False)
opkg_version = output.split(' ')[2].strip()
if salt.utils.versions.LooseVersion(opkg_version) >= \
salt.utils.versions.LooseVersion('0.3.4'):
cmd_compare = ['opkg', 'compare-versions']
elif salt.utils.path.which('opkg-compare-versions'):
cmd_compare = ['opkg-compare-versions']
else:
log.warning('Unable to find a compare-versions utility installed. Either upgrade opkg to '
'version > 0.3.4 (preferred) or install the older opkg-compare-versions script.')
return None
for oper, ret in (("<<", -1), ("=", 0), (">>", 1)):
cmd = cmd_compare[:]
cmd.append(_cmd_quote(pkg1))
cmd.append(oper)
cmd.append(_cmd_quote(pkg2))
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
ignore_retcode=True,
python_shell=False)
if retcode == 0:
return ret
return None
def _set_repo_option(repo, option):
'''
Set the option to repo
'''
if not option:
return
opt = option.split('=')
if len(opt) != 2:
return
if opt[0] == 'trusted':
repo['trusted'] = opt[1] == 'yes'
else:
repo[opt[0]] = opt[1]
def _set_repo_options(repo, options):
'''
Set the options to the repo.
'''
delimiters = "[", "]"
pattern = '|'.join(map(re.escape, delimiters))
for option in options:
splitted = re.split(pattern, option)
for opt in splitted:
_set_repo_option(repo, opt)
def _create_repo(line, filename):
'''
Create repo
'''
repo = {}
if line.startswith('#'):
repo['enabled'] = False
line = line[1:]
else:
repo['enabled'] = True
cols = salt.utils.args.shlex_split(line.strip())
repo['compressed'] = not cols[0] in 'src'
repo['name'] = cols[1]
repo['uri'] = cols[2]
repo['file'] = os.path.join(OPKG_CONFDIR, filename)
if len(cols) > 3:
_set_repo_options(repo, cols[3:])
return repo
def _read_repos(conf_file, repos, filename, regex):
'''
Read repos from configuration file
'''
for line in conf_file:
line = salt.utils.stringutils.to_unicode(line)
if not regex.search(line):
continue
repo = _create_repo(line, filename)
# do not store duplicated uri's
if repo['uri'] not in repos:
repos[repo['uri']] = [repo]
def list_repos(**kwargs): # pylint: disable=unused-argument
'''
Lists all repos on ``/etc/opkg/*.conf``
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos = {}
regex = re.compile(REPO_REGEXP)
for filename in os.listdir(OPKG_CONFDIR):
if not filename.endswith(".conf"):
continue
with salt.utils.files.fopen(os.path.join(OPKG_CONFDIR, filename)) as conf_file:
_read_repos(conf_file, repos, filename, regex)
return repos
def get_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Display a repo from the ``/etc/opkg/*.conf``
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo repo
'''
repos = list_repos()
if repos:
for source in six.itervalues(repos):
for sub in source:
if sub['name'] == repo:
return sub
return {}
def _del_repo_from_file(repo, filepath):
'''
Remove a repo from filepath
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
regex = re.compile(REPO_REGEXP)
for line in fhandle:
line = salt.utils.stringutils.to_unicode(line)
if regex.search(line):
if line.startswith('#'):
line = line[1:]
cols = salt.utils.args.shlex_split(line.strip())
if repo != cols[1]:
output.append(salt.utils.stringutils.to_str(line))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def _set_trusted_option_if_needed(repostr, trusted):
'''
Set trusted option to repo if needed
'''
if trusted is True:
repostr += ' [trusted=yes]'
elif trusted is False:
repostr += ' [trusted=no]'
return repostr
def _add_new_repo(repo, properties):
'''
Add a new repo entry
'''
repostr = '# ' if not properties.get('enabled') else ''
repostr += 'src/gz ' if properties.get('compressed') else 'src '
if ' ' in repo:
repostr += '"' + repo + '" '
else:
repostr += repo + ' '
repostr += properties.get('uri')
repostr = _set_trusted_option_if_needed(repostr, properties.get('trusted'))
repostr += '\n'
conffile = os.path.join(OPKG_CONFDIR, repo + '.conf')
with salt.utils.files.fopen(conffile, 'a') as fhandle:
fhandle.write(salt.utils.stringutils.to_str(repostr))
def _mod_repo_in_file(repo, repostr, filepath):
'''
Replace a repo entry in filepath with repostr
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
for line in fhandle:
cols = salt.utils.args.shlex_split(
salt.utils.stringutils.to_unicode(line).strip()
)
if repo not in cols:
output.append(line)
else:
output.append(salt.utils.stringutils.to_str(repostr + '\n'))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def del_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Delete a repo from ``/etc/opkg/*.conf``
If the file does not contain any other repo configuration, the file itself
will be deleted.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo repo
'''
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
repos = list_repos()
if repos:
deleted_from = dict()
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
deleted_from[source['file']] = 0
_del_repo_from_file(repo, source['file'])
if deleted_from:
ret = ''
for repository in repos:
source = repos[repository][0]
if source['file'] in deleted_from:
deleted_from[source['file']] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 1 and os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.\n')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
if refresh:
refresh_db()
return ret
return "Repo {0} doesn't exist in the opkg repo lists".format(repo)
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as uri is defined.
The following options are available to modify a repo definition:
repo
alias by which opkg refers to the repo.
uri
the URI to the repo.
compressed
defines (True or False) if the index file is compressed
enabled
enable or disable (True or False) repository
but do not remove if disabled.
refresh
enable or disable (True or False) auto-refresh of the repositories
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo repo uri=http://new/uri
salt '*' pkg.mod_repo repo enabled=False
'''
repos = list_repos()
found = False
uri = ''
if 'uri' in kwargs:
uri = kwargs['uri']
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
found = True
repostr = ''
if 'enabled' in kwargs and not kwargs['enabled']:
repostr += '# '
if 'compressed' in kwargs:
repostr += 'src/gz ' if kwargs['compressed'] else 'src'
else:
repostr += 'src/gz' if source['compressed'] else 'src'
repo_alias = kwargs['alias'] if 'alias' in kwargs else repo
if ' ' in repo_alias:
repostr += ' "{0}"'.format(repo_alias)
else:
repostr += ' {0}'.format(repo_alias)
repostr += ' {0}'.format(kwargs['uri'] if 'uri' in kwargs else source['uri'])
trusted = kwargs.get('trusted')
repostr = _set_trusted_option_if_needed(repostr, trusted) if trusted is not None else \
_set_trusted_option_if_needed(repostr, source.get('trusted'))
_mod_repo_in_file(repo, repostr, source['file'])
elif uri and source['uri'] == uri:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(uri, source['name']))
if not found:
# Need to add a new repo
if 'uri' not in kwargs:
raise CommandExecutionError(
'Repository \'{0}\' not found and no URI passed to create one.'.format(repo))
properties = {'uri': kwargs['uri']}
# If compressed is not defined, assume True
properties['compressed'] = kwargs['compressed'] if 'compressed' in kwargs else True
# If enabled is not defined, assume True
properties['enabled'] = kwargs['enabled'] if 'enabled' in kwargs else True
properties['trusted'] = kwargs.get('trusted')
_add_new_repo(repo, properties)
if 'refresh' in kwargs:
refresh_db()
def file_list(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
output = file_dict(*packages)
files = []
for package in list(output['packages'].values()):
files.extend(package)
return {'errors': output['errors'], 'files': files}
def file_dict(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
errors = []
ret = {}
cmd_files = ['opkg', 'files']
if not packages:
packages = list(list_pkgs().keys())
for package in packages:
files = []
cmd = cmd_files[:]
cmd.append(package)
out = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
for line in out['stdout'].splitlines():
if line.startswith('/'):
files.append(line)
elif line.startswith(' * '):
errors.append(line[3:])
break
else:
continue
if files:
ret[package] = files
return {'errors': errors, 'packages': ret}
def owner(*paths, **kwargs): # pylint: disable=unused-argument
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.opkg.version`, if a single
path is passed, a string will be returned, and if multiple paths are passed,
a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
cmd_search = ['opkg', 'search']
for path in paths:
cmd = cmd_search[:]
cmd.append(path)
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
if output:
ret[path] = output.split(' - ')[0].strip()
else:
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def version_clean(version):
'''
Clean the version string removing extra data.
There's nothing do to here for nipkg.py, therefore it will always
return the given version.
'''
return version
def check_extra_requirements(pkgname, pkgver):
'''
Check if the installed package already has the given requirements.
There's nothing do to here for nipkg.py, therefore it will always
return True.
'''
return True
|
saltstack/salt
|
salt/modules/opkg.py
|
_set_state
|
python
|
def _set_state(pkg, state):
'''
Change package state on the opkg database
The state can be any of:
- hold
- noprune
- user
- ok
- installed
- unpacked
This command is commonly used to mark a specific package to be held from
being upgraded, that is, to be kept at a certain version.
Returns a dict containing the package name, and the new and old
versions.
'''
ret = {}
valid_states = ('hold', 'noprune', 'user', 'ok', 'installed', 'unpacked')
if state not in valid_states:
raise SaltInvocationError('Invalid state: {0}'.format(state))
oldstate = _get_state(pkg)
cmd = ['opkg', 'flag']
cmd.append(state)
cmd.append(pkg)
_out = __salt__['cmd.run'](cmd, python_shell=False)
# Missing return value check due to opkg issue 160
ret[pkg] = {'old': oldstate,
'new': state}
return ret
|
Change package state on the opkg database
The state can be any of:
- hold
- noprune
- user
- ok
- installed
- unpacked
This command is commonly used to mark a specific package to be held from
being upgraded, that is, to be kept at a certain version.
Returns a dict containing the package name, and the new and old
versions.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/opkg.py#L936-L968
| null |
# -*- coding: utf-8 -*-
'''
Support for Opkg
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
.. versionadded: 2016.3.0
.. note::
For version comparison support on opkg < 0.3.4, the ``opkg-utils`` package
must be installed.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import os
import re
import logging
import errno
# Import salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.itertools
import salt.utils.path
import salt.utils.pkg
import salt.utils.stringutils
import salt.utils.versions
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import shlex_quote as _cmd_quote # pylint: disable=import-error
from salt.ext.six.moves import map # pylint: disable=import-error,redefined-builtin
REPO_REGEXP = r'^#?\s*(src|src/gz)\s+([^\s<>]+|"[^<>]+")\s+[^\s<>]+'
OPKG_CONFDIR = '/etc/opkg'
ATTR_MAP = {
'Architecture': 'arch',
'Homepage': 'url',
'Installed-Time': 'install_date_time_t',
'Maintainer': 'packager',
'Package': 'name',
'Section': 'group'
}
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
NILRT_RESTARTCHECK_STATE_PATH = '/var/lib/salt/restartcheck_state'
def _update_nilrt_restart_state():
'''
NILRT systems determine whether to reboot after various package operations
including but not limited to kernel module installs/removals by checking
specific file md5sums & timestamps. These files are touched/modified by
the post-install/post-remove functions of their respective packages.
The opkg module uses this function to store/update those file timestamps
and checksums to be used later by the restartcheck module.
'''
__salt__['cmd.shell']('stat -c %Y /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.timestamp'
.format(NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.md5sum'
.format(NILRT_RESTARTCHECK_STATE_PATH))
# We can't assume nisysapi.ini always exists like modules.dep
nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'
if os.path.exists(nisysapi_path):
__salt__['cmd.shell']('stat -c %Y {0} >{1}/nisysapi.ini.timestamp'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0} >{1}/nisysapi.ini.md5sum'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
# Expert plugin files get added to a conf.d dir, so keep track of the total
# no. of files, their timestamps and content hashes
nisysapi_conf_d_path = "/usr/lib/{0}/nisysapi/conf.d/experts/".format(
'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'
)
if os.path.exists(nisysapi_conf_d_path):
with salt.utils.files.fopen('{0}/sysapi.conf.d.count'.format(
NILRT_RESTARTCHECK_STATE_PATH), 'w') as fcount:
fcount.write(str(len(os.listdir(nisysapi_conf_d_path))))
for fexpert in os.listdir(nisysapi_conf_d_path):
__salt__['cmd.shell']('stat -c %Y {0}/{1} >{2}/{1}.timestamp'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0}/{1} >{2}/{1}.md5sum'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
def _get_restartcheck_result(errors):
'''
Return restartcheck result and append errors (if any) to ``errors``
'''
rs_result = __salt__['restartcheck.restartcheck'](verbose=False)
if isinstance(rs_result, dict) and 'comment' in rs_result:
errors.append(rs_result['comment'])
return rs_result
def _process_restartcheck_result(rs_result, **kwargs):
'''
Check restartcheck output to see if system/service restarts were requested
and take appropriate action.
'''
if 'No packages seem to need to be restarted' in rs_result:
return
reboot_required = False
for rstr in rs_result:
if 'System restart required' in rstr:
_update_nilrt_restart_state()
__salt__['system.set_reboot_required_witnessed']()
reboot_required = True
if kwargs.get('always_restart_services', True) or not reboot_required:
for rstr in rs_result:
if 'System restart required' not in rstr:
service = os.path.join('/etc/init.d', rstr)
if os.path.exists(service):
__salt__['cmd.run']([service, 'restart'])
def __virtual__():
'''
Confirm this module is on a nilrt based system
'''
if __grains__.get('os_family') == 'NILinuxRT':
try:
os.makedirs(NILRT_RESTARTCHECK_STATE_PATH)
except OSError as exc:
if exc.errno != errno.EEXIST:
return False, 'Error creating {0} (-{1}): {2}'.format(
NILRT_RESTARTCHECK_STATE_PATH,
exc.errno,
exc.strerror)
# populate state dir if empty
if not os.listdir(NILRT_RESTARTCHECK_STATE_PATH):
_update_nilrt_restart_state()
return __virtualname__
if os.path.isdir(OPKG_CONFDIR):
return __virtualname__
return False, "Module opkg only works on OpenEmbedded based systems"
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
if not names:
return ''
ret = {}
for name in names:
ret[name] = ''
# Refresh before looking for the latest version available
if refresh:
refresh_db()
cmd = ['opkg', 'list-upgradable']
out = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
try:
name, _oldversion, newversion = line.split(' - ')
if name in names:
ret[name] = newversion
except ValueError:
pass
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = latest_version
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(failhard=False, **kwargs): # pylint: disable=unused-argument
'''
Updates the opkg database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
failhard
If False, return results of failed lines as ``False`` for the package
database that encountered the error.
If True, raise an error with a list of the package databases that
encountered errors.
.. versionadded:: 2018.3.0
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
error_repos = []
cmd = ['opkg', 'update']
# opkg returns a non-zero retcode when there is a failure to refresh
# from one or more repos. Due to this, ignore the retcode.
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True,
redirect_stderr=True)
out = call['stdout']
prev_line = ''
for line in salt.utils.itertools.split(out, '\n'):
if 'Inflating' in line:
key = line.strip().split()[1][:-1]
ret[key] = True
elif 'Updated source' in line:
# Use the previous line.
key = prev_line.strip().split()[1][:-1]
ret[key] = True
elif 'Failed to download' in line:
key = line.strip().split()[5].split(',')[0]
ret[key] = False
error_repos.append(key)
prev_line = line
if failhard and error_repos:
raise CommandExecutionError(
'Error getting repos: {0}'.format(', '.join(error_repos))
)
# On a non-zero exit code where no failed repos were found, raise an
# exception because this appears to be a different kind of error.
if call['retcode'] != 0 and not error_repos:
raise CommandExecutionError(out)
return ret
def _is_testmode(**kwargs):
'''
Returns whether a test mode (noaction) operation was requested.
'''
return bool(kwargs.get('test') or __opts__.get('test'))
def _append_noaction_if_testmode(cmd, **kwargs):
'''
Adds the --noaction flag to the command if it's running in the test mode.
'''
if _is_testmode(**kwargs):
cmd.append('--noaction')
def _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall):
'''
Builds a list of install commands to be executed in sequence in order to process
each of the to_install, to_downgrade, and to_reinstall lists.
'''
cmds = []
if to_install:
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(to_install)
cmds.append(cmd)
if to_downgrade:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-downgrade')
cmd.extend(to_downgrade)
cmds.append(cmd)
if to_reinstall:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-reinstall')
cmd.extend(to_reinstall)
cmds.append(cmd)
return cmds
def _parse_reported_packages_from_install_output(output):
'''
Parses the output of "opkg install" to determine what packages would have been
installed by an operation run with the --noaction flag.
We are looking for lines like:
Installing <package> (<version>) on <target>
or
Upgrading <package> from <oldVersion> to <version> on root
'''
reported_pkgs = {}
install_pattern = re.compile(r'Installing\s(?P<package>.*?)\s\((?P<version>.*?)\)\son\s(?P<target>.*?)')
upgrade_pattern = re.compile(r'Upgrading\s(?P<package>.*?)\sfrom\s(?P<oldVersion>.*?)\sto\s(?P<version>.*?)\son\s(?P<target>.*?)')
for line in salt.utils.itertools.split(output, '\n'):
match = install_pattern.match(line)
if match is None:
match = upgrade_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = match.group('version')
return reported_pkgs
def _execute_install_command(cmd, parse_output, errors, parsed_packages):
'''
Executes a command for the install operation.
If the command fails, its error output will be appended to the errors list.
If the command succeeds and parse_output is true, updated packages will be appended
to the parsed_packages dictionary.
'''
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors.append(out['stderr'])
else:
errors.append(out['stdout'])
elif parse_output:
parsed_packages.update(_parse_reported_packages_from_install_output(out['stdout']))
def install(name=None,
refresh=False,
pkgs=None,
sources=None,
reinstall=False,
**kwargs):
'''
Install the passed package, add refresh=True to update the opkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionadded:: 2017.7.0
reinstall : False
Specifying reinstall=True will use ``opkg install --force-reinstall``
rather than simply ``opkg install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``opkg
install --force-reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2017.7.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of IPK packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
install_recommends
Whether to install the packages marked as recommended. Default is True.
only_upgrade
Only upgrade the packages (disallow downgrades), if they are already
installed. Default is False.
.. versionadded:: 2017.7.0
always_restart_services
Whether to restart services even if a reboot is required. Default is True.
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
refreshdb = salt.utils.data.is_true(refresh)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
cmd_prefix = ['opkg', 'install']
to_install = []
to_reinstall = []
to_downgrade = []
_append_noaction_if_testmode(cmd_prefix, **kwargs)
if not pkg_params:
return {}
elif pkg_type == 'file':
if reinstall:
cmd_prefix.append('--force-reinstall')
if not kwargs.get('only_upgrade', False):
cmd_prefix.append('--force-downgrade')
to_install.extend(pkg_params)
elif pkg_type == 'repository':
if not kwargs.get('install_recommends', True):
cmd_prefix.append('--no-install-recommends')
for pkgname, pkgversion in six.iteritems(pkg_params):
if (name and pkgs is None and kwargs.get('version') and
len(pkg_params) == 1):
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
version_num = pkgversion
if version_num is None:
# Don't allow downgrades if the version
# number is not specified.
if reinstall and pkgname in old:
to_reinstall.append(pkgname)
else:
to_install.append(pkgname)
else:
pkgstr = '{0}={1}'.format(pkgname, version_num)
cver = old.get(pkgname, '')
if reinstall and cver and salt.utils.versions.compare(
ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall.append(pkgstr)
elif not cver or salt.utils.versions.compare(
ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
to_install.append(pkgstr)
else:
if not kwargs.get('only_upgrade', False):
to_downgrade.append(pkgstr)
else:
# This should cause the command to fail.
to_install.append(pkgstr)
cmds = _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall)
if not cmds:
return {}
if refreshdb:
refresh_db()
errors = []
is_testmode = _is_testmode(**kwargs)
test_packages = {}
for cmd in cmds:
_execute_install_command(cmd, is_testmode, errors, test_packages)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if is_testmode:
new = copy.deepcopy(new)
new.update(test_packages)
ret = salt.utils.data.compare_dicts(old, new)
if pkg_type == 'file' and reinstall:
# For file-based packages, prepare 'to_reinstall' to have a list
# of all the package names that may have been reinstalled.
# This way, we could include reinstalled packages in 'ret'.
for pkgfile in to_install:
# Convert from file name to package name.
cmd = ['opkg', 'info', pkgfile]
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] == 0:
# Just need the package name.
pkginfo_dict = _process_info_installed_output(
out['stdout'], []
)
if pkginfo_dict:
to_reinstall.append(list(pkginfo_dict.keys())[0])
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def _parse_reported_packages_from_remove_output(output):
'''
Parses the output of "opkg remove" to determine what packages would have been
removed by an operation run with the --noaction flag.
We are looking for lines like
Removing <package> (<version>) from <Target>...
'''
reported_pkgs = {}
remove_pattern = re.compile(r'Removing\s(?P<package>.*?)\s\((?P<version>.*?)\)\sfrom\s(?P<target>.*?)...')
for line in salt.utils.itertools.split(output, '\n'):
match = remove_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = ''
return reported_pkgs
def remove(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Remove packages using ``opkg remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
remove_dependencies
Remove package and all dependencies
.. versionadded:: 2019.2.0
auto_remove_deps
Remove packages that were installed automatically to satisfy dependencies
.. versionadded:: 2019.2.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
salt '*' pkg.remove pkgs='["foo", "bar"]' remove_dependencies=True auto_remove_deps=True
'''
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 {}
cmd = ['opkg', 'remove']
_append_noaction_if_testmode(cmd, **kwargs)
if kwargs.get('remove_dependencies', False):
cmd.append('--force-removal-of-dependent-packages')
if kwargs.get('auto_remove_deps', False):
cmd.append('--autoremove')
cmd.extend(targets)
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors = [out['stderr']]
else:
errors = [out['stdout']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if _is_testmode(**kwargs):
reportedPkgs = _parse_reported_packages_from_remove_output(out['stdout'])
new = {k: v for k, v in new.items() if k not in reportedPkgs}
ret = salt.utils.data.compare_dicts(old, new)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def purge(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Package purges are not supported by opkg, this function is identical to
:mod:`pkg.remove <salt.modules.opkg.remove>`.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name, pkgs=pkgs)
def upgrade(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
Upgrades all packages via ``opkg upgrade``
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
errors = []
if salt.utils.data.is_true(refresh):
refresh_db()
old = list_pkgs()
cmd = ['opkg', 'upgrade']
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
errors.append(result)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif state != 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = _set_state(target, 'hold')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif state == 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret['comment'] = ('Package {0} is set not to be held.'
.format(target))
else:
result = _set_state(target, 'ok')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def _get_state(pkg):
'''
View package state from the opkg database
Return the state of pkg
'''
cmd = ['opkg', 'status']
cmd.append(pkg)
out = __salt__['cmd.run'](cmd, python_shell=False)
state_flag = ''
for line in salt.utils.itertools.split(out, '\n'):
if line.startswith('Status'):
_status, _state_want, state_flag, _state_status = line.split()
return state_flag
def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
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
cmd = ['opkg', 'list-installed']
ret = {}
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
# This is a continuation of package description
if not line or line[0] == ' ':
continue
# This contains package name, version, and description.
# Extract the first two.
pkg_name, pkg_version = line.split(' - ', 2)[:2]
__salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version)
__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 list_upgrades(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
List all available package upgrades.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
ret = {}
if salt.utils.data.is_true(refresh):
refresh_db()
cmd = ['opkg', 'list-upgradable']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
if 'stdout' in call:
comment += call['stdout']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
name, _oldversion, newversion = line.split(' - ')
ret[name] = newversion
return ret
def _convert_to_standard_attr(attr):
'''
Helper function for _process_info_installed_output()
Converts an opkg attribute name to a standard attribute
name which is used across 'pkg' modules.
'''
ret_attr = ATTR_MAP.get(attr, None)
if ret_attr is None:
# All others convert to lowercase
return attr.lower()
return ret_attr
def _process_info_installed_output(out, filter_attrs):
'''
Helper function for info_installed()
Processes stdout output from a single invocation of
'opkg status'.
'''
ret = {}
name = None
attrs = {}
attr = None
for line in salt.utils.itertools.split(out, '\n'):
if line and line[0] == ' ':
# This is a continuation of the last attr
if filter_attrs is None or attr in filter_attrs:
line = line.strip()
if attrs[attr]:
# If attr is empty, don't add leading newline
attrs[attr] += '\n'
attrs[attr] += line
continue
line = line.strip()
if not line:
# Separator between different packages
if name:
ret[name] = attrs
name = None
attrs = {}
attr = None
continue
key, value = line.split(':', 1)
value = value.lstrip()
attr = _convert_to_standard_attr(key)
if attr == 'name':
name = value
elif filter_attrs is None or attr in filter_attrs:
attrs[attr] = value
if name:
ret[name] = attrs
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
.. versionadded:: 2017.7.0
:param names:
Names of the packages to get information about. If none are specified,
will return information for all installed packages.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
arch, conffiles, conflicts, depends, description, filename, group,
install_date_time_t, md5sum, packager, provides, recommends,
replaces, size, source, suggests, url, version
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed
salt '*' pkg.info_installed attr=version,packager
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> attr=version,packager
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,packager
'''
attr = kwargs.pop('attr', None)
if attr is None:
filter_attrs = None
elif isinstance(attr, six.string_types):
filter_attrs = set(attr.split(','))
else:
filter_attrs = set(attr)
ret = {}
if names:
# Specific list of names of installed packages
for name in names:
cmd = ['opkg', 'status', name]
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
else:
# All installed packages
cmd = ['opkg', 'status']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
return ret
def upgrade_available(name, **kwargs): # pylint: disable=unused-argument
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs): # pylint: disable=unused-argument
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2016.3.4
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0' '0.2.4.1-0'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] if ignore_epoch else six.text_type(x)
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
output = __salt__['cmd.run_stdout'](['opkg', '--version'],
output_loglevel='trace',
python_shell=False)
opkg_version = output.split(' ')[2].strip()
if salt.utils.versions.LooseVersion(opkg_version) >= \
salt.utils.versions.LooseVersion('0.3.4'):
cmd_compare = ['opkg', 'compare-versions']
elif salt.utils.path.which('opkg-compare-versions'):
cmd_compare = ['opkg-compare-versions']
else:
log.warning('Unable to find a compare-versions utility installed. Either upgrade opkg to '
'version > 0.3.4 (preferred) or install the older opkg-compare-versions script.')
return None
for oper, ret in (("<<", -1), ("=", 0), (">>", 1)):
cmd = cmd_compare[:]
cmd.append(_cmd_quote(pkg1))
cmd.append(oper)
cmd.append(_cmd_quote(pkg2))
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
ignore_retcode=True,
python_shell=False)
if retcode == 0:
return ret
return None
def _set_repo_option(repo, option):
'''
Set the option to repo
'''
if not option:
return
opt = option.split('=')
if len(opt) != 2:
return
if opt[0] == 'trusted':
repo['trusted'] = opt[1] == 'yes'
else:
repo[opt[0]] = opt[1]
def _set_repo_options(repo, options):
'''
Set the options to the repo.
'''
delimiters = "[", "]"
pattern = '|'.join(map(re.escape, delimiters))
for option in options:
splitted = re.split(pattern, option)
for opt in splitted:
_set_repo_option(repo, opt)
def _create_repo(line, filename):
'''
Create repo
'''
repo = {}
if line.startswith('#'):
repo['enabled'] = False
line = line[1:]
else:
repo['enabled'] = True
cols = salt.utils.args.shlex_split(line.strip())
repo['compressed'] = not cols[0] in 'src'
repo['name'] = cols[1]
repo['uri'] = cols[2]
repo['file'] = os.path.join(OPKG_CONFDIR, filename)
if len(cols) > 3:
_set_repo_options(repo, cols[3:])
return repo
def _read_repos(conf_file, repos, filename, regex):
'''
Read repos from configuration file
'''
for line in conf_file:
line = salt.utils.stringutils.to_unicode(line)
if not regex.search(line):
continue
repo = _create_repo(line, filename)
# do not store duplicated uri's
if repo['uri'] not in repos:
repos[repo['uri']] = [repo]
def list_repos(**kwargs): # pylint: disable=unused-argument
'''
Lists all repos on ``/etc/opkg/*.conf``
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos = {}
regex = re.compile(REPO_REGEXP)
for filename in os.listdir(OPKG_CONFDIR):
if not filename.endswith(".conf"):
continue
with salt.utils.files.fopen(os.path.join(OPKG_CONFDIR, filename)) as conf_file:
_read_repos(conf_file, repos, filename, regex)
return repos
def get_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Display a repo from the ``/etc/opkg/*.conf``
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo repo
'''
repos = list_repos()
if repos:
for source in six.itervalues(repos):
for sub in source:
if sub['name'] == repo:
return sub
return {}
def _del_repo_from_file(repo, filepath):
'''
Remove a repo from filepath
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
regex = re.compile(REPO_REGEXP)
for line in fhandle:
line = salt.utils.stringutils.to_unicode(line)
if regex.search(line):
if line.startswith('#'):
line = line[1:]
cols = salt.utils.args.shlex_split(line.strip())
if repo != cols[1]:
output.append(salt.utils.stringutils.to_str(line))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def _set_trusted_option_if_needed(repostr, trusted):
'''
Set trusted option to repo if needed
'''
if trusted is True:
repostr += ' [trusted=yes]'
elif trusted is False:
repostr += ' [trusted=no]'
return repostr
def _add_new_repo(repo, properties):
'''
Add a new repo entry
'''
repostr = '# ' if not properties.get('enabled') else ''
repostr += 'src/gz ' if properties.get('compressed') else 'src '
if ' ' in repo:
repostr += '"' + repo + '" '
else:
repostr += repo + ' '
repostr += properties.get('uri')
repostr = _set_trusted_option_if_needed(repostr, properties.get('trusted'))
repostr += '\n'
conffile = os.path.join(OPKG_CONFDIR, repo + '.conf')
with salt.utils.files.fopen(conffile, 'a') as fhandle:
fhandle.write(salt.utils.stringutils.to_str(repostr))
def _mod_repo_in_file(repo, repostr, filepath):
'''
Replace a repo entry in filepath with repostr
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
for line in fhandle:
cols = salt.utils.args.shlex_split(
salt.utils.stringutils.to_unicode(line).strip()
)
if repo not in cols:
output.append(line)
else:
output.append(salt.utils.stringutils.to_str(repostr + '\n'))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def del_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Delete a repo from ``/etc/opkg/*.conf``
If the file does not contain any other repo configuration, the file itself
will be deleted.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo repo
'''
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
repos = list_repos()
if repos:
deleted_from = dict()
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
deleted_from[source['file']] = 0
_del_repo_from_file(repo, source['file'])
if deleted_from:
ret = ''
for repository in repos:
source = repos[repository][0]
if source['file'] in deleted_from:
deleted_from[source['file']] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 1 and os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.\n')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
if refresh:
refresh_db()
return ret
return "Repo {0} doesn't exist in the opkg repo lists".format(repo)
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as uri is defined.
The following options are available to modify a repo definition:
repo
alias by which opkg refers to the repo.
uri
the URI to the repo.
compressed
defines (True or False) if the index file is compressed
enabled
enable or disable (True or False) repository
but do not remove if disabled.
refresh
enable or disable (True or False) auto-refresh of the repositories
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo repo uri=http://new/uri
salt '*' pkg.mod_repo repo enabled=False
'''
repos = list_repos()
found = False
uri = ''
if 'uri' in kwargs:
uri = kwargs['uri']
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
found = True
repostr = ''
if 'enabled' in kwargs and not kwargs['enabled']:
repostr += '# '
if 'compressed' in kwargs:
repostr += 'src/gz ' if kwargs['compressed'] else 'src'
else:
repostr += 'src/gz' if source['compressed'] else 'src'
repo_alias = kwargs['alias'] if 'alias' in kwargs else repo
if ' ' in repo_alias:
repostr += ' "{0}"'.format(repo_alias)
else:
repostr += ' {0}'.format(repo_alias)
repostr += ' {0}'.format(kwargs['uri'] if 'uri' in kwargs else source['uri'])
trusted = kwargs.get('trusted')
repostr = _set_trusted_option_if_needed(repostr, trusted) if trusted is not None else \
_set_trusted_option_if_needed(repostr, source.get('trusted'))
_mod_repo_in_file(repo, repostr, source['file'])
elif uri and source['uri'] == uri:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(uri, source['name']))
if not found:
# Need to add a new repo
if 'uri' not in kwargs:
raise CommandExecutionError(
'Repository \'{0}\' not found and no URI passed to create one.'.format(repo))
properties = {'uri': kwargs['uri']}
# If compressed is not defined, assume True
properties['compressed'] = kwargs['compressed'] if 'compressed' in kwargs else True
# If enabled is not defined, assume True
properties['enabled'] = kwargs['enabled'] if 'enabled' in kwargs else True
properties['trusted'] = kwargs.get('trusted')
_add_new_repo(repo, properties)
if 'refresh' in kwargs:
refresh_db()
def file_list(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
output = file_dict(*packages)
files = []
for package in list(output['packages'].values()):
files.extend(package)
return {'errors': output['errors'], 'files': files}
def file_dict(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
errors = []
ret = {}
cmd_files = ['opkg', 'files']
if not packages:
packages = list(list_pkgs().keys())
for package in packages:
files = []
cmd = cmd_files[:]
cmd.append(package)
out = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
for line in out['stdout'].splitlines():
if line.startswith('/'):
files.append(line)
elif line.startswith(' * '):
errors.append(line[3:])
break
else:
continue
if files:
ret[package] = files
return {'errors': errors, 'packages': ret}
def owner(*paths, **kwargs): # pylint: disable=unused-argument
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.opkg.version`, if a single
path is passed, a string will be returned, and if multiple paths are passed,
a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
cmd_search = ['opkg', 'search']
for path in paths:
cmd = cmd_search[:]
cmd.append(path)
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
if output:
ret[path] = output.split(' - ')[0].strip()
else:
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def version_clean(version):
'''
Clean the version string removing extra data.
There's nothing do to here for nipkg.py, therefore it will always
return the given version.
'''
return version
def check_extra_requirements(pkgname, pkgver):
'''
Check if the installed package already has the given requirements.
There's nothing do to here for nipkg.py, therefore it will always
return True.
'''
return True
|
saltstack/salt
|
salt/modules/opkg.py
|
list_upgrades
|
python
|
def list_upgrades(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
List all available package upgrades.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
ret = {}
if salt.utils.data.is_true(refresh):
refresh_db()
cmd = ['opkg', 'list-upgradable']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
if 'stdout' in call:
comment += call['stdout']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
name, _oldversion, newversion = line.split(' - ')
ret[name] = newversion
return ret
|
List all available package upgrades.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/opkg.py#L1018-L1051
|
[
"def is_true(value=None):\n '''\n Returns a boolean value representing the \"truth\" of the value passed. The\n rules for what is a \"True\" value are:\n\n 1. Integer/float values greater than 0\n 2. The string values \"True\" and \"true\"\n 3. Any object for which bool(obj) returns True\n '''\n # First, try int/float conversion\n try:\n value = int(value)\n except (ValueError, TypeError):\n pass\n try:\n value = float(value)\n except (ValueError, TypeError):\n pass\n\n # Now check for truthiness\n if isinstance(value, (six.integer_types, float)):\n return value > 0\n elif isinstance(value, six.string_types):\n return six.text_type(value).lower() == 'true'\n else:\n return bool(value)\n",
"def refresh_db(failhard=False, **kwargs): # pylint: disable=unused-argument\n '''\n Updates the opkg database to latest packages based upon repositories\n\n Returns a dict, with the keys being package databases and the values being\n the result of the update attempt. Values can be one of the following:\n\n - ``True``: Database updated successfully\n - ``False``: Problem updating database\n\n failhard\n If False, return results of failed lines as ``False`` for the package\n database that encountered the error.\n If True, raise an error with a list of the package databases that\n encountered errors.\n\n .. versionadded:: 2018.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.refresh_db\n '''\n # Remove rtag file to keep multiple refreshes from happening in pkg states\n salt.utils.pkg.clear_rtag(__opts__)\n ret = {}\n error_repos = []\n cmd = ['opkg', 'update']\n # opkg returns a non-zero retcode when there is a failure to refresh\n # from one or more repos. Due to this, ignore the retcode.\n call = __salt__['cmd.run_all'](cmd,\n output_loglevel='trace',\n python_shell=False,\n ignore_retcode=True,\n redirect_stderr=True)\n\n out = call['stdout']\n prev_line = ''\n for line in salt.utils.itertools.split(out, '\\n'):\n if 'Inflating' in line:\n key = line.strip().split()[1][:-1]\n ret[key] = True\n elif 'Updated source' in line:\n # Use the previous line.\n key = prev_line.strip().split()[1][:-1]\n ret[key] = True\n elif 'Failed to download' in line:\n key = line.strip().split()[5].split(',')[0]\n ret[key] = False\n error_repos.append(key)\n prev_line = line\n\n if failhard and error_repos:\n raise CommandExecutionError(\n 'Error getting repos: {0}'.format(', '.join(error_repos))\n )\n\n # On a non-zero exit code where no failed repos were found, raise an\n # exception because this appears to be a different kind of error.\n if call['retcode'] != 0 and not error_repos:\n raise CommandExecutionError(out)\n\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Opkg
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
.. versionadded: 2016.3.0
.. note::
For version comparison support on opkg < 0.3.4, the ``opkg-utils`` package
must be installed.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import os
import re
import logging
import errno
# Import salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.itertools
import salt.utils.path
import salt.utils.pkg
import salt.utils.stringutils
import salt.utils.versions
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import shlex_quote as _cmd_quote # pylint: disable=import-error
from salt.ext.six.moves import map # pylint: disable=import-error,redefined-builtin
REPO_REGEXP = r'^#?\s*(src|src/gz)\s+([^\s<>]+|"[^<>]+")\s+[^\s<>]+'
OPKG_CONFDIR = '/etc/opkg'
ATTR_MAP = {
'Architecture': 'arch',
'Homepage': 'url',
'Installed-Time': 'install_date_time_t',
'Maintainer': 'packager',
'Package': 'name',
'Section': 'group'
}
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
NILRT_RESTARTCHECK_STATE_PATH = '/var/lib/salt/restartcheck_state'
def _update_nilrt_restart_state():
'''
NILRT systems determine whether to reboot after various package operations
including but not limited to kernel module installs/removals by checking
specific file md5sums & timestamps. These files are touched/modified by
the post-install/post-remove functions of their respective packages.
The opkg module uses this function to store/update those file timestamps
and checksums to be used later by the restartcheck module.
'''
__salt__['cmd.shell']('stat -c %Y /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.timestamp'
.format(NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.md5sum'
.format(NILRT_RESTARTCHECK_STATE_PATH))
# We can't assume nisysapi.ini always exists like modules.dep
nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'
if os.path.exists(nisysapi_path):
__salt__['cmd.shell']('stat -c %Y {0} >{1}/nisysapi.ini.timestamp'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0} >{1}/nisysapi.ini.md5sum'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
# Expert plugin files get added to a conf.d dir, so keep track of the total
# no. of files, their timestamps and content hashes
nisysapi_conf_d_path = "/usr/lib/{0}/nisysapi/conf.d/experts/".format(
'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'
)
if os.path.exists(nisysapi_conf_d_path):
with salt.utils.files.fopen('{0}/sysapi.conf.d.count'.format(
NILRT_RESTARTCHECK_STATE_PATH), 'w') as fcount:
fcount.write(str(len(os.listdir(nisysapi_conf_d_path))))
for fexpert in os.listdir(nisysapi_conf_d_path):
__salt__['cmd.shell']('stat -c %Y {0}/{1} >{2}/{1}.timestamp'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0}/{1} >{2}/{1}.md5sum'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
def _get_restartcheck_result(errors):
'''
Return restartcheck result and append errors (if any) to ``errors``
'''
rs_result = __salt__['restartcheck.restartcheck'](verbose=False)
if isinstance(rs_result, dict) and 'comment' in rs_result:
errors.append(rs_result['comment'])
return rs_result
def _process_restartcheck_result(rs_result, **kwargs):
'''
Check restartcheck output to see if system/service restarts were requested
and take appropriate action.
'''
if 'No packages seem to need to be restarted' in rs_result:
return
reboot_required = False
for rstr in rs_result:
if 'System restart required' in rstr:
_update_nilrt_restart_state()
__salt__['system.set_reboot_required_witnessed']()
reboot_required = True
if kwargs.get('always_restart_services', True) or not reboot_required:
for rstr in rs_result:
if 'System restart required' not in rstr:
service = os.path.join('/etc/init.d', rstr)
if os.path.exists(service):
__salt__['cmd.run']([service, 'restart'])
def __virtual__():
'''
Confirm this module is on a nilrt based system
'''
if __grains__.get('os_family') == 'NILinuxRT':
try:
os.makedirs(NILRT_RESTARTCHECK_STATE_PATH)
except OSError as exc:
if exc.errno != errno.EEXIST:
return False, 'Error creating {0} (-{1}): {2}'.format(
NILRT_RESTARTCHECK_STATE_PATH,
exc.errno,
exc.strerror)
# populate state dir if empty
if not os.listdir(NILRT_RESTARTCHECK_STATE_PATH):
_update_nilrt_restart_state()
return __virtualname__
if os.path.isdir(OPKG_CONFDIR):
return __virtualname__
return False, "Module opkg only works on OpenEmbedded based systems"
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
if not names:
return ''
ret = {}
for name in names:
ret[name] = ''
# Refresh before looking for the latest version available
if refresh:
refresh_db()
cmd = ['opkg', 'list-upgradable']
out = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
try:
name, _oldversion, newversion = line.split(' - ')
if name in names:
ret[name] = newversion
except ValueError:
pass
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = latest_version
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(failhard=False, **kwargs): # pylint: disable=unused-argument
'''
Updates the opkg database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
failhard
If False, return results of failed lines as ``False`` for the package
database that encountered the error.
If True, raise an error with a list of the package databases that
encountered errors.
.. versionadded:: 2018.3.0
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
error_repos = []
cmd = ['opkg', 'update']
# opkg returns a non-zero retcode when there is a failure to refresh
# from one or more repos. Due to this, ignore the retcode.
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True,
redirect_stderr=True)
out = call['stdout']
prev_line = ''
for line in salt.utils.itertools.split(out, '\n'):
if 'Inflating' in line:
key = line.strip().split()[1][:-1]
ret[key] = True
elif 'Updated source' in line:
# Use the previous line.
key = prev_line.strip().split()[1][:-1]
ret[key] = True
elif 'Failed to download' in line:
key = line.strip().split()[5].split(',')[0]
ret[key] = False
error_repos.append(key)
prev_line = line
if failhard and error_repos:
raise CommandExecutionError(
'Error getting repos: {0}'.format(', '.join(error_repos))
)
# On a non-zero exit code where no failed repos were found, raise an
# exception because this appears to be a different kind of error.
if call['retcode'] != 0 and not error_repos:
raise CommandExecutionError(out)
return ret
def _is_testmode(**kwargs):
'''
Returns whether a test mode (noaction) operation was requested.
'''
return bool(kwargs.get('test') or __opts__.get('test'))
def _append_noaction_if_testmode(cmd, **kwargs):
'''
Adds the --noaction flag to the command if it's running in the test mode.
'''
if _is_testmode(**kwargs):
cmd.append('--noaction')
def _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall):
'''
Builds a list of install commands to be executed in sequence in order to process
each of the to_install, to_downgrade, and to_reinstall lists.
'''
cmds = []
if to_install:
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(to_install)
cmds.append(cmd)
if to_downgrade:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-downgrade')
cmd.extend(to_downgrade)
cmds.append(cmd)
if to_reinstall:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-reinstall')
cmd.extend(to_reinstall)
cmds.append(cmd)
return cmds
def _parse_reported_packages_from_install_output(output):
'''
Parses the output of "opkg install" to determine what packages would have been
installed by an operation run with the --noaction flag.
We are looking for lines like:
Installing <package> (<version>) on <target>
or
Upgrading <package> from <oldVersion> to <version> on root
'''
reported_pkgs = {}
install_pattern = re.compile(r'Installing\s(?P<package>.*?)\s\((?P<version>.*?)\)\son\s(?P<target>.*?)')
upgrade_pattern = re.compile(r'Upgrading\s(?P<package>.*?)\sfrom\s(?P<oldVersion>.*?)\sto\s(?P<version>.*?)\son\s(?P<target>.*?)')
for line in salt.utils.itertools.split(output, '\n'):
match = install_pattern.match(line)
if match is None:
match = upgrade_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = match.group('version')
return reported_pkgs
def _execute_install_command(cmd, parse_output, errors, parsed_packages):
'''
Executes a command for the install operation.
If the command fails, its error output will be appended to the errors list.
If the command succeeds and parse_output is true, updated packages will be appended
to the parsed_packages dictionary.
'''
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors.append(out['stderr'])
else:
errors.append(out['stdout'])
elif parse_output:
parsed_packages.update(_parse_reported_packages_from_install_output(out['stdout']))
def install(name=None,
refresh=False,
pkgs=None,
sources=None,
reinstall=False,
**kwargs):
'''
Install the passed package, add refresh=True to update the opkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionadded:: 2017.7.0
reinstall : False
Specifying reinstall=True will use ``opkg install --force-reinstall``
rather than simply ``opkg install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``opkg
install --force-reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2017.7.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of IPK packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
install_recommends
Whether to install the packages marked as recommended. Default is True.
only_upgrade
Only upgrade the packages (disallow downgrades), if they are already
installed. Default is False.
.. versionadded:: 2017.7.0
always_restart_services
Whether to restart services even if a reboot is required. Default is True.
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
refreshdb = salt.utils.data.is_true(refresh)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
cmd_prefix = ['opkg', 'install']
to_install = []
to_reinstall = []
to_downgrade = []
_append_noaction_if_testmode(cmd_prefix, **kwargs)
if not pkg_params:
return {}
elif pkg_type == 'file':
if reinstall:
cmd_prefix.append('--force-reinstall')
if not kwargs.get('only_upgrade', False):
cmd_prefix.append('--force-downgrade')
to_install.extend(pkg_params)
elif pkg_type == 'repository':
if not kwargs.get('install_recommends', True):
cmd_prefix.append('--no-install-recommends')
for pkgname, pkgversion in six.iteritems(pkg_params):
if (name and pkgs is None and kwargs.get('version') and
len(pkg_params) == 1):
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
version_num = pkgversion
if version_num is None:
# Don't allow downgrades if the version
# number is not specified.
if reinstall and pkgname in old:
to_reinstall.append(pkgname)
else:
to_install.append(pkgname)
else:
pkgstr = '{0}={1}'.format(pkgname, version_num)
cver = old.get(pkgname, '')
if reinstall and cver and salt.utils.versions.compare(
ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall.append(pkgstr)
elif not cver or salt.utils.versions.compare(
ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
to_install.append(pkgstr)
else:
if not kwargs.get('only_upgrade', False):
to_downgrade.append(pkgstr)
else:
# This should cause the command to fail.
to_install.append(pkgstr)
cmds = _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall)
if not cmds:
return {}
if refreshdb:
refresh_db()
errors = []
is_testmode = _is_testmode(**kwargs)
test_packages = {}
for cmd in cmds:
_execute_install_command(cmd, is_testmode, errors, test_packages)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if is_testmode:
new = copy.deepcopy(new)
new.update(test_packages)
ret = salt.utils.data.compare_dicts(old, new)
if pkg_type == 'file' and reinstall:
# For file-based packages, prepare 'to_reinstall' to have a list
# of all the package names that may have been reinstalled.
# This way, we could include reinstalled packages in 'ret'.
for pkgfile in to_install:
# Convert from file name to package name.
cmd = ['opkg', 'info', pkgfile]
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] == 0:
# Just need the package name.
pkginfo_dict = _process_info_installed_output(
out['stdout'], []
)
if pkginfo_dict:
to_reinstall.append(list(pkginfo_dict.keys())[0])
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def _parse_reported_packages_from_remove_output(output):
'''
Parses the output of "opkg remove" to determine what packages would have been
removed by an operation run with the --noaction flag.
We are looking for lines like
Removing <package> (<version>) from <Target>...
'''
reported_pkgs = {}
remove_pattern = re.compile(r'Removing\s(?P<package>.*?)\s\((?P<version>.*?)\)\sfrom\s(?P<target>.*?)...')
for line in salt.utils.itertools.split(output, '\n'):
match = remove_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = ''
return reported_pkgs
def remove(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Remove packages using ``opkg remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
remove_dependencies
Remove package and all dependencies
.. versionadded:: 2019.2.0
auto_remove_deps
Remove packages that were installed automatically to satisfy dependencies
.. versionadded:: 2019.2.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
salt '*' pkg.remove pkgs='["foo", "bar"]' remove_dependencies=True auto_remove_deps=True
'''
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 {}
cmd = ['opkg', 'remove']
_append_noaction_if_testmode(cmd, **kwargs)
if kwargs.get('remove_dependencies', False):
cmd.append('--force-removal-of-dependent-packages')
if kwargs.get('auto_remove_deps', False):
cmd.append('--autoremove')
cmd.extend(targets)
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors = [out['stderr']]
else:
errors = [out['stdout']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if _is_testmode(**kwargs):
reportedPkgs = _parse_reported_packages_from_remove_output(out['stdout'])
new = {k: v for k, v in new.items() if k not in reportedPkgs}
ret = salt.utils.data.compare_dicts(old, new)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def purge(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Package purges are not supported by opkg, this function is identical to
:mod:`pkg.remove <salt.modules.opkg.remove>`.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name, pkgs=pkgs)
def upgrade(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
Upgrades all packages via ``opkg upgrade``
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
errors = []
if salt.utils.data.is_true(refresh):
refresh_db()
old = list_pkgs()
cmd = ['opkg', 'upgrade']
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
errors.append(result)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif state != 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = _set_state(target, 'hold')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif state == 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret['comment'] = ('Package {0} is set not to be held.'
.format(target))
else:
result = _set_state(target, 'ok')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def _get_state(pkg):
'''
View package state from the opkg database
Return the state of pkg
'''
cmd = ['opkg', 'status']
cmd.append(pkg)
out = __salt__['cmd.run'](cmd, python_shell=False)
state_flag = ''
for line in salt.utils.itertools.split(out, '\n'):
if line.startswith('Status'):
_status, _state_want, state_flag, _state_status = line.split()
return state_flag
def _set_state(pkg, state):
'''
Change package state on the opkg database
The state can be any of:
- hold
- noprune
- user
- ok
- installed
- unpacked
This command is commonly used to mark a specific package to be held from
being upgraded, that is, to be kept at a certain version.
Returns a dict containing the package name, and the new and old
versions.
'''
ret = {}
valid_states = ('hold', 'noprune', 'user', 'ok', 'installed', 'unpacked')
if state not in valid_states:
raise SaltInvocationError('Invalid state: {0}'.format(state))
oldstate = _get_state(pkg)
cmd = ['opkg', 'flag']
cmd.append(state)
cmd.append(pkg)
_out = __salt__['cmd.run'](cmd, python_shell=False)
# Missing return value check due to opkg issue 160
ret[pkg] = {'old': oldstate,
'new': state}
return ret
def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
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
cmd = ['opkg', 'list-installed']
ret = {}
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
# This is a continuation of package description
if not line or line[0] == ' ':
continue
# This contains package name, version, and description.
# Extract the first two.
pkg_name, pkg_version = line.split(' - ', 2)[:2]
__salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version)
__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 _convert_to_standard_attr(attr):
'''
Helper function for _process_info_installed_output()
Converts an opkg attribute name to a standard attribute
name which is used across 'pkg' modules.
'''
ret_attr = ATTR_MAP.get(attr, None)
if ret_attr is None:
# All others convert to lowercase
return attr.lower()
return ret_attr
def _process_info_installed_output(out, filter_attrs):
'''
Helper function for info_installed()
Processes stdout output from a single invocation of
'opkg status'.
'''
ret = {}
name = None
attrs = {}
attr = None
for line in salt.utils.itertools.split(out, '\n'):
if line and line[0] == ' ':
# This is a continuation of the last attr
if filter_attrs is None or attr in filter_attrs:
line = line.strip()
if attrs[attr]:
# If attr is empty, don't add leading newline
attrs[attr] += '\n'
attrs[attr] += line
continue
line = line.strip()
if not line:
# Separator between different packages
if name:
ret[name] = attrs
name = None
attrs = {}
attr = None
continue
key, value = line.split(':', 1)
value = value.lstrip()
attr = _convert_to_standard_attr(key)
if attr == 'name':
name = value
elif filter_attrs is None or attr in filter_attrs:
attrs[attr] = value
if name:
ret[name] = attrs
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
.. versionadded:: 2017.7.0
:param names:
Names of the packages to get information about. If none are specified,
will return information for all installed packages.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
arch, conffiles, conflicts, depends, description, filename, group,
install_date_time_t, md5sum, packager, provides, recommends,
replaces, size, source, suggests, url, version
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed
salt '*' pkg.info_installed attr=version,packager
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> attr=version,packager
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,packager
'''
attr = kwargs.pop('attr', None)
if attr is None:
filter_attrs = None
elif isinstance(attr, six.string_types):
filter_attrs = set(attr.split(','))
else:
filter_attrs = set(attr)
ret = {}
if names:
# Specific list of names of installed packages
for name in names:
cmd = ['opkg', 'status', name]
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
else:
# All installed packages
cmd = ['opkg', 'status']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
return ret
def upgrade_available(name, **kwargs): # pylint: disable=unused-argument
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs): # pylint: disable=unused-argument
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2016.3.4
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0' '0.2.4.1-0'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] if ignore_epoch else six.text_type(x)
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
output = __salt__['cmd.run_stdout'](['opkg', '--version'],
output_loglevel='trace',
python_shell=False)
opkg_version = output.split(' ')[2].strip()
if salt.utils.versions.LooseVersion(opkg_version) >= \
salt.utils.versions.LooseVersion('0.3.4'):
cmd_compare = ['opkg', 'compare-versions']
elif salt.utils.path.which('opkg-compare-versions'):
cmd_compare = ['opkg-compare-versions']
else:
log.warning('Unable to find a compare-versions utility installed. Either upgrade opkg to '
'version > 0.3.4 (preferred) or install the older opkg-compare-versions script.')
return None
for oper, ret in (("<<", -1), ("=", 0), (">>", 1)):
cmd = cmd_compare[:]
cmd.append(_cmd_quote(pkg1))
cmd.append(oper)
cmd.append(_cmd_quote(pkg2))
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
ignore_retcode=True,
python_shell=False)
if retcode == 0:
return ret
return None
def _set_repo_option(repo, option):
'''
Set the option to repo
'''
if not option:
return
opt = option.split('=')
if len(opt) != 2:
return
if opt[0] == 'trusted':
repo['trusted'] = opt[1] == 'yes'
else:
repo[opt[0]] = opt[1]
def _set_repo_options(repo, options):
'''
Set the options to the repo.
'''
delimiters = "[", "]"
pattern = '|'.join(map(re.escape, delimiters))
for option in options:
splitted = re.split(pattern, option)
for opt in splitted:
_set_repo_option(repo, opt)
def _create_repo(line, filename):
'''
Create repo
'''
repo = {}
if line.startswith('#'):
repo['enabled'] = False
line = line[1:]
else:
repo['enabled'] = True
cols = salt.utils.args.shlex_split(line.strip())
repo['compressed'] = not cols[0] in 'src'
repo['name'] = cols[1]
repo['uri'] = cols[2]
repo['file'] = os.path.join(OPKG_CONFDIR, filename)
if len(cols) > 3:
_set_repo_options(repo, cols[3:])
return repo
def _read_repos(conf_file, repos, filename, regex):
'''
Read repos from configuration file
'''
for line in conf_file:
line = salt.utils.stringutils.to_unicode(line)
if not regex.search(line):
continue
repo = _create_repo(line, filename)
# do not store duplicated uri's
if repo['uri'] not in repos:
repos[repo['uri']] = [repo]
def list_repos(**kwargs): # pylint: disable=unused-argument
'''
Lists all repos on ``/etc/opkg/*.conf``
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos = {}
regex = re.compile(REPO_REGEXP)
for filename in os.listdir(OPKG_CONFDIR):
if not filename.endswith(".conf"):
continue
with salt.utils.files.fopen(os.path.join(OPKG_CONFDIR, filename)) as conf_file:
_read_repos(conf_file, repos, filename, regex)
return repos
def get_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Display a repo from the ``/etc/opkg/*.conf``
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo repo
'''
repos = list_repos()
if repos:
for source in six.itervalues(repos):
for sub in source:
if sub['name'] == repo:
return sub
return {}
def _del_repo_from_file(repo, filepath):
'''
Remove a repo from filepath
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
regex = re.compile(REPO_REGEXP)
for line in fhandle:
line = salt.utils.stringutils.to_unicode(line)
if regex.search(line):
if line.startswith('#'):
line = line[1:]
cols = salt.utils.args.shlex_split(line.strip())
if repo != cols[1]:
output.append(salt.utils.stringutils.to_str(line))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def _set_trusted_option_if_needed(repostr, trusted):
'''
Set trusted option to repo if needed
'''
if trusted is True:
repostr += ' [trusted=yes]'
elif trusted is False:
repostr += ' [trusted=no]'
return repostr
def _add_new_repo(repo, properties):
'''
Add a new repo entry
'''
repostr = '# ' if not properties.get('enabled') else ''
repostr += 'src/gz ' if properties.get('compressed') else 'src '
if ' ' in repo:
repostr += '"' + repo + '" '
else:
repostr += repo + ' '
repostr += properties.get('uri')
repostr = _set_trusted_option_if_needed(repostr, properties.get('trusted'))
repostr += '\n'
conffile = os.path.join(OPKG_CONFDIR, repo + '.conf')
with salt.utils.files.fopen(conffile, 'a') as fhandle:
fhandle.write(salt.utils.stringutils.to_str(repostr))
def _mod_repo_in_file(repo, repostr, filepath):
'''
Replace a repo entry in filepath with repostr
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
for line in fhandle:
cols = salt.utils.args.shlex_split(
salt.utils.stringutils.to_unicode(line).strip()
)
if repo not in cols:
output.append(line)
else:
output.append(salt.utils.stringutils.to_str(repostr + '\n'))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def del_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Delete a repo from ``/etc/opkg/*.conf``
If the file does not contain any other repo configuration, the file itself
will be deleted.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo repo
'''
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
repos = list_repos()
if repos:
deleted_from = dict()
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
deleted_from[source['file']] = 0
_del_repo_from_file(repo, source['file'])
if deleted_from:
ret = ''
for repository in repos:
source = repos[repository][0]
if source['file'] in deleted_from:
deleted_from[source['file']] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 1 and os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.\n')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
if refresh:
refresh_db()
return ret
return "Repo {0} doesn't exist in the opkg repo lists".format(repo)
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as uri is defined.
The following options are available to modify a repo definition:
repo
alias by which opkg refers to the repo.
uri
the URI to the repo.
compressed
defines (True or False) if the index file is compressed
enabled
enable or disable (True or False) repository
but do not remove if disabled.
refresh
enable or disable (True or False) auto-refresh of the repositories
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo repo uri=http://new/uri
salt '*' pkg.mod_repo repo enabled=False
'''
repos = list_repos()
found = False
uri = ''
if 'uri' in kwargs:
uri = kwargs['uri']
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
found = True
repostr = ''
if 'enabled' in kwargs and not kwargs['enabled']:
repostr += '# '
if 'compressed' in kwargs:
repostr += 'src/gz ' if kwargs['compressed'] else 'src'
else:
repostr += 'src/gz' if source['compressed'] else 'src'
repo_alias = kwargs['alias'] if 'alias' in kwargs else repo
if ' ' in repo_alias:
repostr += ' "{0}"'.format(repo_alias)
else:
repostr += ' {0}'.format(repo_alias)
repostr += ' {0}'.format(kwargs['uri'] if 'uri' in kwargs else source['uri'])
trusted = kwargs.get('trusted')
repostr = _set_trusted_option_if_needed(repostr, trusted) if trusted is not None else \
_set_trusted_option_if_needed(repostr, source.get('trusted'))
_mod_repo_in_file(repo, repostr, source['file'])
elif uri and source['uri'] == uri:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(uri, source['name']))
if not found:
# Need to add a new repo
if 'uri' not in kwargs:
raise CommandExecutionError(
'Repository \'{0}\' not found and no URI passed to create one.'.format(repo))
properties = {'uri': kwargs['uri']}
# If compressed is not defined, assume True
properties['compressed'] = kwargs['compressed'] if 'compressed' in kwargs else True
# If enabled is not defined, assume True
properties['enabled'] = kwargs['enabled'] if 'enabled' in kwargs else True
properties['trusted'] = kwargs.get('trusted')
_add_new_repo(repo, properties)
if 'refresh' in kwargs:
refresh_db()
def file_list(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
output = file_dict(*packages)
files = []
for package in list(output['packages'].values()):
files.extend(package)
return {'errors': output['errors'], 'files': files}
def file_dict(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
errors = []
ret = {}
cmd_files = ['opkg', 'files']
if not packages:
packages = list(list_pkgs().keys())
for package in packages:
files = []
cmd = cmd_files[:]
cmd.append(package)
out = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
for line in out['stdout'].splitlines():
if line.startswith('/'):
files.append(line)
elif line.startswith(' * '):
errors.append(line[3:])
break
else:
continue
if files:
ret[package] = files
return {'errors': errors, 'packages': ret}
def owner(*paths, **kwargs): # pylint: disable=unused-argument
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.opkg.version`, if a single
path is passed, a string will be returned, and if multiple paths are passed,
a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
cmd_search = ['opkg', 'search']
for path in paths:
cmd = cmd_search[:]
cmd.append(path)
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
if output:
ret[path] = output.split(' - ')[0].strip()
else:
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def version_clean(version):
'''
Clean the version string removing extra data.
There's nothing do to here for nipkg.py, therefore it will always
return the given version.
'''
return version
def check_extra_requirements(pkgname, pkgver):
'''
Check if the installed package already has the given requirements.
There's nothing do to here for nipkg.py, therefore it will always
return True.
'''
return True
|
saltstack/salt
|
salt/modules/opkg.py
|
_convert_to_standard_attr
|
python
|
def _convert_to_standard_attr(attr):
'''
Helper function for _process_info_installed_output()
Converts an opkg attribute name to a standard attribute
name which is used across 'pkg' modules.
'''
ret_attr = ATTR_MAP.get(attr, None)
if ret_attr is None:
# All others convert to lowercase
return attr.lower()
return ret_attr
|
Helper function for _process_info_installed_output()
Converts an opkg attribute name to a standard attribute
name which is used across 'pkg' modules.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/opkg.py#L1054-L1065
| null |
# -*- coding: utf-8 -*-
'''
Support for Opkg
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
.. versionadded: 2016.3.0
.. note::
For version comparison support on opkg < 0.3.4, the ``opkg-utils`` package
must be installed.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import os
import re
import logging
import errno
# Import salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.itertools
import salt.utils.path
import salt.utils.pkg
import salt.utils.stringutils
import salt.utils.versions
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import shlex_quote as _cmd_quote # pylint: disable=import-error
from salt.ext.six.moves import map # pylint: disable=import-error,redefined-builtin
REPO_REGEXP = r'^#?\s*(src|src/gz)\s+([^\s<>]+|"[^<>]+")\s+[^\s<>]+'
OPKG_CONFDIR = '/etc/opkg'
ATTR_MAP = {
'Architecture': 'arch',
'Homepage': 'url',
'Installed-Time': 'install_date_time_t',
'Maintainer': 'packager',
'Package': 'name',
'Section': 'group'
}
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
NILRT_RESTARTCHECK_STATE_PATH = '/var/lib/salt/restartcheck_state'
def _update_nilrt_restart_state():
'''
NILRT systems determine whether to reboot after various package operations
including but not limited to kernel module installs/removals by checking
specific file md5sums & timestamps. These files are touched/modified by
the post-install/post-remove functions of their respective packages.
The opkg module uses this function to store/update those file timestamps
and checksums to be used later by the restartcheck module.
'''
__salt__['cmd.shell']('stat -c %Y /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.timestamp'
.format(NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.md5sum'
.format(NILRT_RESTARTCHECK_STATE_PATH))
# We can't assume nisysapi.ini always exists like modules.dep
nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'
if os.path.exists(nisysapi_path):
__salt__['cmd.shell']('stat -c %Y {0} >{1}/nisysapi.ini.timestamp'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0} >{1}/nisysapi.ini.md5sum'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
# Expert plugin files get added to a conf.d dir, so keep track of the total
# no. of files, their timestamps and content hashes
nisysapi_conf_d_path = "/usr/lib/{0}/nisysapi/conf.d/experts/".format(
'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'
)
if os.path.exists(nisysapi_conf_d_path):
with salt.utils.files.fopen('{0}/sysapi.conf.d.count'.format(
NILRT_RESTARTCHECK_STATE_PATH), 'w') as fcount:
fcount.write(str(len(os.listdir(nisysapi_conf_d_path))))
for fexpert in os.listdir(nisysapi_conf_d_path):
__salt__['cmd.shell']('stat -c %Y {0}/{1} >{2}/{1}.timestamp'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0}/{1} >{2}/{1}.md5sum'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
def _get_restartcheck_result(errors):
'''
Return restartcheck result and append errors (if any) to ``errors``
'''
rs_result = __salt__['restartcheck.restartcheck'](verbose=False)
if isinstance(rs_result, dict) and 'comment' in rs_result:
errors.append(rs_result['comment'])
return rs_result
def _process_restartcheck_result(rs_result, **kwargs):
'''
Check restartcheck output to see if system/service restarts were requested
and take appropriate action.
'''
if 'No packages seem to need to be restarted' in rs_result:
return
reboot_required = False
for rstr in rs_result:
if 'System restart required' in rstr:
_update_nilrt_restart_state()
__salt__['system.set_reboot_required_witnessed']()
reboot_required = True
if kwargs.get('always_restart_services', True) or not reboot_required:
for rstr in rs_result:
if 'System restart required' not in rstr:
service = os.path.join('/etc/init.d', rstr)
if os.path.exists(service):
__salt__['cmd.run']([service, 'restart'])
def __virtual__():
'''
Confirm this module is on a nilrt based system
'''
if __grains__.get('os_family') == 'NILinuxRT':
try:
os.makedirs(NILRT_RESTARTCHECK_STATE_PATH)
except OSError as exc:
if exc.errno != errno.EEXIST:
return False, 'Error creating {0} (-{1}): {2}'.format(
NILRT_RESTARTCHECK_STATE_PATH,
exc.errno,
exc.strerror)
# populate state dir if empty
if not os.listdir(NILRT_RESTARTCHECK_STATE_PATH):
_update_nilrt_restart_state()
return __virtualname__
if os.path.isdir(OPKG_CONFDIR):
return __virtualname__
return False, "Module opkg only works on OpenEmbedded based systems"
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
if not names:
return ''
ret = {}
for name in names:
ret[name] = ''
# Refresh before looking for the latest version available
if refresh:
refresh_db()
cmd = ['opkg', 'list-upgradable']
out = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
try:
name, _oldversion, newversion = line.split(' - ')
if name in names:
ret[name] = newversion
except ValueError:
pass
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = latest_version
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(failhard=False, **kwargs): # pylint: disable=unused-argument
'''
Updates the opkg database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
failhard
If False, return results of failed lines as ``False`` for the package
database that encountered the error.
If True, raise an error with a list of the package databases that
encountered errors.
.. versionadded:: 2018.3.0
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
error_repos = []
cmd = ['opkg', 'update']
# opkg returns a non-zero retcode when there is a failure to refresh
# from one or more repos. Due to this, ignore the retcode.
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True,
redirect_stderr=True)
out = call['stdout']
prev_line = ''
for line in salt.utils.itertools.split(out, '\n'):
if 'Inflating' in line:
key = line.strip().split()[1][:-1]
ret[key] = True
elif 'Updated source' in line:
# Use the previous line.
key = prev_line.strip().split()[1][:-1]
ret[key] = True
elif 'Failed to download' in line:
key = line.strip().split()[5].split(',')[0]
ret[key] = False
error_repos.append(key)
prev_line = line
if failhard and error_repos:
raise CommandExecutionError(
'Error getting repos: {0}'.format(', '.join(error_repos))
)
# On a non-zero exit code where no failed repos were found, raise an
# exception because this appears to be a different kind of error.
if call['retcode'] != 0 and not error_repos:
raise CommandExecutionError(out)
return ret
def _is_testmode(**kwargs):
'''
Returns whether a test mode (noaction) operation was requested.
'''
return bool(kwargs.get('test') or __opts__.get('test'))
def _append_noaction_if_testmode(cmd, **kwargs):
'''
Adds the --noaction flag to the command if it's running in the test mode.
'''
if _is_testmode(**kwargs):
cmd.append('--noaction')
def _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall):
'''
Builds a list of install commands to be executed in sequence in order to process
each of the to_install, to_downgrade, and to_reinstall lists.
'''
cmds = []
if to_install:
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(to_install)
cmds.append(cmd)
if to_downgrade:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-downgrade')
cmd.extend(to_downgrade)
cmds.append(cmd)
if to_reinstall:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-reinstall')
cmd.extend(to_reinstall)
cmds.append(cmd)
return cmds
def _parse_reported_packages_from_install_output(output):
'''
Parses the output of "opkg install" to determine what packages would have been
installed by an operation run with the --noaction flag.
We are looking for lines like:
Installing <package> (<version>) on <target>
or
Upgrading <package> from <oldVersion> to <version> on root
'''
reported_pkgs = {}
install_pattern = re.compile(r'Installing\s(?P<package>.*?)\s\((?P<version>.*?)\)\son\s(?P<target>.*?)')
upgrade_pattern = re.compile(r'Upgrading\s(?P<package>.*?)\sfrom\s(?P<oldVersion>.*?)\sto\s(?P<version>.*?)\son\s(?P<target>.*?)')
for line in salt.utils.itertools.split(output, '\n'):
match = install_pattern.match(line)
if match is None:
match = upgrade_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = match.group('version')
return reported_pkgs
def _execute_install_command(cmd, parse_output, errors, parsed_packages):
'''
Executes a command for the install operation.
If the command fails, its error output will be appended to the errors list.
If the command succeeds and parse_output is true, updated packages will be appended
to the parsed_packages dictionary.
'''
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors.append(out['stderr'])
else:
errors.append(out['stdout'])
elif parse_output:
parsed_packages.update(_parse_reported_packages_from_install_output(out['stdout']))
def install(name=None,
refresh=False,
pkgs=None,
sources=None,
reinstall=False,
**kwargs):
'''
Install the passed package, add refresh=True to update the opkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionadded:: 2017.7.0
reinstall : False
Specifying reinstall=True will use ``opkg install --force-reinstall``
rather than simply ``opkg install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``opkg
install --force-reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2017.7.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of IPK packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
install_recommends
Whether to install the packages marked as recommended. Default is True.
only_upgrade
Only upgrade the packages (disallow downgrades), if they are already
installed. Default is False.
.. versionadded:: 2017.7.0
always_restart_services
Whether to restart services even if a reboot is required. Default is True.
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
refreshdb = salt.utils.data.is_true(refresh)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
cmd_prefix = ['opkg', 'install']
to_install = []
to_reinstall = []
to_downgrade = []
_append_noaction_if_testmode(cmd_prefix, **kwargs)
if not pkg_params:
return {}
elif pkg_type == 'file':
if reinstall:
cmd_prefix.append('--force-reinstall')
if not kwargs.get('only_upgrade', False):
cmd_prefix.append('--force-downgrade')
to_install.extend(pkg_params)
elif pkg_type == 'repository':
if not kwargs.get('install_recommends', True):
cmd_prefix.append('--no-install-recommends')
for pkgname, pkgversion in six.iteritems(pkg_params):
if (name and pkgs is None and kwargs.get('version') and
len(pkg_params) == 1):
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
version_num = pkgversion
if version_num is None:
# Don't allow downgrades if the version
# number is not specified.
if reinstall and pkgname in old:
to_reinstall.append(pkgname)
else:
to_install.append(pkgname)
else:
pkgstr = '{0}={1}'.format(pkgname, version_num)
cver = old.get(pkgname, '')
if reinstall and cver and salt.utils.versions.compare(
ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall.append(pkgstr)
elif not cver or salt.utils.versions.compare(
ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
to_install.append(pkgstr)
else:
if not kwargs.get('only_upgrade', False):
to_downgrade.append(pkgstr)
else:
# This should cause the command to fail.
to_install.append(pkgstr)
cmds = _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall)
if not cmds:
return {}
if refreshdb:
refresh_db()
errors = []
is_testmode = _is_testmode(**kwargs)
test_packages = {}
for cmd in cmds:
_execute_install_command(cmd, is_testmode, errors, test_packages)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if is_testmode:
new = copy.deepcopy(new)
new.update(test_packages)
ret = salt.utils.data.compare_dicts(old, new)
if pkg_type == 'file' and reinstall:
# For file-based packages, prepare 'to_reinstall' to have a list
# of all the package names that may have been reinstalled.
# This way, we could include reinstalled packages in 'ret'.
for pkgfile in to_install:
# Convert from file name to package name.
cmd = ['opkg', 'info', pkgfile]
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] == 0:
# Just need the package name.
pkginfo_dict = _process_info_installed_output(
out['stdout'], []
)
if pkginfo_dict:
to_reinstall.append(list(pkginfo_dict.keys())[0])
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def _parse_reported_packages_from_remove_output(output):
'''
Parses the output of "opkg remove" to determine what packages would have been
removed by an operation run with the --noaction flag.
We are looking for lines like
Removing <package> (<version>) from <Target>...
'''
reported_pkgs = {}
remove_pattern = re.compile(r'Removing\s(?P<package>.*?)\s\((?P<version>.*?)\)\sfrom\s(?P<target>.*?)...')
for line in salt.utils.itertools.split(output, '\n'):
match = remove_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = ''
return reported_pkgs
def remove(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Remove packages using ``opkg remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
remove_dependencies
Remove package and all dependencies
.. versionadded:: 2019.2.0
auto_remove_deps
Remove packages that were installed automatically to satisfy dependencies
.. versionadded:: 2019.2.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
salt '*' pkg.remove pkgs='["foo", "bar"]' remove_dependencies=True auto_remove_deps=True
'''
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 {}
cmd = ['opkg', 'remove']
_append_noaction_if_testmode(cmd, **kwargs)
if kwargs.get('remove_dependencies', False):
cmd.append('--force-removal-of-dependent-packages')
if kwargs.get('auto_remove_deps', False):
cmd.append('--autoremove')
cmd.extend(targets)
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors = [out['stderr']]
else:
errors = [out['stdout']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if _is_testmode(**kwargs):
reportedPkgs = _parse_reported_packages_from_remove_output(out['stdout'])
new = {k: v for k, v in new.items() if k not in reportedPkgs}
ret = salt.utils.data.compare_dicts(old, new)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def purge(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Package purges are not supported by opkg, this function is identical to
:mod:`pkg.remove <salt.modules.opkg.remove>`.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name, pkgs=pkgs)
def upgrade(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
Upgrades all packages via ``opkg upgrade``
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
errors = []
if salt.utils.data.is_true(refresh):
refresh_db()
old = list_pkgs()
cmd = ['opkg', 'upgrade']
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
errors.append(result)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif state != 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = _set_state(target, 'hold')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif state == 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret['comment'] = ('Package {0} is set not to be held.'
.format(target))
else:
result = _set_state(target, 'ok')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def _get_state(pkg):
'''
View package state from the opkg database
Return the state of pkg
'''
cmd = ['opkg', 'status']
cmd.append(pkg)
out = __salt__['cmd.run'](cmd, python_shell=False)
state_flag = ''
for line in salt.utils.itertools.split(out, '\n'):
if line.startswith('Status'):
_status, _state_want, state_flag, _state_status = line.split()
return state_flag
def _set_state(pkg, state):
'''
Change package state on the opkg database
The state can be any of:
- hold
- noprune
- user
- ok
- installed
- unpacked
This command is commonly used to mark a specific package to be held from
being upgraded, that is, to be kept at a certain version.
Returns a dict containing the package name, and the new and old
versions.
'''
ret = {}
valid_states = ('hold', 'noprune', 'user', 'ok', 'installed', 'unpacked')
if state not in valid_states:
raise SaltInvocationError('Invalid state: {0}'.format(state))
oldstate = _get_state(pkg)
cmd = ['opkg', 'flag']
cmd.append(state)
cmd.append(pkg)
_out = __salt__['cmd.run'](cmd, python_shell=False)
# Missing return value check due to opkg issue 160
ret[pkg] = {'old': oldstate,
'new': state}
return ret
def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
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
cmd = ['opkg', 'list-installed']
ret = {}
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
# This is a continuation of package description
if not line or line[0] == ' ':
continue
# This contains package name, version, and description.
# Extract the first two.
pkg_name, pkg_version = line.split(' - ', 2)[:2]
__salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version)
__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 list_upgrades(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
List all available package upgrades.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
ret = {}
if salt.utils.data.is_true(refresh):
refresh_db()
cmd = ['opkg', 'list-upgradable']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
if 'stdout' in call:
comment += call['stdout']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
name, _oldversion, newversion = line.split(' - ')
ret[name] = newversion
return ret
def _process_info_installed_output(out, filter_attrs):
'''
Helper function for info_installed()
Processes stdout output from a single invocation of
'opkg status'.
'''
ret = {}
name = None
attrs = {}
attr = None
for line in salt.utils.itertools.split(out, '\n'):
if line and line[0] == ' ':
# This is a continuation of the last attr
if filter_attrs is None or attr in filter_attrs:
line = line.strip()
if attrs[attr]:
# If attr is empty, don't add leading newline
attrs[attr] += '\n'
attrs[attr] += line
continue
line = line.strip()
if not line:
# Separator between different packages
if name:
ret[name] = attrs
name = None
attrs = {}
attr = None
continue
key, value = line.split(':', 1)
value = value.lstrip()
attr = _convert_to_standard_attr(key)
if attr == 'name':
name = value
elif filter_attrs is None or attr in filter_attrs:
attrs[attr] = value
if name:
ret[name] = attrs
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
.. versionadded:: 2017.7.0
:param names:
Names of the packages to get information about. If none are specified,
will return information for all installed packages.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
arch, conffiles, conflicts, depends, description, filename, group,
install_date_time_t, md5sum, packager, provides, recommends,
replaces, size, source, suggests, url, version
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed
salt '*' pkg.info_installed attr=version,packager
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> attr=version,packager
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,packager
'''
attr = kwargs.pop('attr', None)
if attr is None:
filter_attrs = None
elif isinstance(attr, six.string_types):
filter_attrs = set(attr.split(','))
else:
filter_attrs = set(attr)
ret = {}
if names:
# Specific list of names of installed packages
for name in names:
cmd = ['opkg', 'status', name]
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
else:
# All installed packages
cmd = ['opkg', 'status']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
return ret
def upgrade_available(name, **kwargs): # pylint: disable=unused-argument
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs): # pylint: disable=unused-argument
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2016.3.4
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0' '0.2.4.1-0'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] if ignore_epoch else six.text_type(x)
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
output = __salt__['cmd.run_stdout'](['opkg', '--version'],
output_loglevel='trace',
python_shell=False)
opkg_version = output.split(' ')[2].strip()
if salt.utils.versions.LooseVersion(opkg_version) >= \
salt.utils.versions.LooseVersion('0.3.4'):
cmd_compare = ['opkg', 'compare-versions']
elif salt.utils.path.which('opkg-compare-versions'):
cmd_compare = ['opkg-compare-versions']
else:
log.warning('Unable to find a compare-versions utility installed. Either upgrade opkg to '
'version > 0.3.4 (preferred) or install the older opkg-compare-versions script.')
return None
for oper, ret in (("<<", -1), ("=", 0), (">>", 1)):
cmd = cmd_compare[:]
cmd.append(_cmd_quote(pkg1))
cmd.append(oper)
cmd.append(_cmd_quote(pkg2))
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
ignore_retcode=True,
python_shell=False)
if retcode == 0:
return ret
return None
def _set_repo_option(repo, option):
'''
Set the option to repo
'''
if not option:
return
opt = option.split('=')
if len(opt) != 2:
return
if opt[0] == 'trusted':
repo['trusted'] = opt[1] == 'yes'
else:
repo[opt[0]] = opt[1]
def _set_repo_options(repo, options):
'''
Set the options to the repo.
'''
delimiters = "[", "]"
pattern = '|'.join(map(re.escape, delimiters))
for option in options:
splitted = re.split(pattern, option)
for opt in splitted:
_set_repo_option(repo, opt)
def _create_repo(line, filename):
'''
Create repo
'''
repo = {}
if line.startswith('#'):
repo['enabled'] = False
line = line[1:]
else:
repo['enabled'] = True
cols = salt.utils.args.shlex_split(line.strip())
repo['compressed'] = not cols[0] in 'src'
repo['name'] = cols[1]
repo['uri'] = cols[2]
repo['file'] = os.path.join(OPKG_CONFDIR, filename)
if len(cols) > 3:
_set_repo_options(repo, cols[3:])
return repo
def _read_repos(conf_file, repos, filename, regex):
'''
Read repos from configuration file
'''
for line in conf_file:
line = salt.utils.stringutils.to_unicode(line)
if not regex.search(line):
continue
repo = _create_repo(line, filename)
# do not store duplicated uri's
if repo['uri'] not in repos:
repos[repo['uri']] = [repo]
def list_repos(**kwargs): # pylint: disable=unused-argument
'''
Lists all repos on ``/etc/opkg/*.conf``
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos = {}
regex = re.compile(REPO_REGEXP)
for filename in os.listdir(OPKG_CONFDIR):
if not filename.endswith(".conf"):
continue
with salt.utils.files.fopen(os.path.join(OPKG_CONFDIR, filename)) as conf_file:
_read_repos(conf_file, repos, filename, regex)
return repos
def get_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Display a repo from the ``/etc/opkg/*.conf``
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo repo
'''
repos = list_repos()
if repos:
for source in six.itervalues(repos):
for sub in source:
if sub['name'] == repo:
return sub
return {}
def _del_repo_from_file(repo, filepath):
'''
Remove a repo from filepath
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
regex = re.compile(REPO_REGEXP)
for line in fhandle:
line = salt.utils.stringutils.to_unicode(line)
if regex.search(line):
if line.startswith('#'):
line = line[1:]
cols = salt.utils.args.shlex_split(line.strip())
if repo != cols[1]:
output.append(salt.utils.stringutils.to_str(line))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def _set_trusted_option_if_needed(repostr, trusted):
'''
Set trusted option to repo if needed
'''
if trusted is True:
repostr += ' [trusted=yes]'
elif trusted is False:
repostr += ' [trusted=no]'
return repostr
def _add_new_repo(repo, properties):
'''
Add a new repo entry
'''
repostr = '# ' if not properties.get('enabled') else ''
repostr += 'src/gz ' if properties.get('compressed') else 'src '
if ' ' in repo:
repostr += '"' + repo + '" '
else:
repostr += repo + ' '
repostr += properties.get('uri')
repostr = _set_trusted_option_if_needed(repostr, properties.get('trusted'))
repostr += '\n'
conffile = os.path.join(OPKG_CONFDIR, repo + '.conf')
with salt.utils.files.fopen(conffile, 'a') as fhandle:
fhandle.write(salt.utils.stringutils.to_str(repostr))
def _mod_repo_in_file(repo, repostr, filepath):
'''
Replace a repo entry in filepath with repostr
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
for line in fhandle:
cols = salt.utils.args.shlex_split(
salt.utils.stringutils.to_unicode(line).strip()
)
if repo not in cols:
output.append(line)
else:
output.append(salt.utils.stringutils.to_str(repostr + '\n'))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def del_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Delete a repo from ``/etc/opkg/*.conf``
If the file does not contain any other repo configuration, the file itself
will be deleted.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo repo
'''
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
repos = list_repos()
if repos:
deleted_from = dict()
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
deleted_from[source['file']] = 0
_del_repo_from_file(repo, source['file'])
if deleted_from:
ret = ''
for repository in repos:
source = repos[repository][0]
if source['file'] in deleted_from:
deleted_from[source['file']] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 1 and os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.\n')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
if refresh:
refresh_db()
return ret
return "Repo {0} doesn't exist in the opkg repo lists".format(repo)
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as uri is defined.
The following options are available to modify a repo definition:
repo
alias by which opkg refers to the repo.
uri
the URI to the repo.
compressed
defines (True or False) if the index file is compressed
enabled
enable or disable (True or False) repository
but do not remove if disabled.
refresh
enable or disable (True or False) auto-refresh of the repositories
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo repo uri=http://new/uri
salt '*' pkg.mod_repo repo enabled=False
'''
repos = list_repos()
found = False
uri = ''
if 'uri' in kwargs:
uri = kwargs['uri']
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
found = True
repostr = ''
if 'enabled' in kwargs and not kwargs['enabled']:
repostr += '# '
if 'compressed' in kwargs:
repostr += 'src/gz ' if kwargs['compressed'] else 'src'
else:
repostr += 'src/gz' if source['compressed'] else 'src'
repo_alias = kwargs['alias'] if 'alias' in kwargs else repo
if ' ' in repo_alias:
repostr += ' "{0}"'.format(repo_alias)
else:
repostr += ' {0}'.format(repo_alias)
repostr += ' {0}'.format(kwargs['uri'] if 'uri' in kwargs else source['uri'])
trusted = kwargs.get('trusted')
repostr = _set_trusted_option_if_needed(repostr, trusted) if trusted is not None else \
_set_trusted_option_if_needed(repostr, source.get('trusted'))
_mod_repo_in_file(repo, repostr, source['file'])
elif uri and source['uri'] == uri:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(uri, source['name']))
if not found:
# Need to add a new repo
if 'uri' not in kwargs:
raise CommandExecutionError(
'Repository \'{0}\' not found and no URI passed to create one.'.format(repo))
properties = {'uri': kwargs['uri']}
# If compressed is not defined, assume True
properties['compressed'] = kwargs['compressed'] if 'compressed' in kwargs else True
# If enabled is not defined, assume True
properties['enabled'] = kwargs['enabled'] if 'enabled' in kwargs else True
properties['trusted'] = kwargs.get('trusted')
_add_new_repo(repo, properties)
if 'refresh' in kwargs:
refresh_db()
def file_list(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
output = file_dict(*packages)
files = []
for package in list(output['packages'].values()):
files.extend(package)
return {'errors': output['errors'], 'files': files}
def file_dict(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
errors = []
ret = {}
cmd_files = ['opkg', 'files']
if not packages:
packages = list(list_pkgs().keys())
for package in packages:
files = []
cmd = cmd_files[:]
cmd.append(package)
out = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
for line in out['stdout'].splitlines():
if line.startswith('/'):
files.append(line)
elif line.startswith(' * '):
errors.append(line[3:])
break
else:
continue
if files:
ret[package] = files
return {'errors': errors, 'packages': ret}
def owner(*paths, **kwargs): # pylint: disable=unused-argument
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.opkg.version`, if a single
path is passed, a string will be returned, and if multiple paths are passed,
a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
cmd_search = ['opkg', 'search']
for path in paths:
cmd = cmd_search[:]
cmd.append(path)
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
if output:
ret[path] = output.split(' - ')[0].strip()
else:
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def version_clean(version):
'''
Clean the version string removing extra data.
There's nothing do to here for nipkg.py, therefore it will always
return the given version.
'''
return version
def check_extra_requirements(pkgname, pkgver):
'''
Check if the installed package already has the given requirements.
There's nothing do to here for nipkg.py, therefore it will always
return True.
'''
return True
|
saltstack/salt
|
salt/modules/opkg.py
|
_process_info_installed_output
|
python
|
def _process_info_installed_output(out, filter_attrs):
'''
Helper function for info_installed()
Processes stdout output from a single invocation of
'opkg status'.
'''
ret = {}
name = None
attrs = {}
attr = None
for line in salt.utils.itertools.split(out, '\n'):
if line and line[0] == ' ':
# This is a continuation of the last attr
if filter_attrs is None or attr in filter_attrs:
line = line.strip()
if attrs[attr]:
# If attr is empty, don't add leading newline
attrs[attr] += '\n'
attrs[attr] += line
continue
line = line.strip()
if not line:
# Separator between different packages
if name:
ret[name] = attrs
name = None
attrs = {}
attr = None
continue
key, value = line.split(':', 1)
value = value.lstrip()
attr = _convert_to_standard_attr(key)
if attr == 'name':
name = value
elif filter_attrs is None or attr in filter_attrs:
attrs[attr] = value
if name:
ret[name] = attrs
return ret
|
Helper function for info_installed()
Processes stdout output from a single invocation of
'opkg status'.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/opkg.py#L1068-L1109
|
[
"def split(orig, sep=None):\n '''\n Generator function for iterating through large strings, particularly useful\n as a replacement for str.splitlines().\n\n See http://stackoverflow.com/a/3865367\n '''\n exp = re.compile(r'\\s+' if sep is None else re.escape(sep))\n pos = 0\n length = len(orig)\n while True:\n match = exp.search(orig, pos)\n if not match:\n if pos < length or sep is not None:\n val = orig[pos:]\n if val:\n # Only yield a value if the slice was not an empty string,\n # because if it is then we've reached the end. This keeps\n # us from yielding an extra blank value at the end.\n yield val\n break\n if pos < match.start() or sep is not None:\n yield orig[pos:match.start()]\n pos = match.end()\n",
"def _convert_to_standard_attr(attr):\n '''\n Helper function for _process_info_installed_output()\n\n Converts an opkg attribute name to a standard attribute\n name which is used across 'pkg' modules.\n '''\n ret_attr = ATTR_MAP.get(attr, None)\n if ret_attr is None:\n # All others convert to lowercase\n return attr.lower()\n return ret_attr\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Opkg
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
.. versionadded: 2016.3.0
.. note::
For version comparison support on opkg < 0.3.4, the ``opkg-utils`` package
must be installed.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import os
import re
import logging
import errno
# Import salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.itertools
import salt.utils.path
import salt.utils.pkg
import salt.utils.stringutils
import salt.utils.versions
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import shlex_quote as _cmd_quote # pylint: disable=import-error
from salt.ext.six.moves import map # pylint: disable=import-error,redefined-builtin
REPO_REGEXP = r'^#?\s*(src|src/gz)\s+([^\s<>]+|"[^<>]+")\s+[^\s<>]+'
OPKG_CONFDIR = '/etc/opkg'
ATTR_MAP = {
'Architecture': 'arch',
'Homepage': 'url',
'Installed-Time': 'install_date_time_t',
'Maintainer': 'packager',
'Package': 'name',
'Section': 'group'
}
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
NILRT_RESTARTCHECK_STATE_PATH = '/var/lib/salt/restartcheck_state'
def _update_nilrt_restart_state():
'''
NILRT systems determine whether to reboot after various package operations
including but not limited to kernel module installs/removals by checking
specific file md5sums & timestamps. These files are touched/modified by
the post-install/post-remove functions of their respective packages.
The opkg module uses this function to store/update those file timestamps
and checksums to be used later by the restartcheck module.
'''
__salt__['cmd.shell']('stat -c %Y /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.timestamp'
.format(NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.md5sum'
.format(NILRT_RESTARTCHECK_STATE_PATH))
# We can't assume nisysapi.ini always exists like modules.dep
nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'
if os.path.exists(nisysapi_path):
__salt__['cmd.shell']('stat -c %Y {0} >{1}/nisysapi.ini.timestamp'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0} >{1}/nisysapi.ini.md5sum'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
# Expert plugin files get added to a conf.d dir, so keep track of the total
# no. of files, their timestamps and content hashes
nisysapi_conf_d_path = "/usr/lib/{0}/nisysapi/conf.d/experts/".format(
'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'
)
if os.path.exists(nisysapi_conf_d_path):
with salt.utils.files.fopen('{0}/sysapi.conf.d.count'.format(
NILRT_RESTARTCHECK_STATE_PATH), 'w') as fcount:
fcount.write(str(len(os.listdir(nisysapi_conf_d_path))))
for fexpert in os.listdir(nisysapi_conf_d_path):
__salt__['cmd.shell']('stat -c %Y {0}/{1} >{2}/{1}.timestamp'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0}/{1} >{2}/{1}.md5sum'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
def _get_restartcheck_result(errors):
'''
Return restartcheck result and append errors (if any) to ``errors``
'''
rs_result = __salt__['restartcheck.restartcheck'](verbose=False)
if isinstance(rs_result, dict) and 'comment' in rs_result:
errors.append(rs_result['comment'])
return rs_result
def _process_restartcheck_result(rs_result, **kwargs):
'''
Check restartcheck output to see if system/service restarts were requested
and take appropriate action.
'''
if 'No packages seem to need to be restarted' in rs_result:
return
reboot_required = False
for rstr in rs_result:
if 'System restart required' in rstr:
_update_nilrt_restart_state()
__salt__['system.set_reboot_required_witnessed']()
reboot_required = True
if kwargs.get('always_restart_services', True) or not reboot_required:
for rstr in rs_result:
if 'System restart required' not in rstr:
service = os.path.join('/etc/init.d', rstr)
if os.path.exists(service):
__salt__['cmd.run']([service, 'restart'])
def __virtual__():
'''
Confirm this module is on a nilrt based system
'''
if __grains__.get('os_family') == 'NILinuxRT':
try:
os.makedirs(NILRT_RESTARTCHECK_STATE_PATH)
except OSError as exc:
if exc.errno != errno.EEXIST:
return False, 'Error creating {0} (-{1}): {2}'.format(
NILRT_RESTARTCHECK_STATE_PATH,
exc.errno,
exc.strerror)
# populate state dir if empty
if not os.listdir(NILRT_RESTARTCHECK_STATE_PATH):
_update_nilrt_restart_state()
return __virtualname__
if os.path.isdir(OPKG_CONFDIR):
return __virtualname__
return False, "Module opkg only works on OpenEmbedded based systems"
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
if not names:
return ''
ret = {}
for name in names:
ret[name] = ''
# Refresh before looking for the latest version available
if refresh:
refresh_db()
cmd = ['opkg', 'list-upgradable']
out = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
try:
name, _oldversion, newversion = line.split(' - ')
if name in names:
ret[name] = newversion
except ValueError:
pass
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = latest_version
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(failhard=False, **kwargs): # pylint: disable=unused-argument
'''
Updates the opkg database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
failhard
If False, return results of failed lines as ``False`` for the package
database that encountered the error.
If True, raise an error with a list of the package databases that
encountered errors.
.. versionadded:: 2018.3.0
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
error_repos = []
cmd = ['opkg', 'update']
# opkg returns a non-zero retcode when there is a failure to refresh
# from one or more repos. Due to this, ignore the retcode.
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True,
redirect_stderr=True)
out = call['stdout']
prev_line = ''
for line in salt.utils.itertools.split(out, '\n'):
if 'Inflating' in line:
key = line.strip().split()[1][:-1]
ret[key] = True
elif 'Updated source' in line:
# Use the previous line.
key = prev_line.strip().split()[1][:-1]
ret[key] = True
elif 'Failed to download' in line:
key = line.strip().split()[5].split(',')[0]
ret[key] = False
error_repos.append(key)
prev_line = line
if failhard and error_repos:
raise CommandExecutionError(
'Error getting repos: {0}'.format(', '.join(error_repos))
)
# On a non-zero exit code where no failed repos were found, raise an
# exception because this appears to be a different kind of error.
if call['retcode'] != 0 and not error_repos:
raise CommandExecutionError(out)
return ret
def _is_testmode(**kwargs):
'''
Returns whether a test mode (noaction) operation was requested.
'''
return bool(kwargs.get('test') or __opts__.get('test'))
def _append_noaction_if_testmode(cmd, **kwargs):
'''
Adds the --noaction flag to the command if it's running in the test mode.
'''
if _is_testmode(**kwargs):
cmd.append('--noaction')
def _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall):
'''
Builds a list of install commands to be executed in sequence in order to process
each of the to_install, to_downgrade, and to_reinstall lists.
'''
cmds = []
if to_install:
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(to_install)
cmds.append(cmd)
if to_downgrade:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-downgrade')
cmd.extend(to_downgrade)
cmds.append(cmd)
if to_reinstall:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-reinstall')
cmd.extend(to_reinstall)
cmds.append(cmd)
return cmds
def _parse_reported_packages_from_install_output(output):
'''
Parses the output of "opkg install" to determine what packages would have been
installed by an operation run with the --noaction flag.
We are looking for lines like:
Installing <package> (<version>) on <target>
or
Upgrading <package> from <oldVersion> to <version> on root
'''
reported_pkgs = {}
install_pattern = re.compile(r'Installing\s(?P<package>.*?)\s\((?P<version>.*?)\)\son\s(?P<target>.*?)')
upgrade_pattern = re.compile(r'Upgrading\s(?P<package>.*?)\sfrom\s(?P<oldVersion>.*?)\sto\s(?P<version>.*?)\son\s(?P<target>.*?)')
for line in salt.utils.itertools.split(output, '\n'):
match = install_pattern.match(line)
if match is None:
match = upgrade_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = match.group('version')
return reported_pkgs
def _execute_install_command(cmd, parse_output, errors, parsed_packages):
'''
Executes a command for the install operation.
If the command fails, its error output will be appended to the errors list.
If the command succeeds and parse_output is true, updated packages will be appended
to the parsed_packages dictionary.
'''
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors.append(out['stderr'])
else:
errors.append(out['stdout'])
elif parse_output:
parsed_packages.update(_parse_reported_packages_from_install_output(out['stdout']))
def install(name=None,
refresh=False,
pkgs=None,
sources=None,
reinstall=False,
**kwargs):
'''
Install the passed package, add refresh=True to update the opkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionadded:: 2017.7.0
reinstall : False
Specifying reinstall=True will use ``opkg install --force-reinstall``
rather than simply ``opkg install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``opkg
install --force-reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2017.7.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of IPK packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
install_recommends
Whether to install the packages marked as recommended. Default is True.
only_upgrade
Only upgrade the packages (disallow downgrades), if they are already
installed. Default is False.
.. versionadded:: 2017.7.0
always_restart_services
Whether to restart services even if a reboot is required. Default is True.
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
refreshdb = salt.utils.data.is_true(refresh)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
cmd_prefix = ['opkg', 'install']
to_install = []
to_reinstall = []
to_downgrade = []
_append_noaction_if_testmode(cmd_prefix, **kwargs)
if not pkg_params:
return {}
elif pkg_type == 'file':
if reinstall:
cmd_prefix.append('--force-reinstall')
if not kwargs.get('only_upgrade', False):
cmd_prefix.append('--force-downgrade')
to_install.extend(pkg_params)
elif pkg_type == 'repository':
if not kwargs.get('install_recommends', True):
cmd_prefix.append('--no-install-recommends')
for pkgname, pkgversion in six.iteritems(pkg_params):
if (name and pkgs is None and kwargs.get('version') and
len(pkg_params) == 1):
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
version_num = pkgversion
if version_num is None:
# Don't allow downgrades if the version
# number is not specified.
if reinstall and pkgname in old:
to_reinstall.append(pkgname)
else:
to_install.append(pkgname)
else:
pkgstr = '{0}={1}'.format(pkgname, version_num)
cver = old.get(pkgname, '')
if reinstall and cver and salt.utils.versions.compare(
ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall.append(pkgstr)
elif not cver or salt.utils.versions.compare(
ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
to_install.append(pkgstr)
else:
if not kwargs.get('only_upgrade', False):
to_downgrade.append(pkgstr)
else:
# This should cause the command to fail.
to_install.append(pkgstr)
cmds = _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall)
if not cmds:
return {}
if refreshdb:
refresh_db()
errors = []
is_testmode = _is_testmode(**kwargs)
test_packages = {}
for cmd in cmds:
_execute_install_command(cmd, is_testmode, errors, test_packages)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if is_testmode:
new = copy.deepcopy(new)
new.update(test_packages)
ret = salt.utils.data.compare_dicts(old, new)
if pkg_type == 'file' and reinstall:
# For file-based packages, prepare 'to_reinstall' to have a list
# of all the package names that may have been reinstalled.
# This way, we could include reinstalled packages in 'ret'.
for pkgfile in to_install:
# Convert from file name to package name.
cmd = ['opkg', 'info', pkgfile]
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] == 0:
# Just need the package name.
pkginfo_dict = _process_info_installed_output(
out['stdout'], []
)
if pkginfo_dict:
to_reinstall.append(list(pkginfo_dict.keys())[0])
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def _parse_reported_packages_from_remove_output(output):
'''
Parses the output of "opkg remove" to determine what packages would have been
removed by an operation run with the --noaction flag.
We are looking for lines like
Removing <package> (<version>) from <Target>...
'''
reported_pkgs = {}
remove_pattern = re.compile(r'Removing\s(?P<package>.*?)\s\((?P<version>.*?)\)\sfrom\s(?P<target>.*?)...')
for line in salt.utils.itertools.split(output, '\n'):
match = remove_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = ''
return reported_pkgs
def remove(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Remove packages using ``opkg remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
remove_dependencies
Remove package and all dependencies
.. versionadded:: 2019.2.0
auto_remove_deps
Remove packages that were installed automatically to satisfy dependencies
.. versionadded:: 2019.2.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
salt '*' pkg.remove pkgs='["foo", "bar"]' remove_dependencies=True auto_remove_deps=True
'''
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 {}
cmd = ['opkg', 'remove']
_append_noaction_if_testmode(cmd, **kwargs)
if kwargs.get('remove_dependencies', False):
cmd.append('--force-removal-of-dependent-packages')
if kwargs.get('auto_remove_deps', False):
cmd.append('--autoremove')
cmd.extend(targets)
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors = [out['stderr']]
else:
errors = [out['stdout']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if _is_testmode(**kwargs):
reportedPkgs = _parse_reported_packages_from_remove_output(out['stdout'])
new = {k: v for k, v in new.items() if k not in reportedPkgs}
ret = salt.utils.data.compare_dicts(old, new)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def purge(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Package purges are not supported by opkg, this function is identical to
:mod:`pkg.remove <salt.modules.opkg.remove>`.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name, pkgs=pkgs)
def upgrade(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
Upgrades all packages via ``opkg upgrade``
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
errors = []
if salt.utils.data.is_true(refresh):
refresh_db()
old = list_pkgs()
cmd = ['opkg', 'upgrade']
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
errors.append(result)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif state != 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = _set_state(target, 'hold')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif state == 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret['comment'] = ('Package {0} is set not to be held.'
.format(target))
else:
result = _set_state(target, 'ok')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def _get_state(pkg):
'''
View package state from the opkg database
Return the state of pkg
'''
cmd = ['opkg', 'status']
cmd.append(pkg)
out = __salt__['cmd.run'](cmd, python_shell=False)
state_flag = ''
for line in salt.utils.itertools.split(out, '\n'):
if line.startswith('Status'):
_status, _state_want, state_flag, _state_status = line.split()
return state_flag
def _set_state(pkg, state):
'''
Change package state on the opkg database
The state can be any of:
- hold
- noprune
- user
- ok
- installed
- unpacked
This command is commonly used to mark a specific package to be held from
being upgraded, that is, to be kept at a certain version.
Returns a dict containing the package name, and the new and old
versions.
'''
ret = {}
valid_states = ('hold', 'noprune', 'user', 'ok', 'installed', 'unpacked')
if state not in valid_states:
raise SaltInvocationError('Invalid state: {0}'.format(state))
oldstate = _get_state(pkg)
cmd = ['opkg', 'flag']
cmd.append(state)
cmd.append(pkg)
_out = __salt__['cmd.run'](cmd, python_shell=False)
# Missing return value check due to opkg issue 160
ret[pkg] = {'old': oldstate,
'new': state}
return ret
def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
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
cmd = ['opkg', 'list-installed']
ret = {}
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
# This is a continuation of package description
if not line or line[0] == ' ':
continue
# This contains package name, version, and description.
# Extract the first two.
pkg_name, pkg_version = line.split(' - ', 2)[:2]
__salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version)
__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 list_upgrades(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
List all available package upgrades.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
ret = {}
if salt.utils.data.is_true(refresh):
refresh_db()
cmd = ['opkg', 'list-upgradable']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
if 'stdout' in call:
comment += call['stdout']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
name, _oldversion, newversion = line.split(' - ')
ret[name] = newversion
return ret
def _convert_to_standard_attr(attr):
'''
Helper function for _process_info_installed_output()
Converts an opkg attribute name to a standard attribute
name which is used across 'pkg' modules.
'''
ret_attr = ATTR_MAP.get(attr, None)
if ret_attr is None:
# All others convert to lowercase
return attr.lower()
return ret_attr
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
.. versionadded:: 2017.7.0
:param names:
Names of the packages to get information about. If none are specified,
will return information for all installed packages.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
arch, conffiles, conflicts, depends, description, filename, group,
install_date_time_t, md5sum, packager, provides, recommends,
replaces, size, source, suggests, url, version
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed
salt '*' pkg.info_installed attr=version,packager
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> attr=version,packager
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,packager
'''
attr = kwargs.pop('attr', None)
if attr is None:
filter_attrs = None
elif isinstance(attr, six.string_types):
filter_attrs = set(attr.split(','))
else:
filter_attrs = set(attr)
ret = {}
if names:
# Specific list of names of installed packages
for name in names:
cmd = ['opkg', 'status', name]
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
else:
# All installed packages
cmd = ['opkg', 'status']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
return ret
def upgrade_available(name, **kwargs): # pylint: disable=unused-argument
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs): # pylint: disable=unused-argument
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2016.3.4
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0' '0.2.4.1-0'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] if ignore_epoch else six.text_type(x)
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
output = __salt__['cmd.run_stdout'](['opkg', '--version'],
output_loglevel='trace',
python_shell=False)
opkg_version = output.split(' ')[2].strip()
if salt.utils.versions.LooseVersion(opkg_version) >= \
salt.utils.versions.LooseVersion('0.3.4'):
cmd_compare = ['opkg', 'compare-versions']
elif salt.utils.path.which('opkg-compare-versions'):
cmd_compare = ['opkg-compare-versions']
else:
log.warning('Unable to find a compare-versions utility installed. Either upgrade opkg to '
'version > 0.3.4 (preferred) or install the older opkg-compare-versions script.')
return None
for oper, ret in (("<<", -1), ("=", 0), (">>", 1)):
cmd = cmd_compare[:]
cmd.append(_cmd_quote(pkg1))
cmd.append(oper)
cmd.append(_cmd_quote(pkg2))
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
ignore_retcode=True,
python_shell=False)
if retcode == 0:
return ret
return None
def _set_repo_option(repo, option):
'''
Set the option to repo
'''
if not option:
return
opt = option.split('=')
if len(opt) != 2:
return
if opt[0] == 'trusted':
repo['trusted'] = opt[1] == 'yes'
else:
repo[opt[0]] = opt[1]
def _set_repo_options(repo, options):
'''
Set the options to the repo.
'''
delimiters = "[", "]"
pattern = '|'.join(map(re.escape, delimiters))
for option in options:
splitted = re.split(pattern, option)
for opt in splitted:
_set_repo_option(repo, opt)
def _create_repo(line, filename):
'''
Create repo
'''
repo = {}
if line.startswith('#'):
repo['enabled'] = False
line = line[1:]
else:
repo['enabled'] = True
cols = salt.utils.args.shlex_split(line.strip())
repo['compressed'] = not cols[0] in 'src'
repo['name'] = cols[1]
repo['uri'] = cols[2]
repo['file'] = os.path.join(OPKG_CONFDIR, filename)
if len(cols) > 3:
_set_repo_options(repo, cols[3:])
return repo
def _read_repos(conf_file, repos, filename, regex):
'''
Read repos from configuration file
'''
for line in conf_file:
line = salt.utils.stringutils.to_unicode(line)
if not regex.search(line):
continue
repo = _create_repo(line, filename)
# do not store duplicated uri's
if repo['uri'] not in repos:
repos[repo['uri']] = [repo]
def list_repos(**kwargs): # pylint: disable=unused-argument
'''
Lists all repos on ``/etc/opkg/*.conf``
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos = {}
regex = re.compile(REPO_REGEXP)
for filename in os.listdir(OPKG_CONFDIR):
if not filename.endswith(".conf"):
continue
with salt.utils.files.fopen(os.path.join(OPKG_CONFDIR, filename)) as conf_file:
_read_repos(conf_file, repos, filename, regex)
return repos
def get_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Display a repo from the ``/etc/opkg/*.conf``
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo repo
'''
repos = list_repos()
if repos:
for source in six.itervalues(repos):
for sub in source:
if sub['name'] == repo:
return sub
return {}
def _del_repo_from_file(repo, filepath):
'''
Remove a repo from filepath
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
regex = re.compile(REPO_REGEXP)
for line in fhandle:
line = salt.utils.stringutils.to_unicode(line)
if regex.search(line):
if line.startswith('#'):
line = line[1:]
cols = salt.utils.args.shlex_split(line.strip())
if repo != cols[1]:
output.append(salt.utils.stringutils.to_str(line))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def _set_trusted_option_if_needed(repostr, trusted):
'''
Set trusted option to repo if needed
'''
if trusted is True:
repostr += ' [trusted=yes]'
elif trusted is False:
repostr += ' [trusted=no]'
return repostr
def _add_new_repo(repo, properties):
'''
Add a new repo entry
'''
repostr = '# ' if not properties.get('enabled') else ''
repostr += 'src/gz ' if properties.get('compressed') else 'src '
if ' ' in repo:
repostr += '"' + repo + '" '
else:
repostr += repo + ' '
repostr += properties.get('uri')
repostr = _set_trusted_option_if_needed(repostr, properties.get('trusted'))
repostr += '\n'
conffile = os.path.join(OPKG_CONFDIR, repo + '.conf')
with salt.utils.files.fopen(conffile, 'a') as fhandle:
fhandle.write(salt.utils.stringutils.to_str(repostr))
def _mod_repo_in_file(repo, repostr, filepath):
'''
Replace a repo entry in filepath with repostr
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
for line in fhandle:
cols = salt.utils.args.shlex_split(
salt.utils.stringutils.to_unicode(line).strip()
)
if repo not in cols:
output.append(line)
else:
output.append(salt.utils.stringutils.to_str(repostr + '\n'))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def del_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Delete a repo from ``/etc/opkg/*.conf``
If the file does not contain any other repo configuration, the file itself
will be deleted.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo repo
'''
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
repos = list_repos()
if repos:
deleted_from = dict()
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
deleted_from[source['file']] = 0
_del_repo_from_file(repo, source['file'])
if deleted_from:
ret = ''
for repository in repos:
source = repos[repository][0]
if source['file'] in deleted_from:
deleted_from[source['file']] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 1 and os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.\n')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
if refresh:
refresh_db()
return ret
return "Repo {0} doesn't exist in the opkg repo lists".format(repo)
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as uri is defined.
The following options are available to modify a repo definition:
repo
alias by which opkg refers to the repo.
uri
the URI to the repo.
compressed
defines (True or False) if the index file is compressed
enabled
enable or disable (True or False) repository
but do not remove if disabled.
refresh
enable or disable (True or False) auto-refresh of the repositories
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo repo uri=http://new/uri
salt '*' pkg.mod_repo repo enabled=False
'''
repos = list_repos()
found = False
uri = ''
if 'uri' in kwargs:
uri = kwargs['uri']
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
found = True
repostr = ''
if 'enabled' in kwargs and not kwargs['enabled']:
repostr += '# '
if 'compressed' in kwargs:
repostr += 'src/gz ' if kwargs['compressed'] else 'src'
else:
repostr += 'src/gz' if source['compressed'] else 'src'
repo_alias = kwargs['alias'] if 'alias' in kwargs else repo
if ' ' in repo_alias:
repostr += ' "{0}"'.format(repo_alias)
else:
repostr += ' {0}'.format(repo_alias)
repostr += ' {0}'.format(kwargs['uri'] if 'uri' in kwargs else source['uri'])
trusted = kwargs.get('trusted')
repostr = _set_trusted_option_if_needed(repostr, trusted) if trusted is not None else \
_set_trusted_option_if_needed(repostr, source.get('trusted'))
_mod_repo_in_file(repo, repostr, source['file'])
elif uri and source['uri'] == uri:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(uri, source['name']))
if not found:
# Need to add a new repo
if 'uri' not in kwargs:
raise CommandExecutionError(
'Repository \'{0}\' not found and no URI passed to create one.'.format(repo))
properties = {'uri': kwargs['uri']}
# If compressed is not defined, assume True
properties['compressed'] = kwargs['compressed'] if 'compressed' in kwargs else True
# If enabled is not defined, assume True
properties['enabled'] = kwargs['enabled'] if 'enabled' in kwargs else True
properties['trusted'] = kwargs.get('trusted')
_add_new_repo(repo, properties)
if 'refresh' in kwargs:
refresh_db()
def file_list(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
output = file_dict(*packages)
files = []
for package in list(output['packages'].values()):
files.extend(package)
return {'errors': output['errors'], 'files': files}
def file_dict(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
errors = []
ret = {}
cmd_files = ['opkg', 'files']
if not packages:
packages = list(list_pkgs().keys())
for package in packages:
files = []
cmd = cmd_files[:]
cmd.append(package)
out = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
for line in out['stdout'].splitlines():
if line.startswith('/'):
files.append(line)
elif line.startswith(' * '):
errors.append(line[3:])
break
else:
continue
if files:
ret[package] = files
return {'errors': errors, 'packages': ret}
def owner(*paths, **kwargs): # pylint: disable=unused-argument
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.opkg.version`, if a single
path is passed, a string will be returned, and if multiple paths are passed,
a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
cmd_search = ['opkg', 'search']
for path in paths:
cmd = cmd_search[:]
cmd.append(path)
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
if output:
ret[path] = output.split(' - ')[0].strip()
else:
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def version_clean(version):
'''
Clean the version string removing extra data.
There's nothing do to here for nipkg.py, therefore it will always
return the given version.
'''
return version
def check_extra_requirements(pkgname, pkgver):
'''
Check if the installed package already has the given requirements.
There's nothing do to here for nipkg.py, therefore it will always
return True.
'''
return True
|
saltstack/salt
|
salt/modules/opkg.py
|
info_installed
|
python
|
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
.. versionadded:: 2017.7.0
:param names:
Names of the packages to get information about. If none are specified,
will return information for all installed packages.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
arch, conffiles, conflicts, depends, description, filename, group,
install_date_time_t, md5sum, packager, provides, recommends,
replaces, size, source, suggests, url, version
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed
salt '*' pkg.info_installed attr=version,packager
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> attr=version,packager
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,packager
'''
attr = kwargs.pop('attr', None)
if attr is None:
filter_attrs = None
elif isinstance(attr, six.string_types):
filter_attrs = set(attr.split(','))
else:
filter_attrs = set(attr)
ret = {}
if names:
# Specific list of names of installed packages
for name in names:
cmd = ['opkg', 'status', name]
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
else:
# All installed packages
cmd = ['opkg', 'status']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
return ret
|
Return the information of the named package(s), installed on the system.
.. versionadded:: 2017.7.0
:param names:
Names of the packages to get information about. If none are specified,
will return information for all installed packages.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
arch, conffiles, conflicts, depends, description, filename, group,
install_date_time_t, md5sum, packager, provides, recommends,
replaces, size, source, suggests, url, version
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed
salt '*' pkg.info_installed attr=version,packager
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> attr=version,packager
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,packager
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/opkg.py#L1112-L1182
|
[
"def _process_info_installed_output(out, filter_attrs):\n '''\n Helper function for info_installed()\n\n Processes stdout output from a single invocation of\n 'opkg status'.\n '''\n ret = {}\n name = None\n attrs = {}\n attr = None\n\n for line in salt.utils.itertools.split(out, '\\n'):\n if line and line[0] == ' ':\n # This is a continuation of the last attr\n if filter_attrs is None or attr in filter_attrs:\n line = line.strip()\n if attrs[attr]:\n # If attr is empty, don't add leading newline\n attrs[attr] += '\\n'\n attrs[attr] += line\n continue\n line = line.strip()\n if not line:\n # Separator between different packages\n if name:\n ret[name] = attrs\n name = None\n attrs = {}\n attr = None\n continue\n key, value = line.split(':', 1)\n value = value.lstrip()\n attr = _convert_to_standard_attr(key)\n if attr == 'name':\n name = value\n elif filter_attrs is None or attr in filter_attrs:\n attrs[attr] = value\n\n if name:\n ret[name] = attrs\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Opkg
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
.. versionadded: 2016.3.0
.. note::
For version comparison support on opkg < 0.3.4, the ``opkg-utils`` package
must be installed.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import os
import re
import logging
import errno
# Import salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.itertools
import salt.utils.path
import salt.utils.pkg
import salt.utils.stringutils
import salt.utils.versions
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import shlex_quote as _cmd_quote # pylint: disable=import-error
from salt.ext.six.moves import map # pylint: disable=import-error,redefined-builtin
REPO_REGEXP = r'^#?\s*(src|src/gz)\s+([^\s<>]+|"[^<>]+")\s+[^\s<>]+'
OPKG_CONFDIR = '/etc/opkg'
ATTR_MAP = {
'Architecture': 'arch',
'Homepage': 'url',
'Installed-Time': 'install_date_time_t',
'Maintainer': 'packager',
'Package': 'name',
'Section': 'group'
}
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
NILRT_RESTARTCHECK_STATE_PATH = '/var/lib/salt/restartcheck_state'
def _update_nilrt_restart_state():
'''
NILRT systems determine whether to reboot after various package operations
including but not limited to kernel module installs/removals by checking
specific file md5sums & timestamps. These files are touched/modified by
the post-install/post-remove functions of their respective packages.
The opkg module uses this function to store/update those file timestamps
and checksums to be used later by the restartcheck module.
'''
__salt__['cmd.shell']('stat -c %Y /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.timestamp'
.format(NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.md5sum'
.format(NILRT_RESTARTCHECK_STATE_PATH))
# We can't assume nisysapi.ini always exists like modules.dep
nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'
if os.path.exists(nisysapi_path):
__salt__['cmd.shell']('stat -c %Y {0} >{1}/nisysapi.ini.timestamp'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0} >{1}/nisysapi.ini.md5sum'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
# Expert plugin files get added to a conf.d dir, so keep track of the total
# no. of files, their timestamps and content hashes
nisysapi_conf_d_path = "/usr/lib/{0}/nisysapi/conf.d/experts/".format(
'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'
)
if os.path.exists(nisysapi_conf_d_path):
with salt.utils.files.fopen('{0}/sysapi.conf.d.count'.format(
NILRT_RESTARTCHECK_STATE_PATH), 'w') as fcount:
fcount.write(str(len(os.listdir(nisysapi_conf_d_path))))
for fexpert in os.listdir(nisysapi_conf_d_path):
__salt__['cmd.shell']('stat -c %Y {0}/{1} >{2}/{1}.timestamp'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0}/{1} >{2}/{1}.md5sum'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
def _get_restartcheck_result(errors):
'''
Return restartcheck result and append errors (if any) to ``errors``
'''
rs_result = __salt__['restartcheck.restartcheck'](verbose=False)
if isinstance(rs_result, dict) and 'comment' in rs_result:
errors.append(rs_result['comment'])
return rs_result
def _process_restartcheck_result(rs_result, **kwargs):
'''
Check restartcheck output to see if system/service restarts were requested
and take appropriate action.
'''
if 'No packages seem to need to be restarted' in rs_result:
return
reboot_required = False
for rstr in rs_result:
if 'System restart required' in rstr:
_update_nilrt_restart_state()
__salt__['system.set_reboot_required_witnessed']()
reboot_required = True
if kwargs.get('always_restart_services', True) or not reboot_required:
for rstr in rs_result:
if 'System restart required' not in rstr:
service = os.path.join('/etc/init.d', rstr)
if os.path.exists(service):
__salt__['cmd.run']([service, 'restart'])
def __virtual__():
'''
Confirm this module is on a nilrt based system
'''
if __grains__.get('os_family') == 'NILinuxRT':
try:
os.makedirs(NILRT_RESTARTCHECK_STATE_PATH)
except OSError as exc:
if exc.errno != errno.EEXIST:
return False, 'Error creating {0} (-{1}): {2}'.format(
NILRT_RESTARTCHECK_STATE_PATH,
exc.errno,
exc.strerror)
# populate state dir if empty
if not os.listdir(NILRT_RESTARTCHECK_STATE_PATH):
_update_nilrt_restart_state()
return __virtualname__
if os.path.isdir(OPKG_CONFDIR):
return __virtualname__
return False, "Module opkg only works on OpenEmbedded based systems"
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
if not names:
return ''
ret = {}
for name in names:
ret[name] = ''
# Refresh before looking for the latest version available
if refresh:
refresh_db()
cmd = ['opkg', 'list-upgradable']
out = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
try:
name, _oldversion, newversion = line.split(' - ')
if name in names:
ret[name] = newversion
except ValueError:
pass
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = latest_version
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(failhard=False, **kwargs): # pylint: disable=unused-argument
'''
Updates the opkg database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
failhard
If False, return results of failed lines as ``False`` for the package
database that encountered the error.
If True, raise an error with a list of the package databases that
encountered errors.
.. versionadded:: 2018.3.0
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
error_repos = []
cmd = ['opkg', 'update']
# opkg returns a non-zero retcode when there is a failure to refresh
# from one or more repos. Due to this, ignore the retcode.
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True,
redirect_stderr=True)
out = call['stdout']
prev_line = ''
for line in salt.utils.itertools.split(out, '\n'):
if 'Inflating' in line:
key = line.strip().split()[1][:-1]
ret[key] = True
elif 'Updated source' in line:
# Use the previous line.
key = prev_line.strip().split()[1][:-1]
ret[key] = True
elif 'Failed to download' in line:
key = line.strip().split()[5].split(',')[0]
ret[key] = False
error_repos.append(key)
prev_line = line
if failhard and error_repos:
raise CommandExecutionError(
'Error getting repos: {0}'.format(', '.join(error_repos))
)
# On a non-zero exit code where no failed repos were found, raise an
# exception because this appears to be a different kind of error.
if call['retcode'] != 0 and not error_repos:
raise CommandExecutionError(out)
return ret
def _is_testmode(**kwargs):
'''
Returns whether a test mode (noaction) operation was requested.
'''
return bool(kwargs.get('test') or __opts__.get('test'))
def _append_noaction_if_testmode(cmd, **kwargs):
'''
Adds the --noaction flag to the command if it's running in the test mode.
'''
if _is_testmode(**kwargs):
cmd.append('--noaction')
def _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall):
'''
Builds a list of install commands to be executed in sequence in order to process
each of the to_install, to_downgrade, and to_reinstall lists.
'''
cmds = []
if to_install:
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(to_install)
cmds.append(cmd)
if to_downgrade:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-downgrade')
cmd.extend(to_downgrade)
cmds.append(cmd)
if to_reinstall:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-reinstall')
cmd.extend(to_reinstall)
cmds.append(cmd)
return cmds
def _parse_reported_packages_from_install_output(output):
'''
Parses the output of "opkg install" to determine what packages would have been
installed by an operation run with the --noaction flag.
We are looking for lines like:
Installing <package> (<version>) on <target>
or
Upgrading <package> from <oldVersion> to <version> on root
'''
reported_pkgs = {}
install_pattern = re.compile(r'Installing\s(?P<package>.*?)\s\((?P<version>.*?)\)\son\s(?P<target>.*?)')
upgrade_pattern = re.compile(r'Upgrading\s(?P<package>.*?)\sfrom\s(?P<oldVersion>.*?)\sto\s(?P<version>.*?)\son\s(?P<target>.*?)')
for line in salt.utils.itertools.split(output, '\n'):
match = install_pattern.match(line)
if match is None:
match = upgrade_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = match.group('version')
return reported_pkgs
def _execute_install_command(cmd, parse_output, errors, parsed_packages):
'''
Executes a command for the install operation.
If the command fails, its error output will be appended to the errors list.
If the command succeeds and parse_output is true, updated packages will be appended
to the parsed_packages dictionary.
'''
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors.append(out['stderr'])
else:
errors.append(out['stdout'])
elif parse_output:
parsed_packages.update(_parse_reported_packages_from_install_output(out['stdout']))
def install(name=None,
refresh=False,
pkgs=None,
sources=None,
reinstall=False,
**kwargs):
'''
Install the passed package, add refresh=True to update the opkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionadded:: 2017.7.0
reinstall : False
Specifying reinstall=True will use ``opkg install --force-reinstall``
rather than simply ``opkg install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``opkg
install --force-reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2017.7.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of IPK packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
install_recommends
Whether to install the packages marked as recommended. Default is True.
only_upgrade
Only upgrade the packages (disallow downgrades), if they are already
installed. Default is False.
.. versionadded:: 2017.7.0
always_restart_services
Whether to restart services even if a reboot is required. Default is True.
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
refreshdb = salt.utils.data.is_true(refresh)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
cmd_prefix = ['opkg', 'install']
to_install = []
to_reinstall = []
to_downgrade = []
_append_noaction_if_testmode(cmd_prefix, **kwargs)
if not pkg_params:
return {}
elif pkg_type == 'file':
if reinstall:
cmd_prefix.append('--force-reinstall')
if not kwargs.get('only_upgrade', False):
cmd_prefix.append('--force-downgrade')
to_install.extend(pkg_params)
elif pkg_type == 'repository':
if not kwargs.get('install_recommends', True):
cmd_prefix.append('--no-install-recommends')
for pkgname, pkgversion in six.iteritems(pkg_params):
if (name and pkgs is None and kwargs.get('version') and
len(pkg_params) == 1):
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
version_num = pkgversion
if version_num is None:
# Don't allow downgrades if the version
# number is not specified.
if reinstall and pkgname in old:
to_reinstall.append(pkgname)
else:
to_install.append(pkgname)
else:
pkgstr = '{0}={1}'.format(pkgname, version_num)
cver = old.get(pkgname, '')
if reinstall and cver and salt.utils.versions.compare(
ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall.append(pkgstr)
elif not cver or salt.utils.versions.compare(
ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
to_install.append(pkgstr)
else:
if not kwargs.get('only_upgrade', False):
to_downgrade.append(pkgstr)
else:
# This should cause the command to fail.
to_install.append(pkgstr)
cmds = _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall)
if not cmds:
return {}
if refreshdb:
refresh_db()
errors = []
is_testmode = _is_testmode(**kwargs)
test_packages = {}
for cmd in cmds:
_execute_install_command(cmd, is_testmode, errors, test_packages)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if is_testmode:
new = copy.deepcopy(new)
new.update(test_packages)
ret = salt.utils.data.compare_dicts(old, new)
if pkg_type == 'file' and reinstall:
# For file-based packages, prepare 'to_reinstall' to have a list
# of all the package names that may have been reinstalled.
# This way, we could include reinstalled packages in 'ret'.
for pkgfile in to_install:
# Convert from file name to package name.
cmd = ['opkg', 'info', pkgfile]
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] == 0:
# Just need the package name.
pkginfo_dict = _process_info_installed_output(
out['stdout'], []
)
if pkginfo_dict:
to_reinstall.append(list(pkginfo_dict.keys())[0])
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def _parse_reported_packages_from_remove_output(output):
'''
Parses the output of "opkg remove" to determine what packages would have been
removed by an operation run with the --noaction flag.
We are looking for lines like
Removing <package> (<version>) from <Target>...
'''
reported_pkgs = {}
remove_pattern = re.compile(r'Removing\s(?P<package>.*?)\s\((?P<version>.*?)\)\sfrom\s(?P<target>.*?)...')
for line in salt.utils.itertools.split(output, '\n'):
match = remove_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = ''
return reported_pkgs
def remove(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Remove packages using ``opkg remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
remove_dependencies
Remove package and all dependencies
.. versionadded:: 2019.2.0
auto_remove_deps
Remove packages that were installed automatically to satisfy dependencies
.. versionadded:: 2019.2.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
salt '*' pkg.remove pkgs='["foo", "bar"]' remove_dependencies=True auto_remove_deps=True
'''
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 {}
cmd = ['opkg', 'remove']
_append_noaction_if_testmode(cmd, **kwargs)
if kwargs.get('remove_dependencies', False):
cmd.append('--force-removal-of-dependent-packages')
if kwargs.get('auto_remove_deps', False):
cmd.append('--autoremove')
cmd.extend(targets)
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors = [out['stderr']]
else:
errors = [out['stdout']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if _is_testmode(**kwargs):
reportedPkgs = _parse_reported_packages_from_remove_output(out['stdout'])
new = {k: v for k, v in new.items() if k not in reportedPkgs}
ret = salt.utils.data.compare_dicts(old, new)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def purge(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Package purges are not supported by opkg, this function is identical to
:mod:`pkg.remove <salt.modules.opkg.remove>`.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name, pkgs=pkgs)
def upgrade(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
Upgrades all packages via ``opkg upgrade``
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
errors = []
if salt.utils.data.is_true(refresh):
refresh_db()
old = list_pkgs()
cmd = ['opkg', 'upgrade']
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
errors.append(result)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif state != 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = _set_state(target, 'hold')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif state == 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret['comment'] = ('Package {0} is set not to be held.'
.format(target))
else:
result = _set_state(target, 'ok')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def _get_state(pkg):
'''
View package state from the opkg database
Return the state of pkg
'''
cmd = ['opkg', 'status']
cmd.append(pkg)
out = __salt__['cmd.run'](cmd, python_shell=False)
state_flag = ''
for line in salt.utils.itertools.split(out, '\n'):
if line.startswith('Status'):
_status, _state_want, state_flag, _state_status = line.split()
return state_flag
def _set_state(pkg, state):
'''
Change package state on the opkg database
The state can be any of:
- hold
- noprune
- user
- ok
- installed
- unpacked
This command is commonly used to mark a specific package to be held from
being upgraded, that is, to be kept at a certain version.
Returns a dict containing the package name, and the new and old
versions.
'''
ret = {}
valid_states = ('hold', 'noprune', 'user', 'ok', 'installed', 'unpacked')
if state not in valid_states:
raise SaltInvocationError('Invalid state: {0}'.format(state))
oldstate = _get_state(pkg)
cmd = ['opkg', 'flag']
cmd.append(state)
cmd.append(pkg)
_out = __salt__['cmd.run'](cmd, python_shell=False)
# Missing return value check due to opkg issue 160
ret[pkg] = {'old': oldstate,
'new': state}
return ret
def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
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
cmd = ['opkg', 'list-installed']
ret = {}
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
# This is a continuation of package description
if not line or line[0] == ' ':
continue
# This contains package name, version, and description.
# Extract the first two.
pkg_name, pkg_version = line.split(' - ', 2)[:2]
__salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version)
__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 list_upgrades(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
List all available package upgrades.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
ret = {}
if salt.utils.data.is_true(refresh):
refresh_db()
cmd = ['opkg', 'list-upgradable']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
if 'stdout' in call:
comment += call['stdout']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
name, _oldversion, newversion = line.split(' - ')
ret[name] = newversion
return ret
def _convert_to_standard_attr(attr):
'''
Helper function for _process_info_installed_output()
Converts an opkg attribute name to a standard attribute
name which is used across 'pkg' modules.
'''
ret_attr = ATTR_MAP.get(attr, None)
if ret_attr is None:
# All others convert to lowercase
return attr.lower()
return ret_attr
def _process_info_installed_output(out, filter_attrs):
'''
Helper function for info_installed()
Processes stdout output from a single invocation of
'opkg status'.
'''
ret = {}
name = None
attrs = {}
attr = None
for line in salt.utils.itertools.split(out, '\n'):
if line and line[0] == ' ':
# This is a continuation of the last attr
if filter_attrs is None or attr in filter_attrs:
line = line.strip()
if attrs[attr]:
# If attr is empty, don't add leading newline
attrs[attr] += '\n'
attrs[attr] += line
continue
line = line.strip()
if not line:
# Separator between different packages
if name:
ret[name] = attrs
name = None
attrs = {}
attr = None
continue
key, value = line.split(':', 1)
value = value.lstrip()
attr = _convert_to_standard_attr(key)
if attr == 'name':
name = value
elif filter_attrs is None or attr in filter_attrs:
attrs[attr] = value
if name:
ret[name] = attrs
return ret
def upgrade_available(name, **kwargs): # pylint: disable=unused-argument
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs): # pylint: disable=unused-argument
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2016.3.4
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0' '0.2.4.1-0'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] if ignore_epoch else six.text_type(x)
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
output = __salt__['cmd.run_stdout'](['opkg', '--version'],
output_loglevel='trace',
python_shell=False)
opkg_version = output.split(' ')[2].strip()
if salt.utils.versions.LooseVersion(opkg_version) >= \
salt.utils.versions.LooseVersion('0.3.4'):
cmd_compare = ['opkg', 'compare-versions']
elif salt.utils.path.which('opkg-compare-versions'):
cmd_compare = ['opkg-compare-versions']
else:
log.warning('Unable to find a compare-versions utility installed. Either upgrade opkg to '
'version > 0.3.4 (preferred) or install the older opkg-compare-versions script.')
return None
for oper, ret in (("<<", -1), ("=", 0), (">>", 1)):
cmd = cmd_compare[:]
cmd.append(_cmd_quote(pkg1))
cmd.append(oper)
cmd.append(_cmd_quote(pkg2))
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
ignore_retcode=True,
python_shell=False)
if retcode == 0:
return ret
return None
def _set_repo_option(repo, option):
'''
Set the option to repo
'''
if not option:
return
opt = option.split('=')
if len(opt) != 2:
return
if opt[0] == 'trusted':
repo['trusted'] = opt[1] == 'yes'
else:
repo[opt[0]] = opt[1]
def _set_repo_options(repo, options):
'''
Set the options to the repo.
'''
delimiters = "[", "]"
pattern = '|'.join(map(re.escape, delimiters))
for option in options:
splitted = re.split(pattern, option)
for opt in splitted:
_set_repo_option(repo, opt)
def _create_repo(line, filename):
'''
Create repo
'''
repo = {}
if line.startswith('#'):
repo['enabled'] = False
line = line[1:]
else:
repo['enabled'] = True
cols = salt.utils.args.shlex_split(line.strip())
repo['compressed'] = not cols[0] in 'src'
repo['name'] = cols[1]
repo['uri'] = cols[2]
repo['file'] = os.path.join(OPKG_CONFDIR, filename)
if len(cols) > 3:
_set_repo_options(repo, cols[3:])
return repo
def _read_repos(conf_file, repos, filename, regex):
'''
Read repos from configuration file
'''
for line in conf_file:
line = salt.utils.stringutils.to_unicode(line)
if not regex.search(line):
continue
repo = _create_repo(line, filename)
# do not store duplicated uri's
if repo['uri'] not in repos:
repos[repo['uri']] = [repo]
def list_repos(**kwargs): # pylint: disable=unused-argument
'''
Lists all repos on ``/etc/opkg/*.conf``
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos = {}
regex = re.compile(REPO_REGEXP)
for filename in os.listdir(OPKG_CONFDIR):
if not filename.endswith(".conf"):
continue
with salt.utils.files.fopen(os.path.join(OPKG_CONFDIR, filename)) as conf_file:
_read_repos(conf_file, repos, filename, regex)
return repos
def get_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Display a repo from the ``/etc/opkg/*.conf``
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo repo
'''
repos = list_repos()
if repos:
for source in six.itervalues(repos):
for sub in source:
if sub['name'] == repo:
return sub
return {}
def _del_repo_from_file(repo, filepath):
'''
Remove a repo from filepath
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
regex = re.compile(REPO_REGEXP)
for line in fhandle:
line = salt.utils.stringutils.to_unicode(line)
if regex.search(line):
if line.startswith('#'):
line = line[1:]
cols = salt.utils.args.shlex_split(line.strip())
if repo != cols[1]:
output.append(salt.utils.stringutils.to_str(line))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def _set_trusted_option_if_needed(repostr, trusted):
'''
Set trusted option to repo if needed
'''
if trusted is True:
repostr += ' [trusted=yes]'
elif trusted is False:
repostr += ' [trusted=no]'
return repostr
def _add_new_repo(repo, properties):
'''
Add a new repo entry
'''
repostr = '# ' if not properties.get('enabled') else ''
repostr += 'src/gz ' if properties.get('compressed') else 'src '
if ' ' in repo:
repostr += '"' + repo + '" '
else:
repostr += repo + ' '
repostr += properties.get('uri')
repostr = _set_trusted_option_if_needed(repostr, properties.get('trusted'))
repostr += '\n'
conffile = os.path.join(OPKG_CONFDIR, repo + '.conf')
with salt.utils.files.fopen(conffile, 'a') as fhandle:
fhandle.write(salt.utils.stringutils.to_str(repostr))
def _mod_repo_in_file(repo, repostr, filepath):
'''
Replace a repo entry in filepath with repostr
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
for line in fhandle:
cols = salt.utils.args.shlex_split(
salt.utils.stringutils.to_unicode(line).strip()
)
if repo not in cols:
output.append(line)
else:
output.append(salt.utils.stringutils.to_str(repostr + '\n'))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def del_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Delete a repo from ``/etc/opkg/*.conf``
If the file does not contain any other repo configuration, the file itself
will be deleted.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo repo
'''
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
repos = list_repos()
if repos:
deleted_from = dict()
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
deleted_from[source['file']] = 0
_del_repo_from_file(repo, source['file'])
if deleted_from:
ret = ''
for repository in repos:
source = repos[repository][0]
if source['file'] in deleted_from:
deleted_from[source['file']] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 1 and os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.\n')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
if refresh:
refresh_db()
return ret
return "Repo {0} doesn't exist in the opkg repo lists".format(repo)
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as uri is defined.
The following options are available to modify a repo definition:
repo
alias by which opkg refers to the repo.
uri
the URI to the repo.
compressed
defines (True or False) if the index file is compressed
enabled
enable or disable (True or False) repository
but do not remove if disabled.
refresh
enable or disable (True or False) auto-refresh of the repositories
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo repo uri=http://new/uri
salt '*' pkg.mod_repo repo enabled=False
'''
repos = list_repos()
found = False
uri = ''
if 'uri' in kwargs:
uri = kwargs['uri']
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
found = True
repostr = ''
if 'enabled' in kwargs and not kwargs['enabled']:
repostr += '# '
if 'compressed' in kwargs:
repostr += 'src/gz ' if kwargs['compressed'] else 'src'
else:
repostr += 'src/gz' if source['compressed'] else 'src'
repo_alias = kwargs['alias'] if 'alias' in kwargs else repo
if ' ' in repo_alias:
repostr += ' "{0}"'.format(repo_alias)
else:
repostr += ' {0}'.format(repo_alias)
repostr += ' {0}'.format(kwargs['uri'] if 'uri' in kwargs else source['uri'])
trusted = kwargs.get('trusted')
repostr = _set_trusted_option_if_needed(repostr, trusted) if trusted is not None else \
_set_trusted_option_if_needed(repostr, source.get('trusted'))
_mod_repo_in_file(repo, repostr, source['file'])
elif uri and source['uri'] == uri:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(uri, source['name']))
if not found:
# Need to add a new repo
if 'uri' not in kwargs:
raise CommandExecutionError(
'Repository \'{0}\' not found and no URI passed to create one.'.format(repo))
properties = {'uri': kwargs['uri']}
# If compressed is not defined, assume True
properties['compressed'] = kwargs['compressed'] if 'compressed' in kwargs else True
# If enabled is not defined, assume True
properties['enabled'] = kwargs['enabled'] if 'enabled' in kwargs else True
properties['trusted'] = kwargs.get('trusted')
_add_new_repo(repo, properties)
if 'refresh' in kwargs:
refresh_db()
def file_list(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
output = file_dict(*packages)
files = []
for package in list(output['packages'].values()):
files.extend(package)
return {'errors': output['errors'], 'files': files}
def file_dict(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
errors = []
ret = {}
cmd_files = ['opkg', 'files']
if not packages:
packages = list(list_pkgs().keys())
for package in packages:
files = []
cmd = cmd_files[:]
cmd.append(package)
out = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
for line in out['stdout'].splitlines():
if line.startswith('/'):
files.append(line)
elif line.startswith(' * '):
errors.append(line[3:])
break
else:
continue
if files:
ret[package] = files
return {'errors': errors, 'packages': ret}
def owner(*paths, **kwargs): # pylint: disable=unused-argument
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.opkg.version`, if a single
path is passed, a string will be returned, and if multiple paths are passed,
a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
cmd_search = ['opkg', 'search']
for path in paths:
cmd = cmd_search[:]
cmd.append(path)
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
if output:
ret[path] = output.split(' - ')[0].strip()
else:
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def version_clean(version):
'''
Clean the version string removing extra data.
There's nothing do to here for nipkg.py, therefore it will always
return the given version.
'''
return version
def check_extra_requirements(pkgname, pkgver):
'''
Check if the installed package already has the given requirements.
There's nothing do to here for nipkg.py, therefore it will always
return True.
'''
return True
|
saltstack/salt
|
salt/modules/opkg.py
|
version_cmp
|
python
|
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs): # pylint: disable=unused-argument
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2016.3.4
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0' '0.2.4.1-0'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] if ignore_epoch else six.text_type(x)
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
output = __salt__['cmd.run_stdout'](['opkg', '--version'],
output_loglevel='trace',
python_shell=False)
opkg_version = output.split(' ')[2].strip()
if salt.utils.versions.LooseVersion(opkg_version) >= \
salt.utils.versions.LooseVersion('0.3.4'):
cmd_compare = ['opkg', 'compare-versions']
elif salt.utils.path.which('opkg-compare-versions'):
cmd_compare = ['opkg-compare-versions']
else:
log.warning('Unable to find a compare-versions utility installed. Either upgrade opkg to '
'version > 0.3.4 (preferred) or install the older opkg-compare-versions script.')
return None
for oper, ret in (("<<", -1), ("=", 0), (">>", 1)):
cmd = cmd_compare[:]
cmd.append(_cmd_quote(pkg1))
cmd.append(oper)
cmd.append(_cmd_quote(pkg2))
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
ignore_retcode=True,
python_shell=False)
if retcode == 0:
return ret
return None
|
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2016.3.4
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0' '0.2.4.1-0'
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/opkg.py#L1198-L1244
|
[
"normalize = lambda x: six.text_type(x).split(':', 1)[-1] if ignore_epoch else six.text_type(x)\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Opkg
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
.. versionadded: 2016.3.0
.. note::
For version comparison support on opkg < 0.3.4, the ``opkg-utils`` package
must be installed.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import os
import re
import logging
import errno
# Import salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.itertools
import salt.utils.path
import salt.utils.pkg
import salt.utils.stringutils
import salt.utils.versions
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import shlex_quote as _cmd_quote # pylint: disable=import-error
from salt.ext.six.moves import map # pylint: disable=import-error,redefined-builtin
REPO_REGEXP = r'^#?\s*(src|src/gz)\s+([^\s<>]+|"[^<>]+")\s+[^\s<>]+'
OPKG_CONFDIR = '/etc/opkg'
ATTR_MAP = {
'Architecture': 'arch',
'Homepage': 'url',
'Installed-Time': 'install_date_time_t',
'Maintainer': 'packager',
'Package': 'name',
'Section': 'group'
}
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
NILRT_RESTARTCHECK_STATE_PATH = '/var/lib/salt/restartcheck_state'
def _update_nilrt_restart_state():
'''
NILRT systems determine whether to reboot after various package operations
including but not limited to kernel module installs/removals by checking
specific file md5sums & timestamps. These files are touched/modified by
the post-install/post-remove functions of their respective packages.
The opkg module uses this function to store/update those file timestamps
and checksums to be used later by the restartcheck module.
'''
__salt__['cmd.shell']('stat -c %Y /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.timestamp'
.format(NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.md5sum'
.format(NILRT_RESTARTCHECK_STATE_PATH))
# We can't assume nisysapi.ini always exists like modules.dep
nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'
if os.path.exists(nisysapi_path):
__salt__['cmd.shell']('stat -c %Y {0} >{1}/nisysapi.ini.timestamp'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0} >{1}/nisysapi.ini.md5sum'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
# Expert plugin files get added to a conf.d dir, so keep track of the total
# no. of files, their timestamps and content hashes
nisysapi_conf_d_path = "/usr/lib/{0}/nisysapi/conf.d/experts/".format(
'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'
)
if os.path.exists(nisysapi_conf_d_path):
with salt.utils.files.fopen('{0}/sysapi.conf.d.count'.format(
NILRT_RESTARTCHECK_STATE_PATH), 'w') as fcount:
fcount.write(str(len(os.listdir(nisysapi_conf_d_path))))
for fexpert in os.listdir(nisysapi_conf_d_path):
__salt__['cmd.shell']('stat -c %Y {0}/{1} >{2}/{1}.timestamp'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0}/{1} >{2}/{1}.md5sum'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
def _get_restartcheck_result(errors):
'''
Return restartcheck result and append errors (if any) to ``errors``
'''
rs_result = __salt__['restartcheck.restartcheck'](verbose=False)
if isinstance(rs_result, dict) and 'comment' in rs_result:
errors.append(rs_result['comment'])
return rs_result
def _process_restartcheck_result(rs_result, **kwargs):
'''
Check restartcheck output to see if system/service restarts were requested
and take appropriate action.
'''
if 'No packages seem to need to be restarted' in rs_result:
return
reboot_required = False
for rstr in rs_result:
if 'System restart required' in rstr:
_update_nilrt_restart_state()
__salt__['system.set_reboot_required_witnessed']()
reboot_required = True
if kwargs.get('always_restart_services', True) or not reboot_required:
for rstr in rs_result:
if 'System restart required' not in rstr:
service = os.path.join('/etc/init.d', rstr)
if os.path.exists(service):
__salt__['cmd.run']([service, 'restart'])
def __virtual__():
'''
Confirm this module is on a nilrt based system
'''
if __grains__.get('os_family') == 'NILinuxRT':
try:
os.makedirs(NILRT_RESTARTCHECK_STATE_PATH)
except OSError as exc:
if exc.errno != errno.EEXIST:
return False, 'Error creating {0} (-{1}): {2}'.format(
NILRT_RESTARTCHECK_STATE_PATH,
exc.errno,
exc.strerror)
# populate state dir if empty
if not os.listdir(NILRT_RESTARTCHECK_STATE_PATH):
_update_nilrt_restart_state()
return __virtualname__
if os.path.isdir(OPKG_CONFDIR):
return __virtualname__
return False, "Module opkg only works on OpenEmbedded based systems"
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
if not names:
return ''
ret = {}
for name in names:
ret[name] = ''
# Refresh before looking for the latest version available
if refresh:
refresh_db()
cmd = ['opkg', 'list-upgradable']
out = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
try:
name, _oldversion, newversion = line.split(' - ')
if name in names:
ret[name] = newversion
except ValueError:
pass
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = latest_version
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(failhard=False, **kwargs): # pylint: disable=unused-argument
'''
Updates the opkg database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
failhard
If False, return results of failed lines as ``False`` for the package
database that encountered the error.
If True, raise an error with a list of the package databases that
encountered errors.
.. versionadded:: 2018.3.0
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
error_repos = []
cmd = ['opkg', 'update']
# opkg returns a non-zero retcode when there is a failure to refresh
# from one or more repos. Due to this, ignore the retcode.
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True,
redirect_stderr=True)
out = call['stdout']
prev_line = ''
for line in salt.utils.itertools.split(out, '\n'):
if 'Inflating' in line:
key = line.strip().split()[1][:-1]
ret[key] = True
elif 'Updated source' in line:
# Use the previous line.
key = prev_line.strip().split()[1][:-1]
ret[key] = True
elif 'Failed to download' in line:
key = line.strip().split()[5].split(',')[0]
ret[key] = False
error_repos.append(key)
prev_line = line
if failhard and error_repos:
raise CommandExecutionError(
'Error getting repos: {0}'.format(', '.join(error_repos))
)
# On a non-zero exit code where no failed repos were found, raise an
# exception because this appears to be a different kind of error.
if call['retcode'] != 0 and not error_repos:
raise CommandExecutionError(out)
return ret
def _is_testmode(**kwargs):
'''
Returns whether a test mode (noaction) operation was requested.
'''
return bool(kwargs.get('test') or __opts__.get('test'))
def _append_noaction_if_testmode(cmd, **kwargs):
'''
Adds the --noaction flag to the command if it's running in the test mode.
'''
if _is_testmode(**kwargs):
cmd.append('--noaction')
def _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall):
'''
Builds a list of install commands to be executed in sequence in order to process
each of the to_install, to_downgrade, and to_reinstall lists.
'''
cmds = []
if to_install:
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(to_install)
cmds.append(cmd)
if to_downgrade:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-downgrade')
cmd.extend(to_downgrade)
cmds.append(cmd)
if to_reinstall:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-reinstall')
cmd.extend(to_reinstall)
cmds.append(cmd)
return cmds
def _parse_reported_packages_from_install_output(output):
'''
Parses the output of "opkg install" to determine what packages would have been
installed by an operation run with the --noaction flag.
We are looking for lines like:
Installing <package> (<version>) on <target>
or
Upgrading <package> from <oldVersion> to <version> on root
'''
reported_pkgs = {}
install_pattern = re.compile(r'Installing\s(?P<package>.*?)\s\((?P<version>.*?)\)\son\s(?P<target>.*?)')
upgrade_pattern = re.compile(r'Upgrading\s(?P<package>.*?)\sfrom\s(?P<oldVersion>.*?)\sto\s(?P<version>.*?)\son\s(?P<target>.*?)')
for line in salt.utils.itertools.split(output, '\n'):
match = install_pattern.match(line)
if match is None:
match = upgrade_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = match.group('version')
return reported_pkgs
def _execute_install_command(cmd, parse_output, errors, parsed_packages):
'''
Executes a command for the install operation.
If the command fails, its error output will be appended to the errors list.
If the command succeeds and parse_output is true, updated packages will be appended
to the parsed_packages dictionary.
'''
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors.append(out['stderr'])
else:
errors.append(out['stdout'])
elif parse_output:
parsed_packages.update(_parse_reported_packages_from_install_output(out['stdout']))
def install(name=None,
refresh=False,
pkgs=None,
sources=None,
reinstall=False,
**kwargs):
'''
Install the passed package, add refresh=True to update the opkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionadded:: 2017.7.0
reinstall : False
Specifying reinstall=True will use ``opkg install --force-reinstall``
rather than simply ``opkg install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``opkg
install --force-reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2017.7.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of IPK packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
install_recommends
Whether to install the packages marked as recommended. Default is True.
only_upgrade
Only upgrade the packages (disallow downgrades), if they are already
installed. Default is False.
.. versionadded:: 2017.7.0
always_restart_services
Whether to restart services even if a reboot is required. Default is True.
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
refreshdb = salt.utils.data.is_true(refresh)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
cmd_prefix = ['opkg', 'install']
to_install = []
to_reinstall = []
to_downgrade = []
_append_noaction_if_testmode(cmd_prefix, **kwargs)
if not pkg_params:
return {}
elif pkg_type == 'file':
if reinstall:
cmd_prefix.append('--force-reinstall')
if not kwargs.get('only_upgrade', False):
cmd_prefix.append('--force-downgrade')
to_install.extend(pkg_params)
elif pkg_type == 'repository':
if not kwargs.get('install_recommends', True):
cmd_prefix.append('--no-install-recommends')
for pkgname, pkgversion in six.iteritems(pkg_params):
if (name and pkgs is None and kwargs.get('version') and
len(pkg_params) == 1):
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
version_num = pkgversion
if version_num is None:
# Don't allow downgrades if the version
# number is not specified.
if reinstall and pkgname in old:
to_reinstall.append(pkgname)
else:
to_install.append(pkgname)
else:
pkgstr = '{0}={1}'.format(pkgname, version_num)
cver = old.get(pkgname, '')
if reinstall and cver and salt.utils.versions.compare(
ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall.append(pkgstr)
elif not cver or salt.utils.versions.compare(
ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
to_install.append(pkgstr)
else:
if not kwargs.get('only_upgrade', False):
to_downgrade.append(pkgstr)
else:
# This should cause the command to fail.
to_install.append(pkgstr)
cmds = _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall)
if not cmds:
return {}
if refreshdb:
refresh_db()
errors = []
is_testmode = _is_testmode(**kwargs)
test_packages = {}
for cmd in cmds:
_execute_install_command(cmd, is_testmode, errors, test_packages)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if is_testmode:
new = copy.deepcopy(new)
new.update(test_packages)
ret = salt.utils.data.compare_dicts(old, new)
if pkg_type == 'file' and reinstall:
# For file-based packages, prepare 'to_reinstall' to have a list
# of all the package names that may have been reinstalled.
# This way, we could include reinstalled packages in 'ret'.
for pkgfile in to_install:
# Convert from file name to package name.
cmd = ['opkg', 'info', pkgfile]
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] == 0:
# Just need the package name.
pkginfo_dict = _process_info_installed_output(
out['stdout'], []
)
if pkginfo_dict:
to_reinstall.append(list(pkginfo_dict.keys())[0])
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def _parse_reported_packages_from_remove_output(output):
'''
Parses the output of "opkg remove" to determine what packages would have been
removed by an operation run with the --noaction flag.
We are looking for lines like
Removing <package> (<version>) from <Target>...
'''
reported_pkgs = {}
remove_pattern = re.compile(r'Removing\s(?P<package>.*?)\s\((?P<version>.*?)\)\sfrom\s(?P<target>.*?)...')
for line in salt.utils.itertools.split(output, '\n'):
match = remove_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = ''
return reported_pkgs
def remove(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Remove packages using ``opkg remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
remove_dependencies
Remove package and all dependencies
.. versionadded:: 2019.2.0
auto_remove_deps
Remove packages that were installed automatically to satisfy dependencies
.. versionadded:: 2019.2.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
salt '*' pkg.remove pkgs='["foo", "bar"]' remove_dependencies=True auto_remove_deps=True
'''
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 {}
cmd = ['opkg', 'remove']
_append_noaction_if_testmode(cmd, **kwargs)
if kwargs.get('remove_dependencies', False):
cmd.append('--force-removal-of-dependent-packages')
if kwargs.get('auto_remove_deps', False):
cmd.append('--autoremove')
cmd.extend(targets)
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors = [out['stderr']]
else:
errors = [out['stdout']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if _is_testmode(**kwargs):
reportedPkgs = _parse_reported_packages_from_remove_output(out['stdout'])
new = {k: v for k, v in new.items() if k not in reportedPkgs}
ret = salt.utils.data.compare_dicts(old, new)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def purge(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Package purges are not supported by opkg, this function is identical to
:mod:`pkg.remove <salt.modules.opkg.remove>`.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name, pkgs=pkgs)
def upgrade(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
Upgrades all packages via ``opkg upgrade``
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
errors = []
if salt.utils.data.is_true(refresh):
refresh_db()
old = list_pkgs()
cmd = ['opkg', 'upgrade']
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
errors.append(result)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif state != 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = _set_state(target, 'hold')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif state == 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret['comment'] = ('Package {0} is set not to be held.'
.format(target))
else:
result = _set_state(target, 'ok')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def _get_state(pkg):
'''
View package state from the opkg database
Return the state of pkg
'''
cmd = ['opkg', 'status']
cmd.append(pkg)
out = __salt__['cmd.run'](cmd, python_shell=False)
state_flag = ''
for line in salt.utils.itertools.split(out, '\n'):
if line.startswith('Status'):
_status, _state_want, state_flag, _state_status = line.split()
return state_flag
def _set_state(pkg, state):
'''
Change package state on the opkg database
The state can be any of:
- hold
- noprune
- user
- ok
- installed
- unpacked
This command is commonly used to mark a specific package to be held from
being upgraded, that is, to be kept at a certain version.
Returns a dict containing the package name, and the new and old
versions.
'''
ret = {}
valid_states = ('hold', 'noprune', 'user', 'ok', 'installed', 'unpacked')
if state not in valid_states:
raise SaltInvocationError('Invalid state: {0}'.format(state))
oldstate = _get_state(pkg)
cmd = ['opkg', 'flag']
cmd.append(state)
cmd.append(pkg)
_out = __salt__['cmd.run'](cmd, python_shell=False)
# Missing return value check due to opkg issue 160
ret[pkg] = {'old': oldstate,
'new': state}
return ret
def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
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
cmd = ['opkg', 'list-installed']
ret = {}
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
# This is a continuation of package description
if not line or line[0] == ' ':
continue
# This contains package name, version, and description.
# Extract the first two.
pkg_name, pkg_version = line.split(' - ', 2)[:2]
__salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version)
__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 list_upgrades(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
List all available package upgrades.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
ret = {}
if salt.utils.data.is_true(refresh):
refresh_db()
cmd = ['opkg', 'list-upgradable']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
if 'stdout' in call:
comment += call['stdout']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
name, _oldversion, newversion = line.split(' - ')
ret[name] = newversion
return ret
def _convert_to_standard_attr(attr):
'''
Helper function for _process_info_installed_output()
Converts an opkg attribute name to a standard attribute
name which is used across 'pkg' modules.
'''
ret_attr = ATTR_MAP.get(attr, None)
if ret_attr is None:
# All others convert to lowercase
return attr.lower()
return ret_attr
def _process_info_installed_output(out, filter_attrs):
'''
Helper function for info_installed()
Processes stdout output from a single invocation of
'opkg status'.
'''
ret = {}
name = None
attrs = {}
attr = None
for line in salt.utils.itertools.split(out, '\n'):
if line and line[0] == ' ':
# This is a continuation of the last attr
if filter_attrs is None or attr in filter_attrs:
line = line.strip()
if attrs[attr]:
# If attr is empty, don't add leading newline
attrs[attr] += '\n'
attrs[attr] += line
continue
line = line.strip()
if not line:
# Separator between different packages
if name:
ret[name] = attrs
name = None
attrs = {}
attr = None
continue
key, value = line.split(':', 1)
value = value.lstrip()
attr = _convert_to_standard_attr(key)
if attr == 'name':
name = value
elif filter_attrs is None or attr in filter_attrs:
attrs[attr] = value
if name:
ret[name] = attrs
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
.. versionadded:: 2017.7.0
:param names:
Names of the packages to get information about. If none are specified,
will return information for all installed packages.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
arch, conffiles, conflicts, depends, description, filename, group,
install_date_time_t, md5sum, packager, provides, recommends,
replaces, size, source, suggests, url, version
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed
salt '*' pkg.info_installed attr=version,packager
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> attr=version,packager
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,packager
'''
attr = kwargs.pop('attr', None)
if attr is None:
filter_attrs = None
elif isinstance(attr, six.string_types):
filter_attrs = set(attr.split(','))
else:
filter_attrs = set(attr)
ret = {}
if names:
# Specific list of names of installed packages
for name in names:
cmd = ['opkg', 'status', name]
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
else:
# All installed packages
cmd = ['opkg', 'status']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
return ret
def upgrade_available(name, **kwargs): # pylint: disable=unused-argument
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def _set_repo_option(repo, option):
'''
Set the option to repo
'''
if not option:
return
opt = option.split('=')
if len(opt) != 2:
return
if opt[0] == 'trusted':
repo['trusted'] = opt[1] == 'yes'
else:
repo[opt[0]] = opt[1]
def _set_repo_options(repo, options):
'''
Set the options to the repo.
'''
delimiters = "[", "]"
pattern = '|'.join(map(re.escape, delimiters))
for option in options:
splitted = re.split(pattern, option)
for opt in splitted:
_set_repo_option(repo, opt)
def _create_repo(line, filename):
'''
Create repo
'''
repo = {}
if line.startswith('#'):
repo['enabled'] = False
line = line[1:]
else:
repo['enabled'] = True
cols = salt.utils.args.shlex_split(line.strip())
repo['compressed'] = not cols[0] in 'src'
repo['name'] = cols[1]
repo['uri'] = cols[2]
repo['file'] = os.path.join(OPKG_CONFDIR, filename)
if len(cols) > 3:
_set_repo_options(repo, cols[3:])
return repo
def _read_repos(conf_file, repos, filename, regex):
'''
Read repos from configuration file
'''
for line in conf_file:
line = salt.utils.stringutils.to_unicode(line)
if not regex.search(line):
continue
repo = _create_repo(line, filename)
# do not store duplicated uri's
if repo['uri'] not in repos:
repos[repo['uri']] = [repo]
def list_repos(**kwargs): # pylint: disable=unused-argument
'''
Lists all repos on ``/etc/opkg/*.conf``
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos = {}
regex = re.compile(REPO_REGEXP)
for filename in os.listdir(OPKG_CONFDIR):
if not filename.endswith(".conf"):
continue
with salt.utils.files.fopen(os.path.join(OPKG_CONFDIR, filename)) as conf_file:
_read_repos(conf_file, repos, filename, regex)
return repos
def get_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Display a repo from the ``/etc/opkg/*.conf``
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo repo
'''
repos = list_repos()
if repos:
for source in six.itervalues(repos):
for sub in source:
if sub['name'] == repo:
return sub
return {}
def _del_repo_from_file(repo, filepath):
'''
Remove a repo from filepath
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
regex = re.compile(REPO_REGEXP)
for line in fhandle:
line = salt.utils.stringutils.to_unicode(line)
if regex.search(line):
if line.startswith('#'):
line = line[1:]
cols = salt.utils.args.shlex_split(line.strip())
if repo != cols[1]:
output.append(salt.utils.stringutils.to_str(line))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def _set_trusted_option_if_needed(repostr, trusted):
'''
Set trusted option to repo if needed
'''
if trusted is True:
repostr += ' [trusted=yes]'
elif trusted is False:
repostr += ' [trusted=no]'
return repostr
def _add_new_repo(repo, properties):
'''
Add a new repo entry
'''
repostr = '# ' if not properties.get('enabled') else ''
repostr += 'src/gz ' if properties.get('compressed') else 'src '
if ' ' in repo:
repostr += '"' + repo + '" '
else:
repostr += repo + ' '
repostr += properties.get('uri')
repostr = _set_trusted_option_if_needed(repostr, properties.get('trusted'))
repostr += '\n'
conffile = os.path.join(OPKG_CONFDIR, repo + '.conf')
with salt.utils.files.fopen(conffile, 'a') as fhandle:
fhandle.write(salt.utils.stringutils.to_str(repostr))
def _mod_repo_in_file(repo, repostr, filepath):
'''
Replace a repo entry in filepath with repostr
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
for line in fhandle:
cols = salt.utils.args.shlex_split(
salt.utils.stringutils.to_unicode(line).strip()
)
if repo not in cols:
output.append(line)
else:
output.append(salt.utils.stringutils.to_str(repostr + '\n'))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def del_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Delete a repo from ``/etc/opkg/*.conf``
If the file does not contain any other repo configuration, the file itself
will be deleted.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo repo
'''
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
repos = list_repos()
if repos:
deleted_from = dict()
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
deleted_from[source['file']] = 0
_del_repo_from_file(repo, source['file'])
if deleted_from:
ret = ''
for repository in repos:
source = repos[repository][0]
if source['file'] in deleted_from:
deleted_from[source['file']] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 1 and os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.\n')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
if refresh:
refresh_db()
return ret
return "Repo {0} doesn't exist in the opkg repo lists".format(repo)
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as uri is defined.
The following options are available to modify a repo definition:
repo
alias by which opkg refers to the repo.
uri
the URI to the repo.
compressed
defines (True or False) if the index file is compressed
enabled
enable or disable (True or False) repository
but do not remove if disabled.
refresh
enable or disable (True or False) auto-refresh of the repositories
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo repo uri=http://new/uri
salt '*' pkg.mod_repo repo enabled=False
'''
repos = list_repos()
found = False
uri = ''
if 'uri' in kwargs:
uri = kwargs['uri']
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
found = True
repostr = ''
if 'enabled' in kwargs and not kwargs['enabled']:
repostr += '# '
if 'compressed' in kwargs:
repostr += 'src/gz ' if kwargs['compressed'] else 'src'
else:
repostr += 'src/gz' if source['compressed'] else 'src'
repo_alias = kwargs['alias'] if 'alias' in kwargs else repo
if ' ' in repo_alias:
repostr += ' "{0}"'.format(repo_alias)
else:
repostr += ' {0}'.format(repo_alias)
repostr += ' {0}'.format(kwargs['uri'] if 'uri' in kwargs else source['uri'])
trusted = kwargs.get('trusted')
repostr = _set_trusted_option_if_needed(repostr, trusted) if trusted is not None else \
_set_trusted_option_if_needed(repostr, source.get('trusted'))
_mod_repo_in_file(repo, repostr, source['file'])
elif uri and source['uri'] == uri:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(uri, source['name']))
if not found:
# Need to add a new repo
if 'uri' not in kwargs:
raise CommandExecutionError(
'Repository \'{0}\' not found and no URI passed to create one.'.format(repo))
properties = {'uri': kwargs['uri']}
# If compressed is not defined, assume True
properties['compressed'] = kwargs['compressed'] if 'compressed' in kwargs else True
# If enabled is not defined, assume True
properties['enabled'] = kwargs['enabled'] if 'enabled' in kwargs else True
properties['trusted'] = kwargs.get('trusted')
_add_new_repo(repo, properties)
if 'refresh' in kwargs:
refresh_db()
def file_list(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
output = file_dict(*packages)
files = []
for package in list(output['packages'].values()):
files.extend(package)
return {'errors': output['errors'], 'files': files}
def file_dict(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
errors = []
ret = {}
cmd_files = ['opkg', 'files']
if not packages:
packages = list(list_pkgs().keys())
for package in packages:
files = []
cmd = cmd_files[:]
cmd.append(package)
out = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
for line in out['stdout'].splitlines():
if line.startswith('/'):
files.append(line)
elif line.startswith(' * '):
errors.append(line[3:])
break
else:
continue
if files:
ret[package] = files
return {'errors': errors, 'packages': ret}
def owner(*paths, **kwargs): # pylint: disable=unused-argument
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.opkg.version`, if a single
path is passed, a string will be returned, and if multiple paths are passed,
a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
cmd_search = ['opkg', 'search']
for path in paths:
cmd = cmd_search[:]
cmd.append(path)
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
if output:
ret[path] = output.split(' - ')[0].strip()
else:
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def version_clean(version):
'''
Clean the version string removing extra data.
There's nothing do to here for nipkg.py, therefore it will always
return the given version.
'''
return version
def check_extra_requirements(pkgname, pkgver):
'''
Check if the installed package already has the given requirements.
There's nothing do to here for nipkg.py, therefore it will always
return True.
'''
return True
|
saltstack/salt
|
salt/modules/opkg.py
|
_set_repo_option
|
python
|
def _set_repo_option(repo, option):
'''
Set the option to repo
'''
if not option:
return
opt = option.split('=')
if len(opt) != 2:
return
if opt[0] == 'trusted':
repo['trusted'] = opt[1] == 'yes'
else:
repo[opt[0]] = opt[1]
|
Set the option to repo
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/opkg.py#L1247-L1259
| null |
# -*- coding: utf-8 -*-
'''
Support for Opkg
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
.. versionadded: 2016.3.0
.. note::
For version comparison support on opkg < 0.3.4, the ``opkg-utils`` package
must be installed.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import os
import re
import logging
import errno
# Import salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.itertools
import salt.utils.path
import salt.utils.pkg
import salt.utils.stringutils
import salt.utils.versions
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import shlex_quote as _cmd_quote # pylint: disable=import-error
from salt.ext.six.moves import map # pylint: disable=import-error,redefined-builtin
REPO_REGEXP = r'^#?\s*(src|src/gz)\s+([^\s<>]+|"[^<>]+")\s+[^\s<>]+'
OPKG_CONFDIR = '/etc/opkg'
ATTR_MAP = {
'Architecture': 'arch',
'Homepage': 'url',
'Installed-Time': 'install_date_time_t',
'Maintainer': 'packager',
'Package': 'name',
'Section': 'group'
}
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
NILRT_RESTARTCHECK_STATE_PATH = '/var/lib/salt/restartcheck_state'
def _update_nilrt_restart_state():
'''
NILRT systems determine whether to reboot after various package operations
including but not limited to kernel module installs/removals by checking
specific file md5sums & timestamps. These files are touched/modified by
the post-install/post-remove functions of their respective packages.
The opkg module uses this function to store/update those file timestamps
and checksums to be used later by the restartcheck module.
'''
__salt__['cmd.shell']('stat -c %Y /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.timestamp'
.format(NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.md5sum'
.format(NILRT_RESTARTCHECK_STATE_PATH))
# We can't assume nisysapi.ini always exists like modules.dep
nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'
if os.path.exists(nisysapi_path):
__salt__['cmd.shell']('stat -c %Y {0} >{1}/nisysapi.ini.timestamp'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0} >{1}/nisysapi.ini.md5sum'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
# Expert plugin files get added to a conf.d dir, so keep track of the total
# no. of files, their timestamps and content hashes
nisysapi_conf_d_path = "/usr/lib/{0}/nisysapi/conf.d/experts/".format(
'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'
)
if os.path.exists(nisysapi_conf_d_path):
with salt.utils.files.fopen('{0}/sysapi.conf.d.count'.format(
NILRT_RESTARTCHECK_STATE_PATH), 'w') as fcount:
fcount.write(str(len(os.listdir(nisysapi_conf_d_path))))
for fexpert in os.listdir(nisysapi_conf_d_path):
__salt__['cmd.shell']('stat -c %Y {0}/{1} >{2}/{1}.timestamp'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0}/{1} >{2}/{1}.md5sum'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
def _get_restartcheck_result(errors):
'''
Return restartcheck result and append errors (if any) to ``errors``
'''
rs_result = __salt__['restartcheck.restartcheck'](verbose=False)
if isinstance(rs_result, dict) and 'comment' in rs_result:
errors.append(rs_result['comment'])
return rs_result
def _process_restartcheck_result(rs_result, **kwargs):
'''
Check restartcheck output to see if system/service restarts were requested
and take appropriate action.
'''
if 'No packages seem to need to be restarted' in rs_result:
return
reboot_required = False
for rstr in rs_result:
if 'System restart required' in rstr:
_update_nilrt_restart_state()
__salt__['system.set_reboot_required_witnessed']()
reboot_required = True
if kwargs.get('always_restart_services', True) or not reboot_required:
for rstr in rs_result:
if 'System restart required' not in rstr:
service = os.path.join('/etc/init.d', rstr)
if os.path.exists(service):
__salt__['cmd.run']([service, 'restart'])
def __virtual__():
'''
Confirm this module is on a nilrt based system
'''
if __grains__.get('os_family') == 'NILinuxRT':
try:
os.makedirs(NILRT_RESTARTCHECK_STATE_PATH)
except OSError as exc:
if exc.errno != errno.EEXIST:
return False, 'Error creating {0} (-{1}): {2}'.format(
NILRT_RESTARTCHECK_STATE_PATH,
exc.errno,
exc.strerror)
# populate state dir if empty
if not os.listdir(NILRT_RESTARTCHECK_STATE_PATH):
_update_nilrt_restart_state()
return __virtualname__
if os.path.isdir(OPKG_CONFDIR):
return __virtualname__
return False, "Module opkg only works on OpenEmbedded based systems"
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
if not names:
return ''
ret = {}
for name in names:
ret[name] = ''
# Refresh before looking for the latest version available
if refresh:
refresh_db()
cmd = ['opkg', 'list-upgradable']
out = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
try:
name, _oldversion, newversion = line.split(' - ')
if name in names:
ret[name] = newversion
except ValueError:
pass
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = latest_version
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(failhard=False, **kwargs): # pylint: disable=unused-argument
'''
Updates the opkg database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
failhard
If False, return results of failed lines as ``False`` for the package
database that encountered the error.
If True, raise an error with a list of the package databases that
encountered errors.
.. versionadded:: 2018.3.0
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
error_repos = []
cmd = ['opkg', 'update']
# opkg returns a non-zero retcode when there is a failure to refresh
# from one or more repos. Due to this, ignore the retcode.
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True,
redirect_stderr=True)
out = call['stdout']
prev_line = ''
for line in salt.utils.itertools.split(out, '\n'):
if 'Inflating' in line:
key = line.strip().split()[1][:-1]
ret[key] = True
elif 'Updated source' in line:
# Use the previous line.
key = prev_line.strip().split()[1][:-1]
ret[key] = True
elif 'Failed to download' in line:
key = line.strip().split()[5].split(',')[0]
ret[key] = False
error_repos.append(key)
prev_line = line
if failhard and error_repos:
raise CommandExecutionError(
'Error getting repos: {0}'.format(', '.join(error_repos))
)
# On a non-zero exit code where no failed repos were found, raise an
# exception because this appears to be a different kind of error.
if call['retcode'] != 0 and not error_repos:
raise CommandExecutionError(out)
return ret
def _is_testmode(**kwargs):
'''
Returns whether a test mode (noaction) operation was requested.
'''
return bool(kwargs.get('test') or __opts__.get('test'))
def _append_noaction_if_testmode(cmd, **kwargs):
'''
Adds the --noaction flag to the command if it's running in the test mode.
'''
if _is_testmode(**kwargs):
cmd.append('--noaction')
def _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall):
'''
Builds a list of install commands to be executed in sequence in order to process
each of the to_install, to_downgrade, and to_reinstall lists.
'''
cmds = []
if to_install:
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(to_install)
cmds.append(cmd)
if to_downgrade:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-downgrade')
cmd.extend(to_downgrade)
cmds.append(cmd)
if to_reinstall:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-reinstall')
cmd.extend(to_reinstall)
cmds.append(cmd)
return cmds
def _parse_reported_packages_from_install_output(output):
'''
Parses the output of "opkg install" to determine what packages would have been
installed by an operation run with the --noaction flag.
We are looking for lines like:
Installing <package> (<version>) on <target>
or
Upgrading <package> from <oldVersion> to <version> on root
'''
reported_pkgs = {}
install_pattern = re.compile(r'Installing\s(?P<package>.*?)\s\((?P<version>.*?)\)\son\s(?P<target>.*?)')
upgrade_pattern = re.compile(r'Upgrading\s(?P<package>.*?)\sfrom\s(?P<oldVersion>.*?)\sto\s(?P<version>.*?)\son\s(?P<target>.*?)')
for line in salt.utils.itertools.split(output, '\n'):
match = install_pattern.match(line)
if match is None:
match = upgrade_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = match.group('version')
return reported_pkgs
def _execute_install_command(cmd, parse_output, errors, parsed_packages):
'''
Executes a command for the install operation.
If the command fails, its error output will be appended to the errors list.
If the command succeeds and parse_output is true, updated packages will be appended
to the parsed_packages dictionary.
'''
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors.append(out['stderr'])
else:
errors.append(out['stdout'])
elif parse_output:
parsed_packages.update(_parse_reported_packages_from_install_output(out['stdout']))
def install(name=None,
refresh=False,
pkgs=None,
sources=None,
reinstall=False,
**kwargs):
'''
Install the passed package, add refresh=True to update the opkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionadded:: 2017.7.0
reinstall : False
Specifying reinstall=True will use ``opkg install --force-reinstall``
rather than simply ``opkg install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``opkg
install --force-reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2017.7.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of IPK packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
install_recommends
Whether to install the packages marked as recommended. Default is True.
only_upgrade
Only upgrade the packages (disallow downgrades), if they are already
installed. Default is False.
.. versionadded:: 2017.7.0
always_restart_services
Whether to restart services even if a reboot is required. Default is True.
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
refreshdb = salt.utils.data.is_true(refresh)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
cmd_prefix = ['opkg', 'install']
to_install = []
to_reinstall = []
to_downgrade = []
_append_noaction_if_testmode(cmd_prefix, **kwargs)
if not pkg_params:
return {}
elif pkg_type == 'file':
if reinstall:
cmd_prefix.append('--force-reinstall')
if not kwargs.get('only_upgrade', False):
cmd_prefix.append('--force-downgrade')
to_install.extend(pkg_params)
elif pkg_type == 'repository':
if not kwargs.get('install_recommends', True):
cmd_prefix.append('--no-install-recommends')
for pkgname, pkgversion in six.iteritems(pkg_params):
if (name and pkgs is None and kwargs.get('version') and
len(pkg_params) == 1):
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
version_num = pkgversion
if version_num is None:
# Don't allow downgrades if the version
# number is not specified.
if reinstall and pkgname in old:
to_reinstall.append(pkgname)
else:
to_install.append(pkgname)
else:
pkgstr = '{0}={1}'.format(pkgname, version_num)
cver = old.get(pkgname, '')
if reinstall and cver and salt.utils.versions.compare(
ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall.append(pkgstr)
elif not cver or salt.utils.versions.compare(
ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
to_install.append(pkgstr)
else:
if not kwargs.get('only_upgrade', False):
to_downgrade.append(pkgstr)
else:
# This should cause the command to fail.
to_install.append(pkgstr)
cmds = _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall)
if not cmds:
return {}
if refreshdb:
refresh_db()
errors = []
is_testmode = _is_testmode(**kwargs)
test_packages = {}
for cmd in cmds:
_execute_install_command(cmd, is_testmode, errors, test_packages)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if is_testmode:
new = copy.deepcopy(new)
new.update(test_packages)
ret = salt.utils.data.compare_dicts(old, new)
if pkg_type == 'file' and reinstall:
# For file-based packages, prepare 'to_reinstall' to have a list
# of all the package names that may have been reinstalled.
# This way, we could include reinstalled packages in 'ret'.
for pkgfile in to_install:
# Convert from file name to package name.
cmd = ['opkg', 'info', pkgfile]
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] == 0:
# Just need the package name.
pkginfo_dict = _process_info_installed_output(
out['stdout'], []
)
if pkginfo_dict:
to_reinstall.append(list(pkginfo_dict.keys())[0])
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def _parse_reported_packages_from_remove_output(output):
'''
Parses the output of "opkg remove" to determine what packages would have been
removed by an operation run with the --noaction flag.
We are looking for lines like
Removing <package> (<version>) from <Target>...
'''
reported_pkgs = {}
remove_pattern = re.compile(r'Removing\s(?P<package>.*?)\s\((?P<version>.*?)\)\sfrom\s(?P<target>.*?)...')
for line in salt.utils.itertools.split(output, '\n'):
match = remove_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = ''
return reported_pkgs
def remove(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Remove packages using ``opkg remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
remove_dependencies
Remove package and all dependencies
.. versionadded:: 2019.2.0
auto_remove_deps
Remove packages that were installed automatically to satisfy dependencies
.. versionadded:: 2019.2.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
salt '*' pkg.remove pkgs='["foo", "bar"]' remove_dependencies=True auto_remove_deps=True
'''
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 {}
cmd = ['opkg', 'remove']
_append_noaction_if_testmode(cmd, **kwargs)
if kwargs.get('remove_dependencies', False):
cmd.append('--force-removal-of-dependent-packages')
if kwargs.get('auto_remove_deps', False):
cmd.append('--autoremove')
cmd.extend(targets)
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors = [out['stderr']]
else:
errors = [out['stdout']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if _is_testmode(**kwargs):
reportedPkgs = _parse_reported_packages_from_remove_output(out['stdout'])
new = {k: v for k, v in new.items() if k not in reportedPkgs}
ret = salt.utils.data.compare_dicts(old, new)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def purge(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Package purges are not supported by opkg, this function is identical to
:mod:`pkg.remove <salt.modules.opkg.remove>`.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name, pkgs=pkgs)
def upgrade(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
Upgrades all packages via ``opkg upgrade``
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
errors = []
if salt.utils.data.is_true(refresh):
refresh_db()
old = list_pkgs()
cmd = ['opkg', 'upgrade']
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
errors.append(result)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif state != 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = _set_state(target, 'hold')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif state == 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret['comment'] = ('Package {0} is set not to be held.'
.format(target))
else:
result = _set_state(target, 'ok')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def _get_state(pkg):
'''
View package state from the opkg database
Return the state of pkg
'''
cmd = ['opkg', 'status']
cmd.append(pkg)
out = __salt__['cmd.run'](cmd, python_shell=False)
state_flag = ''
for line in salt.utils.itertools.split(out, '\n'):
if line.startswith('Status'):
_status, _state_want, state_flag, _state_status = line.split()
return state_flag
def _set_state(pkg, state):
'''
Change package state on the opkg database
The state can be any of:
- hold
- noprune
- user
- ok
- installed
- unpacked
This command is commonly used to mark a specific package to be held from
being upgraded, that is, to be kept at a certain version.
Returns a dict containing the package name, and the new and old
versions.
'''
ret = {}
valid_states = ('hold', 'noprune', 'user', 'ok', 'installed', 'unpacked')
if state not in valid_states:
raise SaltInvocationError('Invalid state: {0}'.format(state))
oldstate = _get_state(pkg)
cmd = ['opkg', 'flag']
cmd.append(state)
cmd.append(pkg)
_out = __salt__['cmd.run'](cmd, python_shell=False)
# Missing return value check due to opkg issue 160
ret[pkg] = {'old': oldstate,
'new': state}
return ret
def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
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
cmd = ['opkg', 'list-installed']
ret = {}
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
# This is a continuation of package description
if not line or line[0] == ' ':
continue
# This contains package name, version, and description.
# Extract the first two.
pkg_name, pkg_version = line.split(' - ', 2)[:2]
__salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version)
__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 list_upgrades(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
List all available package upgrades.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
ret = {}
if salt.utils.data.is_true(refresh):
refresh_db()
cmd = ['opkg', 'list-upgradable']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
if 'stdout' in call:
comment += call['stdout']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
name, _oldversion, newversion = line.split(' - ')
ret[name] = newversion
return ret
def _convert_to_standard_attr(attr):
'''
Helper function for _process_info_installed_output()
Converts an opkg attribute name to a standard attribute
name which is used across 'pkg' modules.
'''
ret_attr = ATTR_MAP.get(attr, None)
if ret_attr is None:
# All others convert to lowercase
return attr.lower()
return ret_attr
def _process_info_installed_output(out, filter_attrs):
'''
Helper function for info_installed()
Processes stdout output from a single invocation of
'opkg status'.
'''
ret = {}
name = None
attrs = {}
attr = None
for line in salt.utils.itertools.split(out, '\n'):
if line and line[0] == ' ':
# This is a continuation of the last attr
if filter_attrs is None or attr in filter_attrs:
line = line.strip()
if attrs[attr]:
# If attr is empty, don't add leading newline
attrs[attr] += '\n'
attrs[attr] += line
continue
line = line.strip()
if not line:
# Separator between different packages
if name:
ret[name] = attrs
name = None
attrs = {}
attr = None
continue
key, value = line.split(':', 1)
value = value.lstrip()
attr = _convert_to_standard_attr(key)
if attr == 'name':
name = value
elif filter_attrs is None or attr in filter_attrs:
attrs[attr] = value
if name:
ret[name] = attrs
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
.. versionadded:: 2017.7.0
:param names:
Names of the packages to get information about. If none are specified,
will return information for all installed packages.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
arch, conffiles, conflicts, depends, description, filename, group,
install_date_time_t, md5sum, packager, provides, recommends,
replaces, size, source, suggests, url, version
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed
salt '*' pkg.info_installed attr=version,packager
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> attr=version,packager
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,packager
'''
attr = kwargs.pop('attr', None)
if attr is None:
filter_attrs = None
elif isinstance(attr, six.string_types):
filter_attrs = set(attr.split(','))
else:
filter_attrs = set(attr)
ret = {}
if names:
# Specific list of names of installed packages
for name in names:
cmd = ['opkg', 'status', name]
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
else:
# All installed packages
cmd = ['opkg', 'status']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
return ret
def upgrade_available(name, **kwargs): # pylint: disable=unused-argument
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs): # pylint: disable=unused-argument
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2016.3.4
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0' '0.2.4.1-0'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] if ignore_epoch else six.text_type(x)
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
output = __salt__['cmd.run_stdout'](['opkg', '--version'],
output_loglevel='trace',
python_shell=False)
opkg_version = output.split(' ')[2].strip()
if salt.utils.versions.LooseVersion(opkg_version) >= \
salt.utils.versions.LooseVersion('0.3.4'):
cmd_compare = ['opkg', 'compare-versions']
elif salt.utils.path.which('opkg-compare-versions'):
cmd_compare = ['opkg-compare-versions']
else:
log.warning('Unable to find a compare-versions utility installed. Either upgrade opkg to '
'version > 0.3.4 (preferred) or install the older opkg-compare-versions script.')
return None
for oper, ret in (("<<", -1), ("=", 0), (">>", 1)):
cmd = cmd_compare[:]
cmd.append(_cmd_quote(pkg1))
cmd.append(oper)
cmd.append(_cmd_quote(pkg2))
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
ignore_retcode=True,
python_shell=False)
if retcode == 0:
return ret
return None
def _set_repo_options(repo, options):
'''
Set the options to the repo.
'''
delimiters = "[", "]"
pattern = '|'.join(map(re.escape, delimiters))
for option in options:
splitted = re.split(pattern, option)
for opt in splitted:
_set_repo_option(repo, opt)
def _create_repo(line, filename):
'''
Create repo
'''
repo = {}
if line.startswith('#'):
repo['enabled'] = False
line = line[1:]
else:
repo['enabled'] = True
cols = salt.utils.args.shlex_split(line.strip())
repo['compressed'] = not cols[0] in 'src'
repo['name'] = cols[1]
repo['uri'] = cols[2]
repo['file'] = os.path.join(OPKG_CONFDIR, filename)
if len(cols) > 3:
_set_repo_options(repo, cols[3:])
return repo
def _read_repos(conf_file, repos, filename, regex):
'''
Read repos from configuration file
'''
for line in conf_file:
line = salt.utils.stringutils.to_unicode(line)
if not regex.search(line):
continue
repo = _create_repo(line, filename)
# do not store duplicated uri's
if repo['uri'] not in repos:
repos[repo['uri']] = [repo]
def list_repos(**kwargs): # pylint: disable=unused-argument
'''
Lists all repos on ``/etc/opkg/*.conf``
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos = {}
regex = re.compile(REPO_REGEXP)
for filename in os.listdir(OPKG_CONFDIR):
if not filename.endswith(".conf"):
continue
with salt.utils.files.fopen(os.path.join(OPKG_CONFDIR, filename)) as conf_file:
_read_repos(conf_file, repos, filename, regex)
return repos
def get_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Display a repo from the ``/etc/opkg/*.conf``
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo repo
'''
repos = list_repos()
if repos:
for source in six.itervalues(repos):
for sub in source:
if sub['name'] == repo:
return sub
return {}
def _del_repo_from_file(repo, filepath):
'''
Remove a repo from filepath
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
regex = re.compile(REPO_REGEXP)
for line in fhandle:
line = salt.utils.stringutils.to_unicode(line)
if regex.search(line):
if line.startswith('#'):
line = line[1:]
cols = salt.utils.args.shlex_split(line.strip())
if repo != cols[1]:
output.append(salt.utils.stringutils.to_str(line))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def _set_trusted_option_if_needed(repostr, trusted):
'''
Set trusted option to repo if needed
'''
if trusted is True:
repostr += ' [trusted=yes]'
elif trusted is False:
repostr += ' [trusted=no]'
return repostr
def _add_new_repo(repo, properties):
'''
Add a new repo entry
'''
repostr = '# ' if not properties.get('enabled') else ''
repostr += 'src/gz ' if properties.get('compressed') else 'src '
if ' ' in repo:
repostr += '"' + repo + '" '
else:
repostr += repo + ' '
repostr += properties.get('uri')
repostr = _set_trusted_option_if_needed(repostr, properties.get('trusted'))
repostr += '\n'
conffile = os.path.join(OPKG_CONFDIR, repo + '.conf')
with salt.utils.files.fopen(conffile, 'a') as fhandle:
fhandle.write(salt.utils.stringutils.to_str(repostr))
def _mod_repo_in_file(repo, repostr, filepath):
'''
Replace a repo entry in filepath with repostr
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
for line in fhandle:
cols = salt.utils.args.shlex_split(
salt.utils.stringutils.to_unicode(line).strip()
)
if repo not in cols:
output.append(line)
else:
output.append(salt.utils.stringutils.to_str(repostr + '\n'))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def del_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Delete a repo from ``/etc/opkg/*.conf``
If the file does not contain any other repo configuration, the file itself
will be deleted.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo repo
'''
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
repos = list_repos()
if repos:
deleted_from = dict()
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
deleted_from[source['file']] = 0
_del_repo_from_file(repo, source['file'])
if deleted_from:
ret = ''
for repository in repos:
source = repos[repository][0]
if source['file'] in deleted_from:
deleted_from[source['file']] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 1 and os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.\n')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
if refresh:
refresh_db()
return ret
return "Repo {0} doesn't exist in the opkg repo lists".format(repo)
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as uri is defined.
The following options are available to modify a repo definition:
repo
alias by which opkg refers to the repo.
uri
the URI to the repo.
compressed
defines (True or False) if the index file is compressed
enabled
enable or disable (True or False) repository
but do not remove if disabled.
refresh
enable or disable (True or False) auto-refresh of the repositories
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo repo uri=http://new/uri
salt '*' pkg.mod_repo repo enabled=False
'''
repos = list_repos()
found = False
uri = ''
if 'uri' in kwargs:
uri = kwargs['uri']
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
found = True
repostr = ''
if 'enabled' in kwargs and not kwargs['enabled']:
repostr += '# '
if 'compressed' in kwargs:
repostr += 'src/gz ' if kwargs['compressed'] else 'src'
else:
repostr += 'src/gz' if source['compressed'] else 'src'
repo_alias = kwargs['alias'] if 'alias' in kwargs else repo
if ' ' in repo_alias:
repostr += ' "{0}"'.format(repo_alias)
else:
repostr += ' {0}'.format(repo_alias)
repostr += ' {0}'.format(kwargs['uri'] if 'uri' in kwargs else source['uri'])
trusted = kwargs.get('trusted')
repostr = _set_trusted_option_if_needed(repostr, trusted) if trusted is not None else \
_set_trusted_option_if_needed(repostr, source.get('trusted'))
_mod_repo_in_file(repo, repostr, source['file'])
elif uri and source['uri'] == uri:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(uri, source['name']))
if not found:
# Need to add a new repo
if 'uri' not in kwargs:
raise CommandExecutionError(
'Repository \'{0}\' not found and no URI passed to create one.'.format(repo))
properties = {'uri': kwargs['uri']}
# If compressed is not defined, assume True
properties['compressed'] = kwargs['compressed'] if 'compressed' in kwargs else True
# If enabled is not defined, assume True
properties['enabled'] = kwargs['enabled'] if 'enabled' in kwargs else True
properties['trusted'] = kwargs.get('trusted')
_add_new_repo(repo, properties)
if 'refresh' in kwargs:
refresh_db()
def file_list(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
output = file_dict(*packages)
files = []
for package in list(output['packages'].values()):
files.extend(package)
return {'errors': output['errors'], 'files': files}
def file_dict(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
errors = []
ret = {}
cmd_files = ['opkg', 'files']
if not packages:
packages = list(list_pkgs().keys())
for package in packages:
files = []
cmd = cmd_files[:]
cmd.append(package)
out = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
for line in out['stdout'].splitlines():
if line.startswith('/'):
files.append(line)
elif line.startswith(' * '):
errors.append(line[3:])
break
else:
continue
if files:
ret[package] = files
return {'errors': errors, 'packages': ret}
def owner(*paths, **kwargs): # pylint: disable=unused-argument
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.opkg.version`, if a single
path is passed, a string will be returned, and if multiple paths are passed,
a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
cmd_search = ['opkg', 'search']
for path in paths:
cmd = cmd_search[:]
cmd.append(path)
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
if output:
ret[path] = output.split(' - ')[0].strip()
else:
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def version_clean(version):
'''
Clean the version string removing extra data.
There's nothing do to here for nipkg.py, therefore it will always
return the given version.
'''
return version
def check_extra_requirements(pkgname, pkgver):
'''
Check if the installed package already has the given requirements.
There's nothing do to here for nipkg.py, therefore it will always
return True.
'''
return True
|
saltstack/salt
|
salt/modules/opkg.py
|
_set_repo_options
|
python
|
def _set_repo_options(repo, options):
'''
Set the options to the repo.
'''
delimiters = "[", "]"
pattern = '|'.join(map(re.escape, delimiters))
for option in options:
splitted = re.split(pattern, option)
for opt in splitted:
_set_repo_option(repo, opt)
|
Set the options to the repo.
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/opkg.py#L1262-L1271
| null |
# -*- coding: utf-8 -*-
'''
Support for Opkg
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
.. versionadded: 2016.3.0
.. note::
For version comparison support on opkg < 0.3.4, the ``opkg-utils`` package
must be installed.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import os
import re
import logging
import errno
# Import salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.itertools
import salt.utils.path
import salt.utils.pkg
import salt.utils.stringutils
import salt.utils.versions
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import shlex_quote as _cmd_quote # pylint: disable=import-error
from salt.ext.six.moves import map # pylint: disable=import-error,redefined-builtin
REPO_REGEXP = r'^#?\s*(src|src/gz)\s+([^\s<>]+|"[^<>]+")\s+[^\s<>]+'
OPKG_CONFDIR = '/etc/opkg'
ATTR_MAP = {
'Architecture': 'arch',
'Homepage': 'url',
'Installed-Time': 'install_date_time_t',
'Maintainer': 'packager',
'Package': 'name',
'Section': 'group'
}
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
NILRT_RESTARTCHECK_STATE_PATH = '/var/lib/salt/restartcheck_state'
def _update_nilrt_restart_state():
'''
NILRT systems determine whether to reboot after various package operations
including but not limited to kernel module installs/removals by checking
specific file md5sums & timestamps. These files are touched/modified by
the post-install/post-remove functions of their respective packages.
The opkg module uses this function to store/update those file timestamps
and checksums to be used later by the restartcheck module.
'''
__salt__['cmd.shell']('stat -c %Y /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.timestamp'
.format(NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.md5sum'
.format(NILRT_RESTARTCHECK_STATE_PATH))
# We can't assume nisysapi.ini always exists like modules.dep
nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'
if os.path.exists(nisysapi_path):
__salt__['cmd.shell']('stat -c %Y {0} >{1}/nisysapi.ini.timestamp'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0} >{1}/nisysapi.ini.md5sum'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
# Expert plugin files get added to a conf.d dir, so keep track of the total
# no. of files, their timestamps and content hashes
nisysapi_conf_d_path = "/usr/lib/{0}/nisysapi/conf.d/experts/".format(
'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'
)
if os.path.exists(nisysapi_conf_d_path):
with salt.utils.files.fopen('{0}/sysapi.conf.d.count'.format(
NILRT_RESTARTCHECK_STATE_PATH), 'w') as fcount:
fcount.write(str(len(os.listdir(nisysapi_conf_d_path))))
for fexpert in os.listdir(nisysapi_conf_d_path):
__salt__['cmd.shell']('stat -c %Y {0}/{1} >{2}/{1}.timestamp'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0}/{1} >{2}/{1}.md5sum'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
def _get_restartcheck_result(errors):
'''
Return restartcheck result and append errors (if any) to ``errors``
'''
rs_result = __salt__['restartcheck.restartcheck'](verbose=False)
if isinstance(rs_result, dict) and 'comment' in rs_result:
errors.append(rs_result['comment'])
return rs_result
def _process_restartcheck_result(rs_result, **kwargs):
'''
Check restartcheck output to see if system/service restarts were requested
and take appropriate action.
'''
if 'No packages seem to need to be restarted' in rs_result:
return
reboot_required = False
for rstr in rs_result:
if 'System restart required' in rstr:
_update_nilrt_restart_state()
__salt__['system.set_reboot_required_witnessed']()
reboot_required = True
if kwargs.get('always_restart_services', True) or not reboot_required:
for rstr in rs_result:
if 'System restart required' not in rstr:
service = os.path.join('/etc/init.d', rstr)
if os.path.exists(service):
__salt__['cmd.run']([service, 'restart'])
def __virtual__():
'''
Confirm this module is on a nilrt based system
'''
if __grains__.get('os_family') == 'NILinuxRT':
try:
os.makedirs(NILRT_RESTARTCHECK_STATE_PATH)
except OSError as exc:
if exc.errno != errno.EEXIST:
return False, 'Error creating {0} (-{1}): {2}'.format(
NILRT_RESTARTCHECK_STATE_PATH,
exc.errno,
exc.strerror)
# populate state dir if empty
if not os.listdir(NILRT_RESTARTCHECK_STATE_PATH):
_update_nilrt_restart_state()
return __virtualname__
if os.path.isdir(OPKG_CONFDIR):
return __virtualname__
return False, "Module opkg only works on OpenEmbedded based systems"
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
if not names:
return ''
ret = {}
for name in names:
ret[name] = ''
# Refresh before looking for the latest version available
if refresh:
refresh_db()
cmd = ['opkg', 'list-upgradable']
out = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
try:
name, _oldversion, newversion = line.split(' - ')
if name in names:
ret[name] = newversion
except ValueError:
pass
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = latest_version
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(failhard=False, **kwargs): # pylint: disable=unused-argument
'''
Updates the opkg database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
failhard
If False, return results of failed lines as ``False`` for the package
database that encountered the error.
If True, raise an error with a list of the package databases that
encountered errors.
.. versionadded:: 2018.3.0
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
error_repos = []
cmd = ['opkg', 'update']
# opkg returns a non-zero retcode when there is a failure to refresh
# from one or more repos. Due to this, ignore the retcode.
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True,
redirect_stderr=True)
out = call['stdout']
prev_line = ''
for line in salt.utils.itertools.split(out, '\n'):
if 'Inflating' in line:
key = line.strip().split()[1][:-1]
ret[key] = True
elif 'Updated source' in line:
# Use the previous line.
key = prev_line.strip().split()[1][:-1]
ret[key] = True
elif 'Failed to download' in line:
key = line.strip().split()[5].split(',')[0]
ret[key] = False
error_repos.append(key)
prev_line = line
if failhard and error_repos:
raise CommandExecutionError(
'Error getting repos: {0}'.format(', '.join(error_repos))
)
# On a non-zero exit code where no failed repos were found, raise an
# exception because this appears to be a different kind of error.
if call['retcode'] != 0 and not error_repos:
raise CommandExecutionError(out)
return ret
def _is_testmode(**kwargs):
'''
Returns whether a test mode (noaction) operation was requested.
'''
return bool(kwargs.get('test') or __opts__.get('test'))
def _append_noaction_if_testmode(cmd, **kwargs):
'''
Adds the --noaction flag to the command if it's running in the test mode.
'''
if _is_testmode(**kwargs):
cmd.append('--noaction')
def _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall):
'''
Builds a list of install commands to be executed in sequence in order to process
each of the to_install, to_downgrade, and to_reinstall lists.
'''
cmds = []
if to_install:
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(to_install)
cmds.append(cmd)
if to_downgrade:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-downgrade')
cmd.extend(to_downgrade)
cmds.append(cmd)
if to_reinstall:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-reinstall')
cmd.extend(to_reinstall)
cmds.append(cmd)
return cmds
def _parse_reported_packages_from_install_output(output):
'''
Parses the output of "opkg install" to determine what packages would have been
installed by an operation run with the --noaction flag.
We are looking for lines like:
Installing <package> (<version>) on <target>
or
Upgrading <package> from <oldVersion> to <version> on root
'''
reported_pkgs = {}
install_pattern = re.compile(r'Installing\s(?P<package>.*?)\s\((?P<version>.*?)\)\son\s(?P<target>.*?)')
upgrade_pattern = re.compile(r'Upgrading\s(?P<package>.*?)\sfrom\s(?P<oldVersion>.*?)\sto\s(?P<version>.*?)\son\s(?P<target>.*?)')
for line in salt.utils.itertools.split(output, '\n'):
match = install_pattern.match(line)
if match is None:
match = upgrade_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = match.group('version')
return reported_pkgs
def _execute_install_command(cmd, parse_output, errors, parsed_packages):
'''
Executes a command for the install operation.
If the command fails, its error output will be appended to the errors list.
If the command succeeds and parse_output is true, updated packages will be appended
to the parsed_packages dictionary.
'''
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors.append(out['stderr'])
else:
errors.append(out['stdout'])
elif parse_output:
parsed_packages.update(_parse_reported_packages_from_install_output(out['stdout']))
def install(name=None,
refresh=False,
pkgs=None,
sources=None,
reinstall=False,
**kwargs):
'''
Install the passed package, add refresh=True to update the opkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionadded:: 2017.7.0
reinstall : False
Specifying reinstall=True will use ``opkg install --force-reinstall``
rather than simply ``opkg install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``opkg
install --force-reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2017.7.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of IPK packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
install_recommends
Whether to install the packages marked as recommended. Default is True.
only_upgrade
Only upgrade the packages (disallow downgrades), if they are already
installed. Default is False.
.. versionadded:: 2017.7.0
always_restart_services
Whether to restart services even if a reboot is required. Default is True.
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
refreshdb = salt.utils.data.is_true(refresh)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
cmd_prefix = ['opkg', 'install']
to_install = []
to_reinstall = []
to_downgrade = []
_append_noaction_if_testmode(cmd_prefix, **kwargs)
if not pkg_params:
return {}
elif pkg_type == 'file':
if reinstall:
cmd_prefix.append('--force-reinstall')
if not kwargs.get('only_upgrade', False):
cmd_prefix.append('--force-downgrade')
to_install.extend(pkg_params)
elif pkg_type == 'repository':
if not kwargs.get('install_recommends', True):
cmd_prefix.append('--no-install-recommends')
for pkgname, pkgversion in six.iteritems(pkg_params):
if (name and pkgs is None and kwargs.get('version') and
len(pkg_params) == 1):
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
version_num = pkgversion
if version_num is None:
# Don't allow downgrades if the version
# number is not specified.
if reinstall and pkgname in old:
to_reinstall.append(pkgname)
else:
to_install.append(pkgname)
else:
pkgstr = '{0}={1}'.format(pkgname, version_num)
cver = old.get(pkgname, '')
if reinstall and cver and salt.utils.versions.compare(
ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall.append(pkgstr)
elif not cver or salt.utils.versions.compare(
ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
to_install.append(pkgstr)
else:
if not kwargs.get('only_upgrade', False):
to_downgrade.append(pkgstr)
else:
# This should cause the command to fail.
to_install.append(pkgstr)
cmds = _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall)
if not cmds:
return {}
if refreshdb:
refresh_db()
errors = []
is_testmode = _is_testmode(**kwargs)
test_packages = {}
for cmd in cmds:
_execute_install_command(cmd, is_testmode, errors, test_packages)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if is_testmode:
new = copy.deepcopy(new)
new.update(test_packages)
ret = salt.utils.data.compare_dicts(old, new)
if pkg_type == 'file' and reinstall:
# For file-based packages, prepare 'to_reinstall' to have a list
# of all the package names that may have been reinstalled.
# This way, we could include reinstalled packages in 'ret'.
for pkgfile in to_install:
# Convert from file name to package name.
cmd = ['opkg', 'info', pkgfile]
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] == 0:
# Just need the package name.
pkginfo_dict = _process_info_installed_output(
out['stdout'], []
)
if pkginfo_dict:
to_reinstall.append(list(pkginfo_dict.keys())[0])
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def _parse_reported_packages_from_remove_output(output):
'''
Parses the output of "opkg remove" to determine what packages would have been
removed by an operation run with the --noaction flag.
We are looking for lines like
Removing <package> (<version>) from <Target>...
'''
reported_pkgs = {}
remove_pattern = re.compile(r'Removing\s(?P<package>.*?)\s\((?P<version>.*?)\)\sfrom\s(?P<target>.*?)...')
for line in salt.utils.itertools.split(output, '\n'):
match = remove_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = ''
return reported_pkgs
def remove(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Remove packages using ``opkg remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
remove_dependencies
Remove package and all dependencies
.. versionadded:: 2019.2.0
auto_remove_deps
Remove packages that were installed automatically to satisfy dependencies
.. versionadded:: 2019.2.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
salt '*' pkg.remove pkgs='["foo", "bar"]' remove_dependencies=True auto_remove_deps=True
'''
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 {}
cmd = ['opkg', 'remove']
_append_noaction_if_testmode(cmd, **kwargs)
if kwargs.get('remove_dependencies', False):
cmd.append('--force-removal-of-dependent-packages')
if kwargs.get('auto_remove_deps', False):
cmd.append('--autoremove')
cmd.extend(targets)
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors = [out['stderr']]
else:
errors = [out['stdout']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if _is_testmode(**kwargs):
reportedPkgs = _parse_reported_packages_from_remove_output(out['stdout'])
new = {k: v for k, v in new.items() if k not in reportedPkgs}
ret = salt.utils.data.compare_dicts(old, new)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def purge(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Package purges are not supported by opkg, this function is identical to
:mod:`pkg.remove <salt.modules.opkg.remove>`.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name, pkgs=pkgs)
def upgrade(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
Upgrades all packages via ``opkg upgrade``
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
errors = []
if salt.utils.data.is_true(refresh):
refresh_db()
old = list_pkgs()
cmd = ['opkg', 'upgrade']
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
errors.append(result)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif state != 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = _set_state(target, 'hold')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif state == 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret['comment'] = ('Package {0} is set not to be held.'
.format(target))
else:
result = _set_state(target, 'ok')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def _get_state(pkg):
'''
View package state from the opkg database
Return the state of pkg
'''
cmd = ['opkg', 'status']
cmd.append(pkg)
out = __salt__['cmd.run'](cmd, python_shell=False)
state_flag = ''
for line in salt.utils.itertools.split(out, '\n'):
if line.startswith('Status'):
_status, _state_want, state_flag, _state_status = line.split()
return state_flag
def _set_state(pkg, state):
'''
Change package state on the opkg database
The state can be any of:
- hold
- noprune
- user
- ok
- installed
- unpacked
This command is commonly used to mark a specific package to be held from
being upgraded, that is, to be kept at a certain version.
Returns a dict containing the package name, and the new and old
versions.
'''
ret = {}
valid_states = ('hold', 'noprune', 'user', 'ok', 'installed', 'unpacked')
if state not in valid_states:
raise SaltInvocationError('Invalid state: {0}'.format(state))
oldstate = _get_state(pkg)
cmd = ['opkg', 'flag']
cmd.append(state)
cmd.append(pkg)
_out = __salt__['cmd.run'](cmd, python_shell=False)
# Missing return value check due to opkg issue 160
ret[pkg] = {'old': oldstate,
'new': state}
return ret
def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
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
cmd = ['opkg', 'list-installed']
ret = {}
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
# This is a continuation of package description
if not line or line[0] == ' ':
continue
# This contains package name, version, and description.
# Extract the first two.
pkg_name, pkg_version = line.split(' - ', 2)[:2]
__salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version)
__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 list_upgrades(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
List all available package upgrades.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
ret = {}
if salt.utils.data.is_true(refresh):
refresh_db()
cmd = ['opkg', 'list-upgradable']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
if 'stdout' in call:
comment += call['stdout']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
name, _oldversion, newversion = line.split(' - ')
ret[name] = newversion
return ret
def _convert_to_standard_attr(attr):
'''
Helper function for _process_info_installed_output()
Converts an opkg attribute name to a standard attribute
name which is used across 'pkg' modules.
'''
ret_attr = ATTR_MAP.get(attr, None)
if ret_attr is None:
# All others convert to lowercase
return attr.lower()
return ret_attr
def _process_info_installed_output(out, filter_attrs):
'''
Helper function for info_installed()
Processes stdout output from a single invocation of
'opkg status'.
'''
ret = {}
name = None
attrs = {}
attr = None
for line in salt.utils.itertools.split(out, '\n'):
if line and line[0] == ' ':
# This is a continuation of the last attr
if filter_attrs is None or attr in filter_attrs:
line = line.strip()
if attrs[attr]:
# If attr is empty, don't add leading newline
attrs[attr] += '\n'
attrs[attr] += line
continue
line = line.strip()
if not line:
# Separator between different packages
if name:
ret[name] = attrs
name = None
attrs = {}
attr = None
continue
key, value = line.split(':', 1)
value = value.lstrip()
attr = _convert_to_standard_attr(key)
if attr == 'name':
name = value
elif filter_attrs is None or attr in filter_attrs:
attrs[attr] = value
if name:
ret[name] = attrs
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
.. versionadded:: 2017.7.0
:param names:
Names of the packages to get information about. If none are specified,
will return information for all installed packages.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
arch, conffiles, conflicts, depends, description, filename, group,
install_date_time_t, md5sum, packager, provides, recommends,
replaces, size, source, suggests, url, version
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed
salt '*' pkg.info_installed attr=version,packager
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> attr=version,packager
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,packager
'''
attr = kwargs.pop('attr', None)
if attr is None:
filter_attrs = None
elif isinstance(attr, six.string_types):
filter_attrs = set(attr.split(','))
else:
filter_attrs = set(attr)
ret = {}
if names:
# Specific list of names of installed packages
for name in names:
cmd = ['opkg', 'status', name]
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
else:
# All installed packages
cmd = ['opkg', 'status']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
return ret
def upgrade_available(name, **kwargs): # pylint: disable=unused-argument
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs): # pylint: disable=unused-argument
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2016.3.4
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0' '0.2.4.1-0'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] if ignore_epoch else six.text_type(x)
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
output = __salt__['cmd.run_stdout'](['opkg', '--version'],
output_loglevel='trace',
python_shell=False)
opkg_version = output.split(' ')[2].strip()
if salt.utils.versions.LooseVersion(opkg_version) >= \
salt.utils.versions.LooseVersion('0.3.4'):
cmd_compare = ['opkg', 'compare-versions']
elif salt.utils.path.which('opkg-compare-versions'):
cmd_compare = ['opkg-compare-versions']
else:
log.warning('Unable to find a compare-versions utility installed. Either upgrade opkg to '
'version > 0.3.4 (preferred) or install the older opkg-compare-versions script.')
return None
for oper, ret in (("<<", -1), ("=", 0), (">>", 1)):
cmd = cmd_compare[:]
cmd.append(_cmd_quote(pkg1))
cmd.append(oper)
cmd.append(_cmd_quote(pkg2))
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
ignore_retcode=True,
python_shell=False)
if retcode == 0:
return ret
return None
def _set_repo_option(repo, option):
'''
Set the option to repo
'''
if not option:
return
opt = option.split('=')
if len(opt) != 2:
return
if opt[0] == 'trusted':
repo['trusted'] = opt[1] == 'yes'
else:
repo[opt[0]] = opt[1]
def _create_repo(line, filename):
'''
Create repo
'''
repo = {}
if line.startswith('#'):
repo['enabled'] = False
line = line[1:]
else:
repo['enabled'] = True
cols = salt.utils.args.shlex_split(line.strip())
repo['compressed'] = not cols[0] in 'src'
repo['name'] = cols[1]
repo['uri'] = cols[2]
repo['file'] = os.path.join(OPKG_CONFDIR, filename)
if len(cols) > 3:
_set_repo_options(repo, cols[3:])
return repo
def _read_repos(conf_file, repos, filename, regex):
'''
Read repos from configuration file
'''
for line in conf_file:
line = salt.utils.stringutils.to_unicode(line)
if not regex.search(line):
continue
repo = _create_repo(line, filename)
# do not store duplicated uri's
if repo['uri'] not in repos:
repos[repo['uri']] = [repo]
def list_repos(**kwargs): # pylint: disable=unused-argument
'''
Lists all repos on ``/etc/opkg/*.conf``
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos = {}
regex = re.compile(REPO_REGEXP)
for filename in os.listdir(OPKG_CONFDIR):
if not filename.endswith(".conf"):
continue
with salt.utils.files.fopen(os.path.join(OPKG_CONFDIR, filename)) as conf_file:
_read_repos(conf_file, repos, filename, regex)
return repos
def get_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Display a repo from the ``/etc/opkg/*.conf``
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo repo
'''
repos = list_repos()
if repos:
for source in six.itervalues(repos):
for sub in source:
if sub['name'] == repo:
return sub
return {}
def _del_repo_from_file(repo, filepath):
'''
Remove a repo from filepath
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
regex = re.compile(REPO_REGEXP)
for line in fhandle:
line = salt.utils.stringutils.to_unicode(line)
if regex.search(line):
if line.startswith('#'):
line = line[1:]
cols = salt.utils.args.shlex_split(line.strip())
if repo != cols[1]:
output.append(salt.utils.stringutils.to_str(line))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def _set_trusted_option_if_needed(repostr, trusted):
'''
Set trusted option to repo if needed
'''
if trusted is True:
repostr += ' [trusted=yes]'
elif trusted is False:
repostr += ' [trusted=no]'
return repostr
def _add_new_repo(repo, properties):
'''
Add a new repo entry
'''
repostr = '# ' if not properties.get('enabled') else ''
repostr += 'src/gz ' if properties.get('compressed') else 'src '
if ' ' in repo:
repostr += '"' + repo + '" '
else:
repostr += repo + ' '
repostr += properties.get('uri')
repostr = _set_trusted_option_if_needed(repostr, properties.get('trusted'))
repostr += '\n'
conffile = os.path.join(OPKG_CONFDIR, repo + '.conf')
with salt.utils.files.fopen(conffile, 'a') as fhandle:
fhandle.write(salt.utils.stringutils.to_str(repostr))
def _mod_repo_in_file(repo, repostr, filepath):
'''
Replace a repo entry in filepath with repostr
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
for line in fhandle:
cols = salt.utils.args.shlex_split(
salt.utils.stringutils.to_unicode(line).strip()
)
if repo not in cols:
output.append(line)
else:
output.append(salt.utils.stringutils.to_str(repostr + '\n'))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def del_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Delete a repo from ``/etc/opkg/*.conf``
If the file does not contain any other repo configuration, the file itself
will be deleted.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo repo
'''
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
repos = list_repos()
if repos:
deleted_from = dict()
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
deleted_from[source['file']] = 0
_del_repo_from_file(repo, source['file'])
if deleted_from:
ret = ''
for repository in repos:
source = repos[repository][0]
if source['file'] in deleted_from:
deleted_from[source['file']] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 1 and os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.\n')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
if refresh:
refresh_db()
return ret
return "Repo {0} doesn't exist in the opkg repo lists".format(repo)
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as uri is defined.
The following options are available to modify a repo definition:
repo
alias by which opkg refers to the repo.
uri
the URI to the repo.
compressed
defines (True or False) if the index file is compressed
enabled
enable or disable (True or False) repository
but do not remove if disabled.
refresh
enable or disable (True or False) auto-refresh of the repositories
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo repo uri=http://new/uri
salt '*' pkg.mod_repo repo enabled=False
'''
repos = list_repos()
found = False
uri = ''
if 'uri' in kwargs:
uri = kwargs['uri']
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
found = True
repostr = ''
if 'enabled' in kwargs and not kwargs['enabled']:
repostr += '# '
if 'compressed' in kwargs:
repostr += 'src/gz ' if kwargs['compressed'] else 'src'
else:
repostr += 'src/gz' if source['compressed'] else 'src'
repo_alias = kwargs['alias'] if 'alias' in kwargs else repo
if ' ' in repo_alias:
repostr += ' "{0}"'.format(repo_alias)
else:
repostr += ' {0}'.format(repo_alias)
repostr += ' {0}'.format(kwargs['uri'] if 'uri' in kwargs else source['uri'])
trusted = kwargs.get('trusted')
repostr = _set_trusted_option_if_needed(repostr, trusted) if trusted is not None else \
_set_trusted_option_if_needed(repostr, source.get('trusted'))
_mod_repo_in_file(repo, repostr, source['file'])
elif uri and source['uri'] == uri:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(uri, source['name']))
if not found:
# Need to add a new repo
if 'uri' not in kwargs:
raise CommandExecutionError(
'Repository \'{0}\' not found and no URI passed to create one.'.format(repo))
properties = {'uri': kwargs['uri']}
# If compressed is not defined, assume True
properties['compressed'] = kwargs['compressed'] if 'compressed' in kwargs else True
# If enabled is not defined, assume True
properties['enabled'] = kwargs['enabled'] if 'enabled' in kwargs else True
properties['trusted'] = kwargs.get('trusted')
_add_new_repo(repo, properties)
if 'refresh' in kwargs:
refresh_db()
def file_list(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
output = file_dict(*packages)
files = []
for package in list(output['packages'].values()):
files.extend(package)
return {'errors': output['errors'], 'files': files}
def file_dict(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
errors = []
ret = {}
cmd_files = ['opkg', 'files']
if not packages:
packages = list(list_pkgs().keys())
for package in packages:
files = []
cmd = cmd_files[:]
cmd.append(package)
out = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
for line in out['stdout'].splitlines():
if line.startswith('/'):
files.append(line)
elif line.startswith(' * '):
errors.append(line[3:])
break
else:
continue
if files:
ret[package] = files
return {'errors': errors, 'packages': ret}
def owner(*paths, **kwargs): # pylint: disable=unused-argument
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.opkg.version`, if a single
path is passed, a string will be returned, and if multiple paths are passed,
a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
cmd_search = ['opkg', 'search']
for path in paths:
cmd = cmd_search[:]
cmd.append(path)
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
if output:
ret[path] = output.split(' - ')[0].strip()
else:
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def version_clean(version):
'''
Clean the version string removing extra data.
There's nothing do to here for nipkg.py, therefore it will always
return the given version.
'''
return version
def check_extra_requirements(pkgname, pkgver):
'''
Check if the installed package already has the given requirements.
There's nothing do to here for nipkg.py, therefore it will always
return True.
'''
return True
|
saltstack/salt
|
salt/modules/opkg.py
|
_create_repo
|
python
|
def _create_repo(line, filename):
'''
Create repo
'''
repo = {}
if line.startswith('#'):
repo['enabled'] = False
line = line[1:]
else:
repo['enabled'] = True
cols = salt.utils.args.shlex_split(line.strip())
repo['compressed'] = not cols[0] in 'src'
repo['name'] = cols[1]
repo['uri'] = cols[2]
repo['file'] = os.path.join(OPKG_CONFDIR, filename)
if len(cols) > 3:
_set_repo_options(repo, cols[3:])
return repo
|
Create repo
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/opkg.py#L1274-L1291
| null |
# -*- coding: utf-8 -*-
'''
Support for Opkg
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
.. versionadded: 2016.3.0
.. note::
For version comparison support on opkg < 0.3.4, the ``opkg-utils`` package
must be installed.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import os
import re
import logging
import errno
# Import salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.itertools
import salt.utils.path
import salt.utils.pkg
import salt.utils.stringutils
import salt.utils.versions
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import shlex_quote as _cmd_quote # pylint: disable=import-error
from salt.ext.six.moves import map # pylint: disable=import-error,redefined-builtin
REPO_REGEXP = r'^#?\s*(src|src/gz)\s+([^\s<>]+|"[^<>]+")\s+[^\s<>]+'
OPKG_CONFDIR = '/etc/opkg'
ATTR_MAP = {
'Architecture': 'arch',
'Homepage': 'url',
'Installed-Time': 'install_date_time_t',
'Maintainer': 'packager',
'Package': 'name',
'Section': 'group'
}
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
NILRT_RESTARTCHECK_STATE_PATH = '/var/lib/salt/restartcheck_state'
def _update_nilrt_restart_state():
'''
NILRT systems determine whether to reboot after various package operations
including but not limited to kernel module installs/removals by checking
specific file md5sums & timestamps. These files are touched/modified by
the post-install/post-remove functions of their respective packages.
The opkg module uses this function to store/update those file timestamps
and checksums to be used later by the restartcheck module.
'''
__salt__['cmd.shell']('stat -c %Y /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.timestamp'
.format(NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.md5sum'
.format(NILRT_RESTARTCHECK_STATE_PATH))
# We can't assume nisysapi.ini always exists like modules.dep
nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'
if os.path.exists(nisysapi_path):
__salt__['cmd.shell']('stat -c %Y {0} >{1}/nisysapi.ini.timestamp'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0} >{1}/nisysapi.ini.md5sum'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
# Expert plugin files get added to a conf.d dir, so keep track of the total
# no. of files, their timestamps and content hashes
nisysapi_conf_d_path = "/usr/lib/{0}/nisysapi/conf.d/experts/".format(
'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'
)
if os.path.exists(nisysapi_conf_d_path):
with salt.utils.files.fopen('{0}/sysapi.conf.d.count'.format(
NILRT_RESTARTCHECK_STATE_PATH), 'w') as fcount:
fcount.write(str(len(os.listdir(nisysapi_conf_d_path))))
for fexpert in os.listdir(nisysapi_conf_d_path):
__salt__['cmd.shell']('stat -c %Y {0}/{1} >{2}/{1}.timestamp'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0}/{1} >{2}/{1}.md5sum'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
def _get_restartcheck_result(errors):
'''
Return restartcheck result and append errors (if any) to ``errors``
'''
rs_result = __salt__['restartcheck.restartcheck'](verbose=False)
if isinstance(rs_result, dict) and 'comment' in rs_result:
errors.append(rs_result['comment'])
return rs_result
def _process_restartcheck_result(rs_result, **kwargs):
'''
Check restartcheck output to see if system/service restarts were requested
and take appropriate action.
'''
if 'No packages seem to need to be restarted' in rs_result:
return
reboot_required = False
for rstr in rs_result:
if 'System restart required' in rstr:
_update_nilrt_restart_state()
__salt__['system.set_reboot_required_witnessed']()
reboot_required = True
if kwargs.get('always_restart_services', True) or not reboot_required:
for rstr in rs_result:
if 'System restart required' not in rstr:
service = os.path.join('/etc/init.d', rstr)
if os.path.exists(service):
__salt__['cmd.run']([service, 'restart'])
def __virtual__():
'''
Confirm this module is on a nilrt based system
'''
if __grains__.get('os_family') == 'NILinuxRT':
try:
os.makedirs(NILRT_RESTARTCHECK_STATE_PATH)
except OSError as exc:
if exc.errno != errno.EEXIST:
return False, 'Error creating {0} (-{1}): {2}'.format(
NILRT_RESTARTCHECK_STATE_PATH,
exc.errno,
exc.strerror)
# populate state dir if empty
if not os.listdir(NILRT_RESTARTCHECK_STATE_PATH):
_update_nilrt_restart_state()
return __virtualname__
if os.path.isdir(OPKG_CONFDIR):
return __virtualname__
return False, "Module opkg only works on OpenEmbedded based systems"
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
if not names:
return ''
ret = {}
for name in names:
ret[name] = ''
# Refresh before looking for the latest version available
if refresh:
refresh_db()
cmd = ['opkg', 'list-upgradable']
out = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
try:
name, _oldversion, newversion = line.split(' - ')
if name in names:
ret[name] = newversion
except ValueError:
pass
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = latest_version
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(failhard=False, **kwargs): # pylint: disable=unused-argument
'''
Updates the opkg database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
failhard
If False, return results of failed lines as ``False`` for the package
database that encountered the error.
If True, raise an error with a list of the package databases that
encountered errors.
.. versionadded:: 2018.3.0
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
error_repos = []
cmd = ['opkg', 'update']
# opkg returns a non-zero retcode when there is a failure to refresh
# from one or more repos. Due to this, ignore the retcode.
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True,
redirect_stderr=True)
out = call['stdout']
prev_line = ''
for line in salt.utils.itertools.split(out, '\n'):
if 'Inflating' in line:
key = line.strip().split()[1][:-1]
ret[key] = True
elif 'Updated source' in line:
# Use the previous line.
key = prev_line.strip().split()[1][:-1]
ret[key] = True
elif 'Failed to download' in line:
key = line.strip().split()[5].split(',')[0]
ret[key] = False
error_repos.append(key)
prev_line = line
if failhard and error_repos:
raise CommandExecutionError(
'Error getting repos: {0}'.format(', '.join(error_repos))
)
# On a non-zero exit code where no failed repos were found, raise an
# exception because this appears to be a different kind of error.
if call['retcode'] != 0 and not error_repos:
raise CommandExecutionError(out)
return ret
def _is_testmode(**kwargs):
'''
Returns whether a test mode (noaction) operation was requested.
'''
return bool(kwargs.get('test') or __opts__.get('test'))
def _append_noaction_if_testmode(cmd, **kwargs):
'''
Adds the --noaction flag to the command if it's running in the test mode.
'''
if _is_testmode(**kwargs):
cmd.append('--noaction')
def _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall):
'''
Builds a list of install commands to be executed in sequence in order to process
each of the to_install, to_downgrade, and to_reinstall lists.
'''
cmds = []
if to_install:
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(to_install)
cmds.append(cmd)
if to_downgrade:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-downgrade')
cmd.extend(to_downgrade)
cmds.append(cmd)
if to_reinstall:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-reinstall')
cmd.extend(to_reinstall)
cmds.append(cmd)
return cmds
def _parse_reported_packages_from_install_output(output):
'''
Parses the output of "opkg install" to determine what packages would have been
installed by an operation run with the --noaction flag.
We are looking for lines like:
Installing <package> (<version>) on <target>
or
Upgrading <package> from <oldVersion> to <version> on root
'''
reported_pkgs = {}
install_pattern = re.compile(r'Installing\s(?P<package>.*?)\s\((?P<version>.*?)\)\son\s(?P<target>.*?)')
upgrade_pattern = re.compile(r'Upgrading\s(?P<package>.*?)\sfrom\s(?P<oldVersion>.*?)\sto\s(?P<version>.*?)\son\s(?P<target>.*?)')
for line in salt.utils.itertools.split(output, '\n'):
match = install_pattern.match(line)
if match is None:
match = upgrade_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = match.group('version')
return reported_pkgs
def _execute_install_command(cmd, parse_output, errors, parsed_packages):
'''
Executes a command for the install operation.
If the command fails, its error output will be appended to the errors list.
If the command succeeds and parse_output is true, updated packages will be appended
to the parsed_packages dictionary.
'''
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors.append(out['stderr'])
else:
errors.append(out['stdout'])
elif parse_output:
parsed_packages.update(_parse_reported_packages_from_install_output(out['stdout']))
def install(name=None,
refresh=False,
pkgs=None,
sources=None,
reinstall=False,
**kwargs):
'''
Install the passed package, add refresh=True to update the opkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionadded:: 2017.7.0
reinstall : False
Specifying reinstall=True will use ``opkg install --force-reinstall``
rather than simply ``opkg install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``opkg
install --force-reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2017.7.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of IPK packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
install_recommends
Whether to install the packages marked as recommended. Default is True.
only_upgrade
Only upgrade the packages (disallow downgrades), if they are already
installed. Default is False.
.. versionadded:: 2017.7.0
always_restart_services
Whether to restart services even if a reboot is required. Default is True.
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
refreshdb = salt.utils.data.is_true(refresh)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
cmd_prefix = ['opkg', 'install']
to_install = []
to_reinstall = []
to_downgrade = []
_append_noaction_if_testmode(cmd_prefix, **kwargs)
if not pkg_params:
return {}
elif pkg_type == 'file':
if reinstall:
cmd_prefix.append('--force-reinstall')
if not kwargs.get('only_upgrade', False):
cmd_prefix.append('--force-downgrade')
to_install.extend(pkg_params)
elif pkg_type == 'repository':
if not kwargs.get('install_recommends', True):
cmd_prefix.append('--no-install-recommends')
for pkgname, pkgversion in six.iteritems(pkg_params):
if (name and pkgs is None and kwargs.get('version') and
len(pkg_params) == 1):
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
version_num = pkgversion
if version_num is None:
# Don't allow downgrades if the version
# number is not specified.
if reinstall and pkgname in old:
to_reinstall.append(pkgname)
else:
to_install.append(pkgname)
else:
pkgstr = '{0}={1}'.format(pkgname, version_num)
cver = old.get(pkgname, '')
if reinstall and cver and salt.utils.versions.compare(
ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall.append(pkgstr)
elif not cver or salt.utils.versions.compare(
ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
to_install.append(pkgstr)
else:
if not kwargs.get('only_upgrade', False):
to_downgrade.append(pkgstr)
else:
# This should cause the command to fail.
to_install.append(pkgstr)
cmds = _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall)
if not cmds:
return {}
if refreshdb:
refresh_db()
errors = []
is_testmode = _is_testmode(**kwargs)
test_packages = {}
for cmd in cmds:
_execute_install_command(cmd, is_testmode, errors, test_packages)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if is_testmode:
new = copy.deepcopy(new)
new.update(test_packages)
ret = salt.utils.data.compare_dicts(old, new)
if pkg_type == 'file' and reinstall:
# For file-based packages, prepare 'to_reinstall' to have a list
# of all the package names that may have been reinstalled.
# This way, we could include reinstalled packages in 'ret'.
for pkgfile in to_install:
# Convert from file name to package name.
cmd = ['opkg', 'info', pkgfile]
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] == 0:
# Just need the package name.
pkginfo_dict = _process_info_installed_output(
out['stdout'], []
)
if pkginfo_dict:
to_reinstall.append(list(pkginfo_dict.keys())[0])
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def _parse_reported_packages_from_remove_output(output):
'''
Parses the output of "opkg remove" to determine what packages would have been
removed by an operation run with the --noaction flag.
We are looking for lines like
Removing <package> (<version>) from <Target>...
'''
reported_pkgs = {}
remove_pattern = re.compile(r'Removing\s(?P<package>.*?)\s\((?P<version>.*?)\)\sfrom\s(?P<target>.*?)...')
for line in salt.utils.itertools.split(output, '\n'):
match = remove_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = ''
return reported_pkgs
def remove(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Remove packages using ``opkg remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
remove_dependencies
Remove package and all dependencies
.. versionadded:: 2019.2.0
auto_remove_deps
Remove packages that were installed automatically to satisfy dependencies
.. versionadded:: 2019.2.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
salt '*' pkg.remove pkgs='["foo", "bar"]' remove_dependencies=True auto_remove_deps=True
'''
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 {}
cmd = ['opkg', 'remove']
_append_noaction_if_testmode(cmd, **kwargs)
if kwargs.get('remove_dependencies', False):
cmd.append('--force-removal-of-dependent-packages')
if kwargs.get('auto_remove_deps', False):
cmd.append('--autoremove')
cmd.extend(targets)
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors = [out['stderr']]
else:
errors = [out['stdout']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if _is_testmode(**kwargs):
reportedPkgs = _parse_reported_packages_from_remove_output(out['stdout'])
new = {k: v for k, v in new.items() if k not in reportedPkgs}
ret = salt.utils.data.compare_dicts(old, new)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def purge(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Package purges are not supported by opkg, this function is identical to
:mod:`pkg.remove <salt.modules.opkg.remove>`.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name, pkgs=pkgs)
def upgrade(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
Upgrades all packages via ``opkg upgrade``
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
errors = []
if salt.utils.data.is_true(refresh):
refresh_db()
old = list_pkgs()
cmd = ['opkg', 'upgrade']
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
errors.append(result)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif state != 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = _set_state(target, 'hold')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif state == 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret['comment'] = ('Package {0} is set not to be held.'
.format(target))
else:
result = _set_state(target, 'ok')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def _get_state(pkg):
'''
View package state from the opkg database
Return the state of pkg
'''
cmd = ['opkg', 'status']
cmd.append(pkg)
out = __salt__['cmd.run'](cmd, python_shell=False)
state_flag = ''
for line in salt.utils.itertools.split(out, '\n'):
if line.startswith('Status'):
_status, _state_want, state_flag, _state_status = line.split()
return state_flag
def _set_state(pkg, state):
'''
Change package state on the opkg database
The state can be any of:
- hold
- noprune
- user
- ok
- installed
- unpacked
This command is commonly used to mark a specific package to be held from
being upgraded, that is, to be kept at a certain version.
Returns a dict containing the package name, and the new and old
versions.
'''
ret = {}
valid_states = ('hold', 'noprune', 'user', 'ok', 'installed', 'unpacked')
if state not in valid_states:
raise SaltInvocationError('Invalid state: {0}'.format(state))
oldstate = _get_state(pkg)
cmd = ['opkg', 'flag']
cmd.append(state)
cmd.append(pkg)
_out = __salt__['cmd.run'](cmd, python_shell=False)
# Missing return value check due to opkg issue 160
ret[pkg] = {'old': oldstate,
'new': state}
return ret
def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
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
cmd = ['opkg', 'list-installed']
ret = {}
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
# This is a continuation of package description
if not line or line[0] == ' ':
continue
# This contains package name, version, and description.
# Extract the first two.
pkg_name, pkg_version = line.split(' - ', 2)[:2]
__salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version)
__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 list_upgrades(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
List all available package upgrades.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
ret = {}
if salt.utils.data.is_true(refresh):
refresh_db()
cmd = ['opkg', 'list-upgradable']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
if 'stdout' in call:
comment += call['stdout']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
name, _oldversion, newversion = line.split(' - ')
ret[name] = newversion
return ret
def _convert_to_standard_attr(attr):
'''
Helper function for _process_info_installed_output()
Converts an opkg attribute name to a standard attribute
name which is used across 'pkg' modules.
'''
ret_attr = ATTR_MAP.get(attr, None)
if ret_attr is None:
# All others convert to lowercase
return attr.lower()
return ret_attr
def _process_info_installed_output(out, filter_attrs):
'''
Helper function for info_installed()
Processes stdout output from a single invocation of
'opkg status'.
'''
ret = {}
name = None
attrs = {}
attr = None
for line in salt.utils.itertools.split(out, '\n'):
if line and line[0] == ' ':
# This is a continuation of the last attr
if filter_attrs is None or attr in filter_attrs:
line = line.strip()
if attrs[attr]:
# If attr is empty, don't add leading newline
attrs[attr] += '\n'
attrs[attr] += line
continue
line = line.strip()
if not line:
# Separator between different packages
if name:
ret[name] = attrs
name = None
attrs = {}
attr = None
continue
key, value = line.split(':', 1)
value = value.lstrip()
attr = _convert_to_standard_attr(key)
if attr == 'name':
name = value
elif filter_attrs is None or attr in filter_attrs:
attrs[attr] = value
if name:
ret[name] = attrs
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
.. versionadded:: 2017.7.0
:param names:
Names of the packages to get information about. If none are specified,
will return information for all installed packages.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
arch, conffiles, conflicts, depends, description, filename, group,
install_date_time_t, md5sum, packager, provides, recommends,
replaces, size, source, suggests, url, version
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed
salt '*' pkg.info_installed attr=version,packager
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> attr=version,packager
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,packager
'''
attr = kwargs.pop('attr', None)
if attr is None:
filter_attrs = None
elif isinstance(attr, six.string_types):
filter_attrs = set(attr.split(','))
else:
filter_attrs = set(attr)
ret = {}
if names:
# Specific list of names of installed packages
for name in names:
cmd = ['opkg', 'status', name]
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
else:
# All installed packages
cmd = ['opkg', 'status']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
return ret
def upgrade_available(name, **kwargs): # pylint: disable=unused-argument
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs): # pylint: disable=unused-argument
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2016.3.4
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0' '0.2.4.1-0'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] if ignore_epoch else six.text_type(x)
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
output = __salt__['cmd.run_stdout'](['opkg', '--version'],
output_loglevel='trace',
python_shell=False)
opkg_version = output.split(' ')[2].strip()
if salt.utils.versions.LooseVersion(opkg_version) >= \
salt.utils.versions.LooseVersion('0.3.4'):
cmd_compare = ['opkg', 'compare-versions']
elif salt.utils.path.which('opkg-compare-versions'):
cmd_compare = ['opkg-compare-versions']
else:
log.warning('Unable to find a compare-versions utility installed. Either upgrade opkg to '
'version > 0.3.4 (preferred) or install the older opkg-compare-versions script.')
return None
for oper, ret in (("<<", -1), ("=", 0), (">>", 1)):
cmd = cmd_compare[:]
cmd.append(_cmd_quote(pkg1))
cmd.append(oper)
cmd.append(_cmd_quote(pkg2))
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
ignore_retcode=True,
python_shell=False)
if retcode == 0:
return ret
return None
def _set_repo_option(repo, option):
'''
Set the option to repo
'''
if not option:
return
opt = option.split('=')
if len(opt) != 2:
return
if opt[0] == 'trusted':
repo['trusted'] = opt[1] == 'yes'
else:
repo[opt[0]] = opt[1]
def _set_repo_options(repo, options):
'''
Set the options to the repo.
'''
delimiters = "[", "]"
pattern = '|'.join(map(re.escape, delimiters))
for option in options:
splitted = re.split(pattern, option)
for opt in splitted:
_set_repo_option(repo, opt)
def _read_repos(conf_file, repos, filename, regex):
'''
Read repos from configuration file
'''
for line in conf_file:
line = salt.utils.stringutils.to_unicode(line)
if not regex.search(line):
continue
repo = _create_repo(line, filename)
# do not store duplicated uri's
if repo['uri'] not in repos:
repos[repo['uri']] = [repo]
def list_repos(**kwargs): # pylint: disable=unused-argument
'''
Lists all repos on ``/etc/opkg/*.conf``
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos = {}
regex = re.compile(REPO_REGEXP)
for filename in os.listdir(OPKG_CONFDIR):
if not filename.endswith(".conf"):
continue
with salt.utils.files.fopen(os.path.join(OPKG_CONFDIR, filename)) as conf_file:
_read_repos(conf_file, repos, filename, regex)
return repos
def get_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Display a repo from the ``/etc/opkg/*.conf``
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo repo
'''
repos = list_repos()
if repos:
for source in six.itervalues(repos):
for sub in source:
if sub['name'] == repo:
return sub
return {}
def _del_repo_from_file(repo, filepath):
'''
Remove a repo from filepath
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
regex = re.compile(REPO_REGEXP)
for line in fhandle:
line = salt.utils.stringutils.to_unicode(line)
if regex.search(line):
if line.startswith('#'):
line = line[1:]
cols = salt.utils.args.shlex_split(line.strip())
if repo != cols[1]:
output.append(salt.utils.stringutils.to_str(line))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def _set_trusted_option_if_needed(repostr, trusted):
'''
Set trusted option to repo if needed
'''
if trusted is True:
repostr += ' [trusted=yes]'
elif trusted is False:
repostr += ' [trusted=no]'
return repostr
def _add_new_repo(repo, properties):
'''
Add a new repo entry
'''
repostr = '# ' if not properties.get('enabled') else ''
repostr += 'src/gz ' if properties.get('compressed') else 'src '
if ' ' in repo:
repostr += '"' + repo + '" '
else:
repostr += repo + ' '
repostr += properties.get('uri')
repostr = _set_trusted_option_if_needed(repostr, properties.get('trusted'))
repostr += '\n'
conffile = os.path.join(OPKG_CONFDIR, repo + '.conf')
with salt.utils.files.fopen(conffile, 'a') as fhandle:
fhandle.write(salt.utils.stringutils.to_str(repostr))
def _mod_repo_in_file(repo, repostr, filepath):
'''
Replace a repo entry in filepath with repostr
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
for line in fhandle:
cols = salt.utils.args.shlex_split(
salt.utils.stringutils.to_unicode(line).strip()
)
if repo not in cols:
output.append(line)
else:
output.append(salt.utils.stringutils.to_str(repostr + '\n'))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def del_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Delete a repo from ``/etc/opkg/*.conf``
If the file does not contain any other repo configuration, the file itself
will be deleted.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo repo
'''
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
repos = list_repos()
if repos:
deleted_from = dict()
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
deleted_from[source['file']] = 0
_del_repo_from_file(repo, source['file'])
if deleted_from:
ret = ''
for repository in repos:
source = repos[repository][0]
if source['file'] in deleted_from:
deleted_from[source['file']] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 1 and os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.\n')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
if refresh:
refresh_db()
return ret
return "Repo {0} doesn't exist in the opkg repo lists".format(repo)
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as uri is defined.
The following options are available to modify a repo definition:
repo
alias by which opkg refers to the repo.
uri
the URI to the repo.
compressed
defines (True or False) if the index file is compressed
enabled
enable or disable (True or False) repository
but do not remove if disabled.
refresh
enable or disable (True or False) auto-refresh of the repositories
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo repo uri=http://new/uri
salt '*' pkg.mod_repo repo enabled=False
'''
repos = list_repos()
found = False
uri = ''
if 'uri' in kwargs:
uri = kwargs['uri']
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
found = True
repostr = ''
if 'enabled' in kwargs and not kwargs['enabled']:
repostr += '# '
if 'compressed' in kwargs:
repostr += 'src/gz ' if kwargs['compressed'] else 'src'
else:
repostr += 'src/gz' if source['compressed'] else 'src'
repo_alias = kwargs['alias'] if 'alias' in kwargs else repo
if ' ' in repo_alias:
repostr += ' "{0}"'.format(repo_alias)
else:
repostr += ' {0}'.format(repo_alias)
repostr += ' {0}'.format(kwargs['uri'] if 'uri' in kwargs else source['uri'])
trusted = kwargs.get('trusted')
repostr = _set_trusted_option_if_needed(repostr, trusted) if trusted is not None else \
_set_trusted_option_if_needed(repostr, source.get('trusted'))
_mod_repo_in_file(repo, repostr, source['file'])
elif uri and source['uri'] == uri:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(uri, source['name']))
if not found:
# Need to add a new repo
if 'uri' not in kwargs:
raise CommandExecutionError(
'Repository \'{0}\' not found and no URI passed to create one.'.format(repo))
properties = {'uri': kwargs['uri']}
# If compressed is not defined, assume True
properties['compressed'] = kwargs['compressed'] if 'compressed' in kwargs else True
# If enabled is not defined, assume True
properties['enabled'] = kwargs['enabled'] if 'enabled' in kwargs else True
properties['trusted'] = kwargs.get('trusted')
_add_new_repo(repo, properties)
if 'refresh' in kwargs:
refresh_db()
def file_list(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
output = file_dict(*packages)
files = []
for package in list(output['packages'].values()):
files.extend(package)
return {'errors': output['errors'], 'files': files}
def file_dict(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
errors = []
ret = {}
cmd_files = ['opkg', 'files']
if not packages:
packages = list(list_pkgs().keys())
for package in packages:
files = []
cmd = cmd_files[:]
cmd.append(package)
out = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
for line in out['stdout'].splitlines():
if line.startswith('/'):
files.append(line)
elif line.startswith(' * '):
errors.append(line[3:])
break
else:
continue
if files:
ret[package] = files
return {'errors': errors, 'packages': ret}
def owner(*paths, **kwargs): # pylint: disable=unused-argument
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.opkg.version`, if a single
path is passed, a string will be returned, and if multiple paths are passed,
a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
cmd_search = ['opkg', 'search']
for path in paths:
cmd = cmd_search[:]
cmd.append(path)
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
if output:
ret[path] = output.split(' - ')[0].strip()
else:
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def version_clean(version):
'''
Clean the version string removing extra data.
There's nothing do to here for nipkg.py, therefore it will always
return the given version.
'''
return version
def check_extra_requirements(pkgname, pkgver):
'''
Check if the installed package already has the given requirements.
There's nothing do to here for nipkg.py, therefore it will always
return True.
'''
return True
|
saltstack/salt
|
salt/modules/opkg.py
|
_read_repos
|
python
|
def _read_repos(conf_file, repos, filename, regex):
'''
Read repos from configuration file
'''
for line in conf_file:
line = salt.utils.stringutils.to_unicode(line)
if not regex.search(line):
continue
repo = _create_repo(line, filename)
# do not store duplicated uri's
if repo['uri'] not in repos:
repos[repo['uri']] = [repo]
|
Read repos from configuration file
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/opkg.py#L1294-L1306
|
[
"def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n",
"def _create_repo(line, filename):\n '''\n Create repo\n '''\n repo = {}\n if line.startswith('#'):\n repo['enabled'] = False\n line = line[1:]\n else:\n repo['enabled'] = True\n cols = salt.utils.args.shlex_split(line.strip())\n repo['compressed'] = not cols[0] in 'src'\n repo['name'] = cols[1]\n repo['uri'] = cols[2]\n repo['file'] = os.path.join(OPKG_CONFDIR, filename)\n if len(cols) > 3:\n _set_repo_options(repo, cols[3:])\n return repo\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Opkg
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
.. versionadded: 2016.3.0
.. note::
For version comparison support on opkg < 0.3.4, the ``opkg-utils`` package
must be installed.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import os
import re
import logging
import errno
# Import salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.itertools
import salt.utils.path
import salt.utils.pkg
import salt.utils.stringutils
import salt.utils.versions
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import shlex_quote as _cmd_quote # pylint: disable=import-error
from salt.ext.six.moves import map # pylint: disable=import-error,redefined-builtin
REPO_REGEXP = r'^#?\s*(src|src/gz)\s+([^\s<>]+|"[^<>]+")\s+[^\s<>]+'
OPKG_CONFDIR = '/etc/opkg'
ATTR_MAP = {
'Architecture': 'arch',
'Homepage': 'url',
'Installed-Time': 'install_date_time_t',
'Maintainer': 'packager',
'Package': 'name',
'Section': 'group'
}
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
NILRT_RESTARTCHECK_STATE_PATH = '/var/lib/salt/restartcheck_state'
def _update_nilrt_restart_state():
'''
NILRT systems determine whether to reboot after various package operations
including but not limited to kernel module installs/removals by checking
specific file md5sums & timestamps. These files are touched/modified by
the post-install/post-remove functions of their respective packages.
The opkg module uses this function to store/update those file timestamps
and checksums to be used later by the restartcheck module.
'''
__salt__['cmd.shell']('stat -c %Y /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.timestamp'
.format(NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.md5sum'
.format(NILRT_RESTARTCHECK_STATE_PATH))
# We can't assume nisysapi.ini always exists like modules.dep
nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'
if os.path.exists(nisysapi_path):
__salt__['cmd.shell']('stat -c %Y {0} >{1}/nisysapi.ini.timestamp'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0} >{1}/nisysapi.ini.md5sum'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
# Expert plugin files get added to a conf.d dir, so keep track of the total
# no. of files, their timestamps and content hashes
nisysapi_conf_d_path = "/usr/lib/{0}/nisysapi/conf.d/experts/".format(
'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'
)
if os.path.exists(nisysapi_conf_d_path):
with salt.utils.files.fopen('{0}/sysapi.conf.d.count'.format(
NILRT_RESTARTCHECK_STATE_PATH), 'w') as fcount:
fcount.write(str(len(os.listdir(nisysapi_conf_d_path))))
for fexpert in os.listdir(nisysapi_conf_d_path):
__salt__['cmd.shell']('stat -c %Y {0}/{1} >{2}/{1}.timestamp'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0}/{1} >{2}/{1}.md5sum'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
def _get_restartcheck_result(errors):
'''
Return restartcheck result and append errors (if any) to ``errors``
'''
rs_result = __salt__['restartcheck.restartcheck'](verbose=False)
if isinstance(rs_result, dict) and 'comment' in rs_result:
errors.append(rs_result['comment'])
return rs_result
def _process_restartcheck_result(rs_result, **kwargs):
'''
Check restartcheck output to see if system/service restarts were requested
and take appropriate action.
'''
if 'No packages seem to need to be restarted' in rs_result:
return
reboot_required = False
for rstr in rs_result:
if 'System restart required' in rstr:
_update_nilrt_restart_state()
__salt__['system.set_reboot_required_witnessed']()
reboot_required = True
if kwargs.get('always_restart_services', True) or not reboot_required:
for rstr in rs_result:
if 'System restart required' not in rstr:
service = os.path.join('/etc/init.d', rstr)
if os.path.exists(service):
__salt__['cmd.run']([service, 'restart'])
def __virtual__():
'''
Confirm this module is on a nilrt based system
'''
if __grains__.get('os_family') == 'NILinuxRT':
try:
os.makedirs(NILRT_RESTARTCHECK_STATE_PATH)
except OSError as exc:
if exc.errno != errno.EEXIST:
return False, 'Error creating {0} (-{1}): {2}'.format(
NILRT_RESTARTCHECK_STATE_PATH,
exc.errno,
exc.strerror)
# populate state dir if empty
if not os.listdir(NILRT_RESTARTCHECK_STATE_PATH):
_update_nilrt_restart_state()
return __virtualname__
if os.path.isdir(OPKG_CONFDIR):
return __virtualname__
return False, "Module opkg only works on OpenEmbedded based systems"
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
if not names:
return ''
ret = {}
for name in names:
ret[name] = ''
# Refresh before looking for the latest version available
if refresh:
refresh_db()
cmd = ['opkg', 'list-upgradable']
out = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
try:
name, _oldversion, newversion = line.split(' - ')
if name in names:
ret[name] = newversion
except ValueError:
pass
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = latest_version
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(failhard=False, **kwargs): # pylint: disable=unused-argument
'''
Updates the opkg database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
failhard
If False, return results of failed lines as ``False`` for the package
database that encountered the error.
If True, raise an error with a list of the package databases that
encountered errors.
.. versionadded:: 2018.3.0
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
error_repos = []
cmd = ['opkg', 'update']
# opkg returns a non-zero retcode when there is a failure to refresh
# from one or more repos. Due to this, ignore the retcode.
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True,
redirect_stderr=True)
out = call['stdout']
prev_line = ''
for line in salt.utils.itertools.split(out, '\n'):
if 'Inflating' in line:
key = line.strip().split()[1][:-1]
ret[key] = True
elif 'Updated source' in line:
# Use the previous line.
key = prev_line.strip().split()[1][:-1]
ret[key] = True
elif 'Failed to download' in line:
key = line.strip().split()[5].split(',')[0]
ret[key] = False
error_repos.append(key)
prev_line = line
if failhard and error_repos:
raise CommandExecutionError(
'Error getting repos: {0}'.format(', '.join(error_repos))
)
# On a non-zero exit code where no failed repos were found, raise an
# exception because this appears to be a different kind of error.
if call['retcode'] != 0 and not error_repos:
raise CommandExecutionError(out)
return ret
def _is_testmode(**kwargs):
'''
Returns whether a test mode (noaction) operation was requested.
'''
return bool(kwargs.get('test') or __opts__.get('test'))
def _append_noaction_if_testmode(cmd, **kwargs):
'''
Adds the --noaction flag to the command if it's running in the test mode.
'''
if _is_testmode(**kwargs):
cmd.append('--noaction')
def _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall):
'''
Builds a list of install commands to be executed in sequence in order to process
each of the to_install, to_downgrade, and to_reinstall lists.
'''
cmds = []
if to_install:
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(to_install)
cmds.append(cmd)
if to_downgrade:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-downgrade')
cmd.extend(to_downgrade)
cmds.append(cmd)
if to_reinstall:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-reinstall')
cmd.extend(to_reinstall)
cmds.append(cmd)
return cmds
def _parse_reported_packages_from_install_output(output):
'''
Parses the output of "opkg install" to determine what packages would have been
installed by an operation run with the --noaction flag.
We are looking for lines like:
Installing <package> (<version>) on <target>
or
Upgrading <package> from <oldVersion> to <version> on root
'''
reported_pkgs = {}
install_pattern = re.compile(r'Installing\s(?P<package>.*?)\s\((?P<version>.*?)\)\son\s(?P<target>.*?)')
upgrade_pattern = re.compile(r'Upgrading\s(?P<package>.*?)\sfrom\s(?P<oldVersion>.*?)\sto\s(?P<version>.*?)\son\s(?P<target>.*?)')
for line in salt.utils.itertools.split(output, '\n'):
match = install_pattern.match(line)
if match is None:
match = upgrade_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = match.group('version')
return reported_pkgs
def _execute_install_command(cmd, parse_output, errors, parsed_packages):
'''
Executes a command for the install operation.
If the command fails, its error output will be appended to the errors list.
If the command succeeds and parse_output is true, updated packages will be appended
to the parsed_packages dictionary.
'''
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors.append(out['stderr'])
else:
errors.append(out['stdout'])
elif parse_output:
parsed_packages.update(_parse_reported_packages_from_install_output(out['stdout']))
def install(name=None,
refresh=False,
pkgs=None,
sources=None,
reinstall=False,
**kwargs):
'''
Install the passed package, add refresh=True to update the opkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionadded:: 2017.7.0
reinstall : False
Specifying reinstall=True will use ``opkg install --force-reinstall``
rather than simply ``opkg install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``opkg
install --force-reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2017.7.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of IPK packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
install_recommends
Whether to install the packages marked as recommended. Default is True.
only_upgrade
Only upgrade the packages (disallow downgrades), if they are already
installed. Default is False.
.. versionadded:: 2017.7.0
always_restart_services
Whether to restart services even if a reboot is required. Default is True.
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
refreshdb = salt.utils.data.is_true(refresh)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
cmd_prefix = ['opkg', 'install']
to_install = []
to_reinstall = []
to_downgrade = []
_append_noaction_if_testmode(cmd_prefix, **kwargs)
if not pkg_params:
return {}
elif pkg_type == 'file':
if reinstall:
cmd_prefix.append('--force-reinstall')
if not kwargs.get('only_upgrade', False):
cmd_prefix.append('--force-downgrade')
to_install.extend(pkg_params)
elif pkg_type == 'repository':
if not kwargs.get('install_recommends', True):
cmd_prefix.append('--no-install-recommends')
for pkgname, pkgversion in six.iteritems(pkg_params):
if (name and pkgs is None and kwargs.get('version') and
len(pkg_params) == 1):
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
version_num = pkgversion
if version_num is None:
# Don't allow downgrades if the version
# number is not specified.
if reinstall and pkgname in old:
to_reinstall.append(pkgname)
else:
to_install.append(pkgname)
else:
pkgstr = '{0}={1}'.format(pkgname, version_num)
cver = old.get(pkgname, '')
if reinstall and cver and salt.utils.versions.compare(
ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall.append(pkgstr)
elif not cver or salt.utils.versions.compare(
ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
to_install.append(pkgstr)
else:
if not kwargs.get('only_upgrade', False):
to_downgrade.append(pkgstr)
else:
# This should cause the command to fail.
to_install.append(pkgstr)
cmds = _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall)
if not cmds:
return {}
if refreshdb:
refresh_db()
errors = []
is_testmode = _is_testmode(**kwargs)
test_packages = {}
for cmd in cmds:
_execute_install_command(cmd, is_testmode, errors, test_packages)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if is_testmode:
new = copy.deepcopy(new)
new.update(test_packages)
ret = salt.utils.data.compare_dicts(old, new)
if pkg_type == 'file' and reinstall:
# For file-based packages, prepare 'to_reinstall' to have a list
# of all the package names that may have been reinstalled.
# This way, we could include reinstalled packages in 'ret'.
for pkgfile in to_install:
# Convert from file name to package name.
cmd = ['opkg', 'info', pkgfile]
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] == 0:
# Just need the package name.
pkginfo_dict = _process_info_installed_output(
out['stdout'], []
)
if pkginfo_dict:
to_reinstall.append(list(pkginfo_dict.keys())[0])
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def _parse_reported_packages_from_remove_output(output):
'''
Parses the output of "opkg remove" to determine what packages would have been
removed by an operation run with the --noaction flag.
We are looking for lines like
Removing <package> (<version>) from <Target>...
'''
reported_pkgs = {}
remove_pattern = re.compile(r'Removing\s(?P<package>.*?)\s\((?P<version>.*?)\)\sfrom\s(?P<target>.*?)...')
for line in salt.utils.itertools.split(output, '\n'):
match = remove_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = ''
return reported_pkgs
def remove(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Remove packages using ``opkg remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
remove_dependencies
Remove package and all dependencies
.. versionadded:: 2019.2.0
auto_remove_deps
Remove packages that were installed automatically to satisfy dependencies
.. versionadded:: 2019.2.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
salt '*' pkg.remove pkgs='["foo", "bar"]' remove_dependencies=True auto_remove_deps=True
'''
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 {}
cmd = ['opkg', 'remove']
_append_noaction_if_testmode(cmd, **kwargs)
if kwargs.get('remove_dependencies', False):
cmd.append('--force-removal-of-dependent-packages')
if kwargs.get('auto_remove_deps', False):
cmd.append('--autoremove')
cmd.extend(targets)
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors = [out['stderr']]
else:
errors = [out['stdout']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if _is_testmode(**kwargs):
reportedPkgs = _parse_reported_packages_from_remove_output(out['stdout'])
new = {k: v for k, v in new.items() if k not in reportedPkgs}
ret = salt.utils.data.compare_dicts(old, new)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def purge(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Package purges are not supported by opkg, this function is identical to
:mod:`pkg.remove <salt.modules.opkg.remove>`.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name, pkgs=pkgs)
def upgrade(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
Upgrades all packages via ``opkg upgrade``
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
errors = []
if salt.utils.data.is_true(refresh):
refresh_db()
old = list_pkgs()
cmd = ['opkg', 'upgrade']
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
errors.append(result)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif state != 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = _set_state(target, 'hold')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif state == 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret['comment'] = ('Package {0} is set not to be held.'
.format(target))
else:
result = _set_state(target, 'ok')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def _get_state(pkg):
'''
View package state from the opkg database
Return the state of pkg
'''
cmd = ['opkg', 'status']
cmd.append(pkg)
out = __salt__['cmd.run'](cmd, python_shell=False)
state_flag = ''
for line in salt.utils.itertools.split(out, '\n'):
if line.startswith('Status'):
_status, _state_want, state_flag, _state_status = line.split()
return state_flag
def _set_state(pkg, state):
'''
Change package state on the opkg database
The state can be any of:
- hold
- noprune
- user
- ok
- installed
- unpacked
This command is commonly used to mark a specific package to be held from
being upgraded, that is, to be kept at a certain version.
Returns a dict containing the package name, and the new and old
versions.
'''
ret = {}
valid_states = ('hold', 'noprune', 'user', 'ok', 'installed', 'unpacked')
if state not in valid_states:
raise SaltInvocationError('Invalid state: {0}'.format(state))
oldstate = _get_state(pkg)
cmd = ['opkg', 'flag']
cmd.append(state)
cmd.append(pkg)
_out = __salt__['cmd.run'](cmd, python_shell=False)
# Missing return value check due to opkg issue 160
ret[pkg] = {'old': oldstate,
'new': state}
return ret
def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
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
cmd = ['opkg', 'list-installed']
ret = {}
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
# This is a continuation of package description
if not line or line[0] == ' ':
continue
# This contains package name, version, and description.
# Extract the first two.
pkg_name, pkg_version = line.split(' - ', 2)[:2]
__salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version)
__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 list_upgrades(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
List all available package upgrades.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
ret = {}
if salt.utils.data.is_true(refresh):
refresh_db()
cmd = ['opkg', 'list-upgradable']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
if 'stdout' in call:
comment += call['stdout']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
name, _oldversion, newversion = line.split(' - ')
ret[name] = newversion
return ret
def _convert_to_standard_attr(attr):
'''
Helper function for _process_info_installed_output()
Converts an opkg attribute name to a standard attribute
name which is used across 'pkg' modules.
'''
ret_attr = ATTR_MAP.get(attr, None)
if ret_attr is None:
# All others convert to lowercase
return attr.lower()
return ret_attr
def _process_info_installed_output(out, filter_attrs):
'''
Helper function for info_installed()
Processes stdout output from a single invocation of
'opkg status'.
'''
ret = {}
name = None
attrs = {}
attr = None
for line in salt.utils.itertools.split(out, '\n'):
if line and line[0] == ' ':
# This is a continuation of the last attr
if filter_attrs is None or attr in filter_attrs:
line = line.strip()
if attrs[attr]:
# If attr is empty, don't add leading newline
attrs[attr] += '\n'
attrs[attr] += line
continue
line = line.strip()
if not line:
# Separator between different packages
if name:
ret[name] = attrs
name = None
attrs = {}
attr = None
continue
key, value = line.split(':', 1)
value = value.lstrip()
attr = _convert_to_standard_attr(key)
if attr == 'name':
name = value
elif filter_attrs is None or attr in filter_attrs:
attrs[attr] = value
if name:
ret[name] = attrs
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
.. versionadded:: 2017.7.0
:param names:
Names of the packages to get information about. If none are specified,
will return information for all installed packages.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
arch, conffiles, conflicts, depends, description, filename, group,
install_date_time_t, md5sum, packager, provides, recommends,
replaces, size, source, suggests, url, version
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed
salt '*' pkg.info_installed attr=version,packager
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> attr=version,packager
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,packager
'''
attr = kwargs.pop('attr', None)
if attr is None:
filter_attrs = None
elif isinstance(attr, six.string_types):
filter_attrs = set(attr.split(','))
else:
filter_attrs = set(attr)
ret = {}
if names:
# Specific list of names of installed packages
for name in names:
cmd = ['opkg', 'status', name]
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
else:
# All installed packages
cmd = ['opkg', 'status']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
return ret
def upgrade_available(name, **kwargs): # pylint: disable=unused-argument
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs): # pylint: disable=unused-argument
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2016.3.4
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0' '0.2.4.1-0'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] if ignore_epoch else six.text_type(x)
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
output = __salt__['cmd.run_stdout'](['opkg', '--version'],
output_loglevel='trace',
python_shell=False)
opkg_version = output.split(' ')[2].strip()
if salt.utils.versions.LooseVersion(opkg_version) >= \
salt.utils.versions.LooseVersion('0.3.4'):
cmd_compare = ['opkg', 'compare-versions']
elif salt.utils.path.which('opkg-compare-versions'):
cmd_compare = ['opkg-compare-versions']
else:
log.warning('Unable to find a compare-versions utility installed. Either upgrade opkg to '
'version > 0.3.4 (preferred) or install the older opkg-compare-versions script.')
return None
for oper, ret in (("<<", -1), ("=", 0), (">>", 1)):
cmd = cmd_compare[:]
cmd.append(_cmd_quote(pkg1))
cmd.append(oper)
cmd.append(_cmd_quote(pkg2))
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
ignore_retcode=True,
python_shell=False)
if retcode == 0:
return ret
return None
def _set_repo_option(repo, option):
'''
Set the option to repo
'''
if not option:
return
opt = option.split('=')
if len(opt) != 2:
return
if opt[0] == 'trusted':
repo['trusted'] = opt[1] == 'yes'
else:
repo[opt[0]] = opt[1]
def _set_repo_options(repo, options):
'''
Set the options to the repo.
'''
delimiters = "[", "]"
pattern = '|'.join(map(re.escape, delimiters))
for option in options:
splitted = re.split(pattern, option)
for opt in splitted:
_set_repo_option(repo, opt)
def _create_repo(line, filename):
'''
Create repo
'''
repo = {}
if line.startswith('#'):
repo['enabled'] = False
line = line[1:]
else:
repo['enabled'] = True
cols = salt.utils.args.shlex_split(line.strip())
repo['compressed'] = not cols[0] in 'src'
repo['name'] = cols[1]
repo['uri'] = cols[2]
repo['file'] = os.path.join(OPKG_CONFDIR, filename)
if len(cols) > 3:
_set_repo_options(repo, cols[3:])
return repo
def list_repos(**kwargs): # pylint: disable=unused-argument
'''
Lists all repos on ``/etc/opkg/*.conf``
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos = {}
regex = re.compile(REPO_REGEXP)
for filename in os.listdir(OPKG_CONFDIR):
if not filename.endswith(".conf"):
continue
with salt.utils.files.fopen(os.path.join(OPKG_CONFDIR, filename)) as conf_file:
_read_repos(conf_file, repos, filename, regex)
return repos
def get_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Display a repo from the ``/etc/opkg/*.conf``
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo repo
'''
repos = list_repos()
if repos:
for source in six.itervalues(repos):
for sub in source:
if sub['name'] == repo:
return sub
return {}
def _del_repo_from_file(repo, filepath):
'''
Remove a repo from filepath
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
regex = re.compile(REPO_REGEXP)
for line in fhandle:
line = salt.utils.stringutils.to_unicode(line)
if regex.search(line):
if line.startswith('#'):
line = line[1:]
cols = salt.utils.args.shlex_split(line.strip())
if repo != cols[1]:
output.append(salt.utils.stringutils.to_str(line))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def _set_trusted_option_if_needed(repostr, trusted):
'''
Set trusted option to repo if needed
'''
if trusted is True:
repostr += ' [trusted=yes]'
elif trusted is False:
repostr += ' [trusted=no]'
return repostr
def _add_new_repo(repo, properties):
'''
Add a new repo entry
'''
repostr = '# ' if not properties.get('enabled') else ''
repostr += 'src/gz ' if properties.get('compressed') else 'src '
if ' ' in repo:
repostr += '"' + repo + '" '
else:
repostr += repo + ' '
repostr += properties.get('uri')
repostr = _set_trusted_option_if_needed(repostr, properties.get('trusted'))
repostr += '\n'
conffile = os.path.join(OPKG_CONFDIR, repo + '.conf')
with salt.utils.files.fopen(conffile, 'a') as fhandle:
fhandle.write(salt.utils.stringutils.to_str(repostr))
def _mod_repo_in_file(repo, repostr, filepath):
'''
Replace a repo entry in filepath with repostr
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
for line in fhandle:
cols = salt.utils.args.shlex_split(
salt.utils.stringutils.to_unicode(line).strip()
)
if repo not in cols:
output.append(line)
else:
output.append(salt.utils.stringutils.to_str(repostr + '\n'))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def del_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Delete a repo from ``/etc/opkg/*.conf``
If the file does not contain any other repo configuration, the file itself
will be deleted.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo repo
'''
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
repos = list_repos()
if repos:
deleted_from = dict()
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
deleted_from[source['file']] = 0
_del_repo_from_file(repo, source['file'])
if deleted_from:
ret = ''
for repository in repos:
source = repos[repository][0]
if source['file'] in deleted_from:
deleted_from[source['file']] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 1 and os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.\n')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
if refresh:
refresh_db()
return ret
return "Repo {0} doesn't exist in the opkg repo lists".format(repo)
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as uri is defined.
The following options are available to modify a repo definition:
repo
alias by which opkg refers to the repo.
uri
the URI to the repo.
compressed
defines (True or False) if the index file is compressed
enabled
enable or disable (True or False) repository
but do not remove if disabled.
refresh
enable or disable (True or False) auto-refresh of the repositories
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo repo uri=http://new/uri
salt '*' pkg.mod_repo repo enabled=False
'''
repos = list_repos()
found = False
uri = ''
if 'uri' in kwargs:
uri = kwargs['uri']
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
found = True
repostr = ''
if 'enabled' in kwargs and not kwargs['enabled']:
repostr += '# '
if 'compressed' in kwargs:
repostr += 'src/gz ' if kwargs['compressed'] else 'src'
else:
repostr += 'src/gz' if source['compressed'] else 'src'
repo_alias = kwargs['alias'] if 'alias' in kwargs else repo
if ' ' in repo_alias:
repostr += ' "{0}"'.format(repo_alias)
else:
repostr += ' {0}'.format(repo_alias)
repostr += ' {0}'.format(kwargs['uri'] if 'uri' in kwargs else source['uri'])
trusted = kwargs.get('trusted')
repostr = _set_trusted_option_if_needed(repostr, trusted) if trusted is not None else \
_set_trusted_option_if_needed(repostr, source.get('trusted'))
_mod_repo_in_file(repo, repostr, source['file'])
elif uri and source['uri'] == uri:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(uri, source['name']))
if not found:
# Need to add a new repo
if 'uri' not in kwargs:
raise CommandExecutionError(
'Repository \'{0}\' not found and no URI passed to create one.'.format(repo))
properties = {'uri': kwargs['uri']}
# If compressed is not defined, assume True
properties['compressed'] = kwargs['compressed'] if 'compressed' in kwargs else True
# If enabled is not defined, assume True
properties['enabled'] = kwargs['enabled'] if 'enabled' in kwargs else True
properties['trusted'] = kwargs.get('trusted')
_add_new_repo(repo, properties)
if 'refresh' in kwargs:
refresh_db()
def file_list(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
output = file_dict(*packages)
files = []
for package in list(output['packages'].values()):
files.extend(package)
return {'errors': output['errors'], 'files': files}
def file_dict(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
errors = []
ret = {}
cmd_files = ['opkg', 'files']
if not packages:
packages = list(list_pkgs().keys())
for package in packages:
files = []
cmd = cmd_files[:]
cmd.append(package)
out = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
for line in out['stdout'].splitlines():
if line.startswith('/'):
files.append(line)
elif line.startswith(' * '):
errors.append(line[3:])
break
else:
continue
if files:
ret[package] = files
return {'errors': errors, 'packages': ret}
def owner(*paths, **kwargs): # pylint: disable=unused-argument
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.opkg.version`, if a single
path is passed, a string will be returned, and if multiple paths are passed,
a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
cmd_search = ['opkg', 'search']
for path in paths:
cmd = cmd_search[:]
cmd.append(path)
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
if output:
ret[path] = output.split(' - ')[0].strip()
else:
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def version_clean(version):
'''
Clean the version string removing extra data.
There's nothing do to here for nipkg.py, therefore it will always
return the given version.
'''
return version
def check_extra_requirements(pkgname, pkgver):
'''
Check if the installed package already has the given requirements.
There's nothing do to here for nipkg.py, therefore it will always
return True.
'''
return True
|
saltstack/salt
|
salt/modules/opkg.py
|
list_repos
|
python
|
def list_repos(**kwargs): # pylint: disable=unused-argument
'''
Lists all repos on ``/etc/opkg/*.conf``
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos = {}
regex = re.compile(REPO_REGEXP)
for filename in os.listdir(OPKG_CONFDIR):
if not filename.endswith(".conf"):
continue
with salt.utils.files.fopen(os.path.join(OPKG_CONFDIR, filename)) as conf_file:
_read_repos(conf_file, repos, filename, regex)
return repos
|
Lists all repos on ``/etc/opkg/*.conf``
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/opkg.py#L1309-L1326
|
[
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n",
"def _read_repos(conf_file, repos, filename, regex):\n '''\n Read repos from configuration file\n '''\n for line in conf_file:\n line = salt.utils.stringutils.to_unicode(line)\n if not regex.search(line):\n continue\n repo = _create_repo(line, filename)\n\n # do not store duplicated uri's\n if repo['uri'] not in repos:\n repos[repo['uri']] = [repo]\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Opkg
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
.. versionadded: 2016.3.0
.. note::
For version comparison support on opkg < 0.3.4, the ``opkg-utils`` package
must be installed.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import os
import re
import logging
import errno
# Import salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.itertools
import salt.utils.path
import salt.utils.pkg
import salt.utils.stringutils
import salt.utils.versions
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import shlex_quote as _cmd_quote # pylint: disable=import-error
from salt.ext.six.moves import map # pylint: disable=import-error,redefined-builtin
REPO_REGEXP = r'^#?\s*(src|src/gz)\s+([^\s<>]+|"[^<>]+")\s+[^\s<>]+'
OPKG_CONFDIR = '/etc/opkg'
ATTR_MAP = {
'Architecture': 'arch',
'Homepage': 'url',
'Installed-Time': 'install_date_time_t',
'Maintainer': 'packager',
'Package': 'name',
'Section': 'group'
}
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
NILRT_RESTARTCHECK_STATE_PATH = '/var/lib/salt/restartcheck_state'
def _update_nilrt_restart_state():
'''
NILRT systems determine whether to reboot after various package operations
including but not limited to kernel module installs/removals by checking
specific file md5sums & timestamps. These files are touched/modified by
the post-install/post-remove functions of their respective packages.
The opkg module uses this function to store/update those file timestamps
and checksums to be used later by the restartcheck module.
'''
__salt__['cmd.shell']('stat -c %Y /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.timestamp'
.format(NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.md5sum'
.format(NILRT_RESTARTCHECK_STATE_PATH))
# We can't assume nisysapi.ini always exists like modules.dep
nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'
if os.path.exists(nisysapi_path):
__salt__['cmd.shell']('stat -c %Y {0} >{1}/nisysapi.ini.timestamp'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0} >{1}/nisysapi.ini.md5sum'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
# Expert plugin files get added to a conf.d dir, so keep track of the total
# no. of files, their timestamps and content hashes
nisysapi_conf_d_path = "/usr/lib/{0}/nisysapi/conf.d/experts/".format(
'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'
)
if os.path.exists(nisysapi_conf_d_path):
with salt.utils.files.fopen('{0}/sysapi.conf.d.count'.format(
NILRT_RESTARTCHECK_STATE_PATH), 'w') as fcount:
fcount.write(str(len(os.listdir(nisysapi_conf_d_path))))
for fexpert in os.listdir(nisysapi_conf_d_path):
__salt__['cmd.shell']('stat -c %Y {0}/{1} >{2}/{1}.timestamp'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0}/{1} >{2}/{1}.md5sum'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
def _get_restartcheck_result(errors):
'''
Return restartcheck result and append errors (if any) to ``errors``
'''
rs_result = __salt__['restartcheck.restartcheck'](verbose=False)
if isinstance(rs_result, dict) and 'comment' in rs_result:
errors.append(rs_result['comment'])
return rs_result
def _process_restartcheck_result(rs_result, **kwargs):
'''
Check restartcheck output to see if system/service restarts were requested
and take appropriate action.
'''
if 'No packages seem to need to be restarted' in rs_result:
return
reboot_required = False
for rstr in rs_result:
if 'System restart required' in rstr:
_update_nilrt_restart_state()
__salt__['system.set_reboot_required_witnessed']()
reboot_required = True
if kwargs.get('always_restart_services', True) or not reboot_required:
for rstr in rs_result:
if 'System restart required' not in rstr:
service = os.path.join('/etc/init.d', rstr)
if os.path.exists(service):
__salt__['cmd.run']([service, 'restart'])
def __virtual__():
'''
Confirm this module is on a nilrt based system
'''
if __grains__.get('os_family') == 'NILinuxRT':
try:
os.makedirs(NILRT_RESTARTCHECK_STATE_PATH)
except OSError as exc:
if exc.errno != errno.EEXIST:
return False, 'Error creating {0} (-{1}): {2}'.format(
NILRT_RESTARTCHECK_STATE_PATH,
exc.errno,
exc.strerror)
# populate state dir if empty
if not os.listdir(NILRT_RESTARTCHECK_STATE_PATH):
_update_nilrt_restart_state()
return __virtualname__
if os.path.isdir(OPKG_CONFDIR):
return __virtualname__
return False, "Module opkg only works on OpenEmbedded based systems"
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
if not names:
return ''
ret = {}
for name in names:
ret[name] = ''
# Refresh before looking for the latest version available
if refresh:
refresh_db()
cmd = ['opkg', 'list-upgradable']
out = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
try:
name, _oldversion, newversion = line.split(' - ')
if name in names:
ret[name] = newversion
except ValueError:
pass
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = latest_version
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(failhard=False, **kwargs): # pylint: disable=unused-argument
'''
Updates the opkg database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
failhard
If False, return results of failed lines as ``False`` for the package
database that encountered the error.
If True, raise an error with a list of the package databases that
encountered errors.
.. versionadded:: 2018.3.0
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
error_repos = []
cmd = ['opkg', 'update']
# opkg returns a non-zero retcode when there is a failure to refresh
# from one or more repos. Due to this, ignore the retcode.
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True,
redirect_stderr=True)
out = call['stdout']
prev_line = ''
for line in salt.utils.itertools.split(out, '\n'):
if 'Inflating' in line:
key = line.strip().split()[1][:-1]
ret[key] = True
elif 'Updated source' in line:
# Use the previous line.
key = prev_line.strip().split()[1][:-1]
ret[key] = True
elif 'Failed to download' in line:
key = line.strip().split()[5].split(',')[0]
ret[key] = False
error_repos.append(key)
prev_line = line
if failhard and error_repos:
raise CommandExecutionError(
'Error getting repos: {0}'.format(', '.join(error_repos))
)
# On a non-zero exit code where no failed repos were found, raise an
# exception because this appears to be a different kind of error.
if call['retcode'] != 0 and not error_repos:
raise CommandExecutionError(out)
return ret
def _is_testmode(**kwargs):
'''
Returns whether a test mode (noaction) operation was requested.
'''
return bool(kwargs.get('test') or __opts__.get('test'))
def _append_noaction_if_testmode(cmd, **kwargs):
'''
Adds the --noaction flag to the command if it's running in the test mode.
'''
if _is_testmode(**kwargs):
cmd.append('--noaction')
def _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall):
'''
Builds a list of install commands to be executed in sequence in order to process
each of the to_install, to_downgrade, and to_reinstall lists.
'''
cmds = []
if to_install:
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(to_install)
cmds.append(cmd)
if to_downgrade:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-downgrade')
cmd.extend(to_downgrade)
cmds.append(cmd)
if to_reinstall:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-reinstall')
cmd.extend(to_reinstall)
cmds.append(cmd)
return cmds
def _parse_reported_packages_from_install_output(output):
'''
Parses the output of "opkg install" to determine what packages would have been
installed by an operation run with the --noaction flag.
We are looking for lines like:
Installing <package> (<version>) on <target>
or
Upgrading <package> from <oldVersion> to <version> on root
'''
reported_pkgs = {}
install_pattern = re.compile(r'Installing\s(?P<package>.*?)\s\((?P<version>.*?)\)\son\s(?P<target>.*?)')
upgrade_pattern = re.compile(r'Upgrading\s(?P<package>.*?)\sfrom\s(?P<oldVersion>.*?)\sto\s(?P<version>.*?)\son\s(?P<target>.*?)')
for line in salt.utils.itertools.split(output, '\n'):
match = install_pattern.match(line)
if match is None:
match = upgrade_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = match.group('version')
return reported_pkgs
def _execute_install_command(cmd, parse_output, errors, parsed_packages):
'''
Executes a command for the install operation.
If the command fails, its error output will be appended to the errors list.
If the command succeeds and parse_output is true, updated packages will be appended
to the parsed_packages dictionary.
'''
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors.append(out['stderr'])
else:
errors.append(out['stdout'])
elif parse_output:
parsed_packages.update(_parse_reported_packages_from_install_output(out['stdout']))
def install(name=None,
refresh=False,
pkgs=None,
sources=None,
reinstall=False,
**kwargs):
'''
Install the passed package, add refresh=True to update the opkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionadded:: 2017.7.0
reinstall : False
Specifying reinstall=True will use ``opkg install --force-reinstall``
rather than simply ``opkg install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``opkg
install --force-reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2017.7.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of IPK packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
install_recommends
Whether to install the packages marked as recommended. Default is True.
only_upgrade
Only upgrade the packages (disallow downgrades), if they are already
installed. Default is False.
.. versionadded:: 2017.7.0
always_restart_services
Whether to restart services even if a reboot is required. Default is True.
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
refreshdb = salt.utils.data.is_true(refresh)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
cmd_prefix = ['opkg', 'install']
to_install = []
to_reinstall = []
to_downgrade = []
_append_noaction_if_testmode(cmd_prefix, **kwargs)
if not pkg_params:
return {}
elif pkg_type == 'file':
if reinstall:
cmd_prefix.append('--force-reinstall')
if not kwargs.get('only_upgrade', False):
cmd_prefix.append('--force-downgrade')
to_install.extend(pkg_params)
elif pkg_type == 'repository':
if not kwargs.get('install_recommends', True):
cmd_prefix.append('--no-install-recommends')
for pkgname, pkgversion in six.iteritems(pkg_params):
if (name and pkgs is None and kwargs.get('version') and
len(pkg_params) == 1):
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
version_num = pkgversion
if version_num is None:
# Don't allow downgrades if the version
# number is not specified.
if reinstall and pkgname in old:
to_reinstall.append(pkgname)
else:
to_install.append(pkgname)
else:
pkgstr = '{0}={1}'.format(pkgname, version_num)
cver = old.get(pkgname, '')
if reinstall and cver and salt.utils.versions.compare(
ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall.append(pkgstr)
elif not cver or salt.utils.versions.compare(
ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
to_install.append(pkgstr)
else:
if not kwargs.get('only_upgrade', False):
to_downgrade.append(pkgstr)
else:
# This should cause the command to fail.
to_install.append(pkgstr)
cmds = _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall)
if not cmds:
return {}
if refreshdb:
refresh_db()
errors = []
is_testmode = _is_testmode(**kwargs)
test_packages = {}
for cmd in cmds:
_execute_install_command(cmd, is_testmode, errors, test_packages)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if is_testmode:
new = copy.deepcopy(new)
new.update(test_packages)
ret = salt.utils.data.compare_dicts(old, new)
if pkg_type == 'file' and reinstall:
# For file-based packages, prepare 'to_reinstall' to have a list
# of all the package names that may have been reinstalled.
# This way, we could include reinstalled packages in 'ret'.
for pkgfile in to_install:
# Convert from file name to package name.
cmd = ['opkg', 'info', pkgfile]
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] == 0:
# Just need the package name.
pkginfo_dict = _process_info_installed_output(
out['stdout'], []
)
if pkginfo_dict:
to_reinstall.append(list(pkginfo_dict.keys())[0])
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def _parse_reported_packages_from_remove_output(output):
'''
Parses the output of "opkg remove" to determine what packages would have been
removed by an operation run with the --noaction flag.
We are looking for lines like
Removing <package> (<version>) from <Target>...
'''
reported_pkgs = {}
remove_pattern = re.compile(r'Removing\s(?P<package>.*?)\s\((?P<version>.*?)\)\sfrom\s(?P<target>.*?)...')
for line in salt.utils.itertools.split(output, '\n'):
match = remove_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = ''
return reported_pkgs
def remove(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Remove packages using ``opkg remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
remove_dependencies
Remove package and all dependencies
.. versionadded:: 2019.2.0
auto_remove_deps
Remove packages that were installed automatically to satisfy dependencies
.. versionadded:: 2019.2.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
salt '*' pkg.remove pkgs='["foo", "bar"]' remove_dependencies=True auto_remove_deps=True
'''
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 {}
cmd = ['opkg', 'remove']
_append_noaction_if_testmode(cmd, **kwargs)
if kwargs.get('remove_dependencies', False):
cmd.append('--force-removal-of-dependent-packages')
if kwargs.get('auto_remove_deps', False):
cmd.append('--autoremove')
cmd.extend(targets)
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors = [out['stderr']]
else:
errors = [out['stdout']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if _is_testmode(**kwargs):
reportedPkgs = _parse_reported_packages_from_remove_output(out['stdout'])
new = {k: v for k, v in new.items() if k not in reportedPkgs}
ret = salt.utils.data.compare_dicts(old, new)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def purge(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Package purges are not supported by opkg, this function is identical to
:mod:`pkg.remove <salt.modules.opkg.remove>`.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name, pkgs=pkgs)
def upgrade(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
Upgrades all packages via ``opkg upgrade``
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
errors = []
if salt.utils.data.is_true(refresh):
refresh_db()
old = list_pkgs()
cmd = ['opkg', 'upgrade']
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
errors.append(result)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif state != 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = _set_state(target, 'hold')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif state == 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret['comment'] = ('Package {0} is set not to be held.'
.format(target))
else:
result = _set_state(target, 'ok')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def _get_state(pkg):
'''
View package state from the opkg database
Return the state of pkg
'''
cmd = ['opkg', 'status']
cmd.append(pkg)
out = __salt__['cmd.run'](cmd, python_shell=False)
state_flag = ''
for line in salt.utils.itertools.split(out, '\n'):
if line.startswith('Status'):
_status, _state_want, state_flag, _state_status = line.split()
return state_flag
def _set_state(pkg, state):
'''
Change package state on the opkg database
The state can be any of:
- hold
- noprune
- user
- ok
- installed
- unpacked
This command is commonly used to mark a specific package to be held from
being upgraded, that is, to be kept at a certain version.
Returns a dict containing the package name, and the new and old
versions.
'''
ret = {}
valid_states = ('hold', 'noprune', 'user', 'ok', 'installed', 'unpacked')
if state not in valid_states:
raise SaltInvocationError('Invalid state: {0}'.format(state))
oldstate = _get_state(pkg)
cmd = ['opkg', 'flag']
cmd.append(state)
cmd.append(pkg)
_out = __salt__['cmd.run'](cmd, python_shell=False)
# Missing return value check due to opkg issue 160
ret[pkg] = {'old': oldstate,
'new': state}
return ret
def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
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
cmd = ['opkg', 'list-installed']
ret = {}
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
# This is a continuation of package description
if not line or line[0] == ' ':
continue
# This contains package name, version, and description.
# Extract the first two.
pkg_name, pkg_version = line.split(' - ', 2)[:2]
__salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version)
__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 list_upgrades(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
List all available package upgrades.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
ret = {}
if salt.utils.data.is_true(refresh):
refresh_db()
cmd = ['opkg', 'list-upgradable']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
if 'stdout' in call:
comment += call['stdout']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
name, _oldversion, newversion = line.split(' - ')
ret[name] = newversion
return ret
def _convert_to_standard_attr(attr):
'''
Helper function for _process_info_installed_output()
Converts an opkg attribute name to a standard attribute
name which is used across 'pkg' modules.
'''
ret_attr = ATTR_MAP.get(attr, None)
if ret_attr is None:
# All others convert to lowercase
return attr.lower()
return ret_attr
def _process_info_installed_output(out, filter_attrs):
'''
Helper function for info_installed()
Processes stdout output from a single invocation of
'opkg status'.
'''
ret = {}
name = None
attrs = {}
attr = None
for line in salt.utils.itertools.split(out, '\n'):
if line and line[0] == ' ':
# This is a continuation of the last attr
if filter_attrs is None or attr in filter_attrs:
line = line.strip()
if attrs[attr]:
# If attr is empty, don't add leading newline
attrs[attr] += '\n'
attrs[attr] += line
continue
line = line.strip()
if not line:
# Separator between different packages
if name:
ret[name] = attrs
name = None
attrs = {}
attr = None
continue
key, value = line.split(':', 1)
value = value.lstrip()
attr = _convert_to_standard_attr(key)
if attr == 'name':
name = value
elif filter_attrs is None or attr in filter_attrs:
attrs[attr] = value
if name:
ret[name] = attrs
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
.. versionadded:: 2017.7.0
:param names:
Names of the packages to get information about. If none are specified,
will return information for all installed packages.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
arch, conffiles, conflicts, depends, description, filename, group,
install_date_time_t, md5sum, packager, provides, recommends,
replaces, size, source, suggests, url, version
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed
salt '*' pkg.info_installed attr=version,packager
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> attr=version,packager
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,packager
'''
attr = kwargs.pop('attr', None)
if attr is None:
filter_attrs = None
elif isinstance(attr, six.string_types):
filter_attrs = set(attr.split(','))
else:
filter_attrs = set(attr)
ret = {}
if names:
# Specific list of names of installed packages
for name in names:
cmd = ['opkg', 'status', name]
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
else:
# All installed packages
cmd = ['opkg', 'status']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
return ret
def upgrade_available(name, **kwargs): # pylint: disable=unused-argument
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs): # pylint: disable=unused-argument
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2016.3.4
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0' '0.2.4.1-0'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] if ignore_epoch else six.text_type(x)
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
output = __salt__['cmd.run_stdout'](['opkg', '--version'],
output_loglevel='trace',
python_shell=False)
opkg_version = output.split(' ')[2].strip()
if salt.utils.versions.LooseVersion(opkg_version) >= \
salt.utils.versions.LooseVersion('0.3.4'):
cmd_compare = ['opkg', 'compare-versions']
elif salt.utils.path.which('opkg-compare-versions'):
cmd_compare = ['opkg-compare-versions']
else:
log.warning('Unable to find a compare-versions utility installed. Either upgrade opkg to '
'version > 0.3.4 (preferred) or install the older opkg-compare-versions script.')
return None
for oper, ret in (("<<", -1), ("=", 0), (">>", 1)):
cmd = cmd_compare[:]
cmd.append(_cmd_quote(pkg1))
cmd.append(oper)
cmd.append(_cmd_quote(pkg2))
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
ignore_retcode=True,
python_shell=False)
if retcode == 0:
return ret
return None
def _set_repo_option(repo, option):
'''
Set the option to repo
'''
if not option:
return
opt = option.split('=')
if len(opt) != 2:
return
if opt[0] == 'trusted':
repo['trusted'] = opt[1] == 'yes'
else:
repo[opt[0]] = opt[1]
def _set_repo_options(repo, options):
'''
Set the options to the repo.
'''
delimiters = "[", "]"
pattern = '|'.join(map(re.escape, delimiters))
for option in options:
splitted = re.split(pattern, option)
for opt in splitted:
_set_repo_option(repo, opt)
def _create_repo(line, filename):
'''
Create repo
'''
repo = {}
if line.startswith('#'):
repo['enabled'] = False
line = line[1:]
else:
repo['enabled'] = True
cols = salt.utils.args.shlex_split(line.strip())
repo['compressed'] = not cols[0] in 'src'
repo['name'] = cols[1]
repo['uri'] = cols[2]
repo['file'] = os.path.join(OPKG_CONFDIR, filename)
if len(cols) > 3:
_set_repo_options(repo, cols[3:])
return repo
def _read_repos(conf_file, repos, filename, regex):
'''
Read repos from configuration file
'''
for line in conf_file:
line = salt.utils.stringutils.to_unicode(line)
if not regex.search(line):
continue
repo = _create_repo(line, filename)
# do not store duplicated uri's
if repo['uri'] not in repos:
repos[repo['uri']] = [repo]
def get_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Display a repo from the ``/etc/opkg/*.conf``
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo repo
'''
repos = list_repos()
if repos:
for source in six.itervalues(repos):
for sub in source:
if sub['name'] == repo:
return sub
return {}
def _del_repo_from_file(repo, filepath):
'''
Remove a repo from filepath
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
regex = re.compile(REPO_REGEXP)
for line in fhandle:
line = salt.utils.stringutils.to_unicode(line)
if regex.search(line):
if line.startswith('#'):
line = line[1:]
cols = salt.utils.args.shlex_split(line.strip())
if repo != cols[1]:
output.append(salt.utils.stringutils.to_str(line))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def _set_trusted_option_if_needed(repostr, trusted):
'''
Set trusted option to repo if needed
'''
if trusted is True:
repostr += ' [trusted=yes]'
elif trusted is False:
repostr += ' [trusted=no]'
return repostr
def _add_new_repo(repo, properties):
'''
Add a new repo entry
'''
repostr = '# ' if not properties.get('enabled') else ''
repostr += 'src/gz ' if properties.get('compressed') else 'src '
if ' ' in repo:
repostr += '"' + repo + '" '
else:
repostr += repo + ' '
repostr += properties.get('uri')
repostr = _set_trusted_option_if_needed(repostr, properties.get('trusted'))
repostr += '\n'
conffile = os.path.join(OPKG_CONFDIR, repo + '.conf')
with salt.utils.files.fopen(conffile, 'a') as fhandle:
fhandle.write(salt.utils.stringutils.to_str(repostr))
def _mod_repo_in_file(repo, repostr, filepath):
'''
Replace a repo entry in filepath with repostr
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
for line in fhandle:
cols = salt.utils.args.shlex_split(
salt.utils.stringutils.to_unicode(line).strip()
)
if repo not in cols:
output.append(line)
else:
output.append(salt.utils.stringutils.to_str(repostr + '\n'))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def del_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Delete a repo from ``/etc/opkg/*.conf``
If the file does not contain any other repo configuration, the file itself
will be deleted.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo repo
'''
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
repos = list_repos()
if repos:
deleted_from = dict()
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
deleted_from[source['file']] = 0
_del_repo_from_file(repo, source['file'])
if deleted_from:
ret = ''
for repository in repos:
source = repos[repository][0]
if source['file'] in deleted_from:
deleted_from[source['file']] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 1 and os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.\n')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
if refresh:
refresh_db()
return ret
return "Repo {0} doesn't exist in the opkg repo lists".format(repo)
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as uri is defined.
The following options are available to modify a repo definition:
repo
alias by which opkg refers to the repo.
uri
the URI to the repo.
compressed
defines (True or False) if the index file is compressed
enabled
enable or disable (True or False) repository
but do not remove if disabled.
refresh
enable or disable (True or False) auto-refresh of the repositories
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo repo uri=http://new/uri
salt '*' pkg.mod_repo repo enabled=False
'''
repos = list_repos()
found = False
uri = ''
if 'uri' in kwargs:
uri = kwargs['uri']
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
found = True
repostr = ''
if 'enabled' in kwargs and not kwargs['enabled']:
repostr += '# '
if 'compressed' in kwargs:
repostr += 'src/gz ' if kwargs['compressed'] else 'src'
else:
repostr += 'src/gz' if source['compressed'] else 'src'
repo_alias = kwargs['alias'] if 'alias' in kwargs else repo
if ' ' in repo_alias:
repostr += ' "{0}"'.format(repo_alias)
else:
repostr += ' {0}'.format(repo_alias)
repostr += ' {0}'.format(kwargs['uri'] if 'uri' in kwargs else source['uri'])
trusted = kwargs.get('trusted')
repostr = _set_trusted_option_if_needed(repostr, trusted) if trusted is not None else \
_set_trusted_option_if_needed(repostr, source.get('trusted'))
_mod_repo_in_file(repo, repostr, source['file'])
elif uri and source['uri'] == uri:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(uri, source['name']))
if not found:
# Need to add a new repo
if 'uri' not in kwargs:
raise CommandExecutionError(
'Repository \'{0}\' not found and no URI passed to create one.'.format(repo))
properties = {'uri': kwargs['uri']}
# If compressed is not defined, assume True
properties['compressed'] = kwargs['compressed'] if 'compressed' in kwargs else True
# If enabled is not defined, assume True
properties['enabled'] = kwargs['enabled'] if 'enabled' in kwargs else True
properties['trusted'] = kwargs.get('trusted')
_add_new_repo(repo, properties)
if 'refresh' in kwargs:
refresh_db()
def file_list(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
output = file_dict(*packages)
files = []
for package in list(output['packages'].values()):
files.extend(package)
return {'errors': output['errors'], 'files': files}
def file_dict(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
errors = []
ret = {}
cmd_files = ['opkg', 'files']
if not packages:
packages = list(list_pkgs().keys())
for package in packages:
files = []
cmd = cmd_files[:]
cmd.append(package)
out = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
for line in out['stdout'].splitlines():
if line.startswith('/'):
files.append(line)
elif line.startswith(' * '):
errors.append(line[3:])
break
else:
continue
if files:
ret[package] = files
return {'errors': errors, 'packages': ret}
def owner(*paths, **kwargs): # pylint: disable=unused-argument
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.opkg.version`, if a single
path is passed, a string will be returned, and if multiple paths are passed,
a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
cmd_search = ['opkg', 'search']
for path in paths:
cmd = cmd_search[:]
cmd.append(path)
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
if output:
ret[path] = output.split(' - ')[0].strip()
else:
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def version_clean(version):
'''
Clean the version string removing extra data.
There's nothing do to here for nipkg.py, therefore it will always
return the given version.
'''
return version
def check_extra_requirements(pkgname, pkgver):
'''
Check if the installed package already has the given requirements.
There's nothing do to here for nipkg.py, therefore it will always
return True.
'''
return True
|
saltstack/salt
|
salt/modules/opkg.py
|
get_repo
|
python
|
def get_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Display a repo from the ``/etc/opkg/*.conf``
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo repo
'''
repos = list_repos()
if repos:
for source in six.itervalues(repos):
for sub in source:
if sub['name'] == repo:
return sub
return {}
|
Display a repo from the ``/etc/opkg/*.conf``
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo repo
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/opkg.py#L1329-L1346
|
[
"def itervalues(d, **kw):\n return d.itervalues(**kw)\n",
"def list_repos(**kwargs): # pylint: disable=unused-argument\n '''\n Lists all repos on ``/etc/opkg/*.conf``\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.list_repos\n '''\n repos = {}\n regex = re.compile(REPO_REGEXP)\n for filename in os.listdir(OPKG_CONFDIR):\n if not filename.endswith(\".conf\"):\n continue\n with salt.utils.files.fopen(os.path.join(OPKG_CONFDIR, filename)) as conf_file:\n _read_repos(conf_file, repos, filename, regex)\n return repos\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Opkg
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
.. versionadded: 2016.3.0
.. note::
For version comparison support on opkg < 0.3.4, the ``opkg-utils`` package
must be installed.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import os
import re
import logging
import errno
# Import salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.itertools
import salt.utils.path
import salt.utils.pkg
import salt.utils.stringutils
import salt.utils.versions
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import shlex_quote as _cmd_quote # pylint: disable=import-error
from salt.ext.six.moves import map # pylint: disable=import-error,redefined-builtin
REPO_REGEXP = r'^#?\s*(src|src/gz)\s+([^\s<>]+|"[^<>]+")\s+[^\s<>]+'
OPKG_CONFDIR = '/etc/opkg'
ATTR_MAP = {
'Architecture': 'arch',
'Homepage': 'url',
'Installed-Time': 'install_date_time_t',
'Maintainer': 'packager',
'Package': 'name',
'Section': 'group'
}
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
NILRT_RESTARTCHECK_STATE_PATH = '/var/lib/salt/restartcheck_state'
def _update_nilrt_restart_state():
'''
NILRT systems determine whether to reboot after various package operations
including but not limited to kernel module installs/removals by checking
specific file md5sums & timestamps. These files are touched/modified by
the post-install/post-remove functions of their respective packages.
The opkg module uses this function to store/update those file timestamps
and checksums to be used later by the restartcheck module.
'''
__salt__['cmd.shell']('stat -c %Y /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.timestamp'
.format(NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.md5sum'
.format(NILRT_RESTARTCHECK_STATE_PATH))
# We can't assume nisysapi.ini always exists like modules.dep
nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'
if os.path.exists(nisysapi_path):
__salt__['cmd.shell']('stat -c %Y {0} >{1}/nisysapi.ini.timestamp'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0} >{1}/nisysapi.ini.md5sum'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
# Expert plugin files get added to a conf.d dir, so keep track of the total
# no. of files, their timestamps and content hashes
nisysapi_conf_d_path = "/usr/lib/{0}/nisysapi/conf.d/experts/".format(
'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'
)
if os.path.exists(nisysapi_conf_d_path):
with salt.utils.files.fopen('{0}/sysapi.conf.d.count'.format(
NILRT_RESTARTCHECK_STATE_PATH), 'w') as fcount:
fcount.write(str(len(os.listdir(nisysapi_conf_d_path))))
for fexpert in os.listdir(nisysapi_conf_d_path):
__salt__['cmd.shell']('stat -c %Y {0}/{1} >{2}/{1}.timestamp'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0}/{1} >{2}/{1}.md5sum'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
def _get_restartcheck_result(errors):
'''
Return restartcheck result and append errors (if any) to ``errors``
'''
rs_result = __salt__['restartcheck.restartcheck'](verbose=False)
if isinstance(rs_result, dict) and 'comment' in rs_result:
errors.append(rs_result['comment'])
return rs_result
def _process_restartcheck_result(rs_result, **kwargs):
'''
Check restartcheck output to see if system/service restarts were requested
and take appropriate action.
'''
if 'No packages seem to need to be restarted' in rs_result:
return
reboot_required = False
for rstr in rs_result:
if 'System restart required' in rstr:
_update_nilrt_restart_state()
__salt__['system.set_reboot_required_witnessed']()
reboot_required = True
if kwargs.get('always_restart_services', True) or not reboot_required:
for rstr in rs_result:
if 'System restart required' not in rstr:
service = os.path.join('/etc/init.d', rstr)
if os.path.exists(service):
__salt__['cmd.run']([service, 'restart'])
def __virtual__():
'''
Confirm this module is on a nilrt based system
'''
if __grains__.get('os_family') == 'NILinuxRT':
try:
os.makedirs(NILRT_RESTARTCHECK_STATE_PATH)
except OSError as exc:
if exc.errno != errno.EEXIST:
return False, 'Error creating {0} (-{1}): {2}'.format(
NILRT_RESTARTCHECK_STATE_PATH,
exc.errno,
exc.strerror)
# populate state dir if empty
if not os.listdir(NILRT_RESTARTCHECK_STATE_PATH):
_update_nilrt_restart_state()
return __virtualname__
if os.path.isdir(OPKG_CONFDIR):
return __virtualname__
return False, "Module opkg only works on OpenEmbedded based systems"
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
if not names:
return ''
ret = {}
for name in names:
ret[name] = ''
# Refresh before looking for the latest version available
if refresh:
refresh_db()
cmd = ['opkg', 'list-upgradable']
out = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
try:
name, _oldversion, newversion = line.split(' - ')
if name in names:
ret[name] = newversion
except ValueError:
pass
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = latest_version
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(failhard=False, **kwargs): # pylint: disable=unused-argument
'''
Updates the opkg database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
failhard
If False, return results of failed lines as ``False`` for the package
database that encountered the error.
If True, raise an error with a list of the package databases that
encountered errors.
.. versionadded:: 2018.3.0
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
error_repos = []
cmd = ['opkg', 'update']
# opkg returns a non-zero retcode when there is a failure to refresh
# from one or more repos. Due to this, ignore the retcode.
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True,
redirect_stderr=True)
out = call['stdout']
prev_line = ''
for line in salt.utils.itertools.split(out, '\n'):
if 'Inflating' in line:
key = line.strip().split()[1][:-1]
ret[key] = True
elif 'Updated source' in line:
# Use the previous line.
key = prev_line.strip().split()[1][:-1]
ret[key] = True
elif 'Failed to download' in line:
key = line.strip().split()[5].split(',')[0]
ret[key] = False
error_repos.append(key)
prev_line = line
if failhard and error_repos:
raise CommandExecutionError(
'Error getting repos: {0}'.format(', '.join(error_repos))
)
# On a non-zero exit code where no failed repos were found, raise an
# exception because this appears to be a different kind of error.
if call['retcode'] != 0 and not error_repos:
raise CommandExecutionError(out)
return ret
def _is_testmode(**kwargs):
'''
Returns whether a test mode (noaction) operation was requested.
'''
return bool(kwargs.get('test') or __opts__.get('test'))
def _append_noaction_if_testmode(cmd, **kwargs):
'''
Adds the --noaction flag to the command if it's running in the test mode.
'''
if _is_testmode(**kwargs):
cmd.append('--noaction')
def _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall):
'''
Builds a list of install commands to be executed in sequence in order to process
each of the to_install, to_downgrade, and to_reinstall lists.
'''
cmds = []
if to_install:
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(to_install)
cmds.append(cmd)
if to_downgrade:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-downgrade')
cmd.extend(to_downgrade)
cmds.append(cmd)
if to_reinstall:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-reinstall')
cmd.extend(to_reinstall)
cmds.append(cmd)
return cmds
def _parse_reported_packages_from_install_output(output):
'''
Parses the output of "opkg install" to determine what packages would have been
installed by an operation run with the --noaction flag.
We are looking for lines like:
Installing <package> (<version>) on <target>
or
Upgrading <package> from <oldVersion> to <version> on root
'''
reported_pkgs = {}
install_pattern = re.compile(r'Installing\s(?P<package>.*?)\s\((?P<version>.*?)\)\son\s(?P<target>.*?)')
upgrade_pattern = re.compile(r'Upgrading\s(?P<package>.*?)\sfrom\s(?P<oldVersion>.*?)\sto\s(?P<version>.*?)\son\s(?P<target>.*?)')
for line in salt.utils.itertools.split(output, '\n'):
match = install_pattern.match(line)
if match is None:
match = upgrade_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = match.group('version')
return reported_pkgs
def _execute_install_command(cmd, parse_output, errors, parsed_packages):
'''
Executes a command for the install operation.
If the command fails, its error output will be appended to the errors list.
If the command succeeds and parse_output is true, updated packages will be appended
to the parsed_packages dictionary.
'''
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors.append(out['stderr'])
else:
errors.append(out['stdout'])
elif parse_output:
parsed_packages.update(_parse_reported_packages_from_install_output(out['stdout']))
def install(name=None,
refresh=False,
pkgs=None,
sources=None,
reinstall=False,
**kwargs):
'''
Install the passed package, add refresh=True to update the opkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionadded:: 2017.7.0
reinstall : False
Specifying reinstall=True will use ``opkg install --force-reinstall``
rather than simply ``opkg install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``opkg
install --force-reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2017.7.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of IPK packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
install_recommends
Whether to install the packages marked as recommended. Default is True.
only_upgrade
Only upgrade the packages (disallow downgrades), if they are already
installed. Default is False.
.. versionadded:: 2017.7.0
always_restart_services
Whether to restart services even if a reboot is required. Default is True.
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
refreshdb = salt.utils.data.is_true(refresh)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
cmd_prefix = ['opkg', 'install']
to_install = []
to_reinstall = []
to_downgrade = []
_append_noaction_if_testmode(cmd_prefix, **kwargs)
if not pkg_params:
return {}
elif pkg_type == 'file':
if reinstall:
cmd_prefix.append('--force-reinstall')
if not kwargs.get('only_upgrade', False):
cmd_prefix.append('--force-downgrade')
to_install.extend(pkg_params)
elif pkg_type == 'repository':
if not kwargs.get('install_recommends', True):
cmd_prefix.append('--no-install-recommends')
for pkgname, pkgversion in six.iteritems(pkg_params):
if (name and pkgs is None and kwargs.get('version') and
len(pkg_params) == 1):
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
version_num = pkgversion
if version_num is None:
# Don't allow downgrades if the version
# number is not specified.
if reinstall and pkgname in old:
to_reinstall.append(pkgname)
else:
to_install.append(pkgname)
else:
pkgstr = '{0}={1}'.format(pkgname, version_num)
cver = old.get(pkgname, '')
if reinstall and cver and salt.utils.versions.compare(
ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall.append(pkgstr)
elif not cver or salt.utils.versions.compare(
ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
to_install.append(pkgstr)
else:
if not kwargs.get('only_upgrade', False):
to_downgrade.append(pkgstr)
else:
# This should cause the command to fail.
to_install.append(pkgstr)
cmds = _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall)
if not cmds:
return {}
if refreshdb:
refresh_db()
errors = []
is_testmode = _is_testmode(**kwargs)
test_packages = {}
for cmd in cmds:
_execute_install_command(cmd, is_testmode, errors, test_packages)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if is_testmode:
new = copy.deepcopy(new)
new.update(test_packages)
ret = salt.utils.data.compare_dicts(old, new)
if pkg_type == 'file' and reinstall:
# For file-based packages, prepare 'to_reinstall' to have a list
# of all the package names that may have been reinstalled.
# This way, we could include reinstalled packages in 'ret'.
for pkgfile in to_install:
# Convert from file name to package name.
cmd = ['opkg', 'info', pkgfile]
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] == 0:
# Just need the package name.
pkginfo_dict = _process_info_installed_output(
out['stdout'], []
)
if pkginfo_dict:
to_reinstall.append(list(pkginfo_dict.keys())[0])
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def _parse_reported_packages_from_remove_output(output):
'''
Parses the output of "opkg remove" to determine what packages would have been
removed by an operation run with the --noaction flag.
We are looking for lines like
Removing <package> (<version>) from <Target>...
'''
reported_pkgs = {}
remove_pattern = re.compile(r'Removing\s(?P<package>.*?)\s\((?P<version>.*?)\)\sfrom\s(?P<target>.*?)...')
for line in salt.utils.itertools.split(output, '\n'):
match = remove_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = ''
return reported_pkgs
def remove(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Remove packages using ``opkg remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
remove_dependencies
Remove package and all dependencies
.. versionadded:: 2019.2.0
auto_remove_deps
Remove packages that were installed automatically to satisfy dependencies
.. versionadded:: 2019.2.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
salt '*' pkg.remove pkgs='["foo", "bar"]' remove_dependencies=True auto_remove_deps=True
'''
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 {}
cmd = ['opkg', 'remove']
_append_noaction_if_testmode(cmd, **kwargs)
if kwargs.get('remove_dependencies', False):
cmd.append('--force-removal-of-dependent-packages')
if kwargs.get('auto_remove_deps', False):
cmd.append('--autoremove')
cmd.extend(targets)
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors = [out['stderr']]
else:
errors = [out['stdout']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if _is_testmode(**kwargs):
reportedPkgs = _parse_reported_packages_from_remove_output(out['stdout'])
new = {k: v for k, v in new.items() if k not in reportedPkgs}
ret = salt.utils.data.compare_dicts(old, new)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def purge(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Package purges are not supported by opkg, this function is identical to
:mod:`pkg.remove <salt.modules.opkg.remove>`.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name, pkgs=pkgs)
def upgrade(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
Upgrades all packages via ``opkg upgrade``
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
errors = []
if salt.utils.data.is_true(refresh):
refresh_db()
old = list_pkgs()
cmd = ['opkg', 'upgrade']
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
errors.append(result)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif state != 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = _set_state(target, 'hold')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif state == 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret['comment'] = ('Package {0} is set not to be held.'
.format(target))
else:
result = _set_state(target, 'ok')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def _get_state(pkg):
'''
View package state from the opkg database
Return the state of pkg
'''
cmd = ['opkg', 'status']
cmd.append(pkg)
out = __salt__['cmd.run'](cmd, python_shell=False)
state_flag = ''
for line in salt.utils.itertools.split(out, '\n'):
if line.startswith('Status'):
_status, _state_want, state_flag, _state_status = line.split()
return state_flag
def _set_state(pkg, state):
'''
Change package state on the opkg database
The state can be any of:
- hold
- noprune
- user
- ok
- installed
- unpacked
This command is commonly used to mark a specific package to be held from
being upgraded, that is, to be kept at a certain version.
Returns a dict containing the package name, and the new and old
versions.
'''
ret = {}
valid_states = ('hold', 'noprune', 'user', 'ok', 'installed', 'unpacked')
if state not in valid_states:
raise SaltInvocationError('Invalid state: {0}'.format(state))
oldstate = _get_state(pkg)
cmd = ['opkg', 'flag']
cmd.append(state)
cmd.append(pkg)
_out = __salt__['cmd.run'](cmd, python_shell=False)
# Missing return value check due to opkg issue 160
ret[pkg] = {'old': oldstate,
'new': state}
return ret
def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
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
cmd = ['opkg', 'list-installed']
ret = {}
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
# This is a continuation of package description
if not line or line[0] == ' ':
continue
# This contains package name, version, and description.
# Extract the first two.
pkg_name, pkg_version = line.split(' - ', 2)[:2]
__salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version)
__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 list_upgrades(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
List all available package upgrades.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
ret = {}
if salt.utils.data.is_true(refresh):
refresh_db()
cmd = ['opkg', 'list-upgradable']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
if 'stdout' in call:
comment += call['stdout']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
name, _oldversion, newversion = line.split(' - ')
ret[name] = newversion
return ret
def _convert_to_standard_attr(attr):
'''
Helper function for _process_info_installed_output()
Converts an opkg attribute name to a standard attribute
name which is used across 'pkg' modules.
'''
ret_attr = ATTR_MAP.get(attr, None)
if ret_attr is None:
# All others convert to lowercase
return attr.lower()
return ret_attr
def _process_info_installed_output(out, filter_attrs):
'''
Helper function for info_installed()
Processes stdout output from a single invocation of
'opkg status'.
'''
ret = {}
name = None
attrs = {}
attr = None
for line in salt.utils.itertools.split(out, '\n'):
if line and line[0] == ' ':
# This is a continuation of the last attr
if filter_attrs is None or attr in filter_attrs:
line = line.strip()
if attrs[attr]:
# If attr is empty, don't add leading newline
attrs[attr] += '\n'
attrs[attr] += line
continue
line = line.strip()
if not line:
# Separator between different packages
if name:
ret[name] = attrs
name = None
attrs = {}
attr = None
continue
key, value = line.split(':', 1)
value = value.lstrip()
attr = _convert_to_standard_attr(key)
if attr == 'name':
name = value
elif filter_attrs is None or attr in filter_attrs:
attrs[attr] = value
if name:
ret[name] = attrs
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
.. versionadded:: 2017.7.0
:param names:
Names of the packages to get information about. If none are specified,
will return information for all installed packages.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
arch, conffiles, conflicts, depends, description, filename, group,
install_date_time_t, md5sum, packager, provides, recommends,
replaces, size, source, suggests, url, version
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed
salt '*' pkg.info_installed attr=version,packager
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> attr=version,packager
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,packager
'''
attr = kwargs.pop('attr', None)
if attr is None:
filter_attrs = None
elif isinstance(attr, six.string_types):
filter_attrs = set(attr.split(','))
else:
filter_attrs = set(attr)
ret = {}
if names:
# Specific list of names of installed packages
for name in names:
cmd = ['opkg', 'status', name]
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
else:
# All installed packages
cmd = ['opkg', 'status']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
return ret
def upgrade_available(name, **kwargs): # pylint: disable=unused-argument
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs): # pylint: disable=unused-argument
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2016.3.4
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0' '0.2.4.1-0'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] if ignore_epoch else six.text_type(x)
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
output = __salt__['cmd.run_stdout'](['opkg', '--version'],
output_loglevel='trace',
python_shell=False)
opkg_version = output.split(' ')[2].strip()
if salt.utils.versions.LooseVersion(opkg_version) >= \
salt.utils.versions.LooseVersion('0.3.4'):
cmd_compare = ['opkg', 'compare-versions']
elif salt.utils.path.which('opkg-compare-versions'):
cmd_compare = ['opkg-compare-versions']
else:
log.warning('Unable to find a compare-versions utility installed. Either upgrade opkg to '
'version > 0.3.4 (preferred) or install the older opkg-compare-versions script.')
return None
for oper, ret in (("<<", -1), ("=", 0), (">>", 1)):
cmd = cmd_compare[:]
cmd.append(_cmd_quote(pkg1))
cmd.append(oper)
cmd.append(_cmd_quote(pkg2))
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
ignore_retcode=True,
python_shell=False)
if retcode == 0:
return ret
return None
def _set_repo_option(repo, option):
'''
Set the option to repo
'''
if not option:
return
opt = option.split('=')
if len(opt) != 2:
return
if opt[0] == 'trusted':
repo['trusted'] = opt[1] == 'yes'
else:
repo[opt[0]] = opt[1]
def _set_repo_options(repo, options):
'''
Set the options to the repo.
'''
delimiters = "[", "]"
pattern = '|'.join(map(re.escape, delimiters))
for option in options:
splitted = re.split(pattern, option)
for opt in splitted:
_set_repo_option(repo, opt)
def _create_repo(line, filename):
'''
Create repo
'''
repo = {}
if line.startswith('#'):
repo['enabled'] = False
line = line[1:]
else:
repo['enabled'] = True
cols = salt.utils.args.shlex_split(line.strip())
repo['compressed'] = not cols[0] in 'src'
repo['name'] = cols[1]
repo['uri'] = cols[2]
repo['file'] = os.path.join(OPKG_CONFDIR, filename)
if len(cols) > 3:
_set_repo_options(repo, cols[3:])
return repo
def _read_repos(conf_file, repos, filename, regex):
'''
Read repos from configuration file
'''
for line in conf_file:
line = salt.utils.stringutils.to_unicode(line)
if not regex.search(line):
continue
repo = _create_repo(line, filename)
# do not store duplicated uri's
if repo['uri'] not in repos:
repos[repo['uri']] = [repo]
def list_repos(**kwargs): # pylint: disable=unused-argument
'''
Lists all repos on ``/etc/opkg/*.conf``
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos = {}
regex = re.compile(REPO_REGEXP)
for filename in os.listdir(OPKG_CONFDIR):
if not filename.endswith(".conf"):
continue
with salt.utils.files.fopen(os.path.join(OPKG_CONFDIR, filename)) as conf_file:
_read_repos(conf_file, repos, filename, regex)
return repos
def _del_repo_from_file(repo, filepath):
'''
Remove a repo from filepath
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
regex = re.compile(REPO_REGEXP)
for line in fhandle:
line = salt.utils.stringutils.to_unicode(line)
if regex.search(line):
if line.startswith('#'):
line = line[1:]
cols = salt.utils.args.shlex_split(line.strip())
if repo != cols[1]:
output.append(salt.utils.stringutils.to_str(line))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def _set_trusted_option_if_needed(repostr, trusted):
'''
Set trusted option to repo if needed
'''
if trusted is True:
repostr += ' [trusted=yes]'
elif trusted is False:
repostr += ' [trusted=no]'
return repostr
def _add_new_repo(repo, properties):
'''
Add a new repo entry
'''
repostr = '# ' if not properties.get('enabled') else ''
repostr += 'src/gz ' if properties.get('compressed') else 'src '
if ' ' in repo:
repostr += '"' + repo + '" '
else:
repostr += repo + ' '
repostr += properties.get('uri')
repostr = _set_trusted_option_if_needed(repostr, properties.get('trusted'))
repostr += '\n'
conffile = os.path.join(OPKG_CONFDIR, repo + '.conf')
with salt.utils.files.fopen(conffile, 'a') as fhandle:
fhandle.write(salt.utils.stringutils.to_str(repostr))
def _mod_repo_in_file(repo, repostr, filepath):
'''
Replace a repo entry in filepath with repostr
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
for line in fhandle:
cols = salt.utils.args.shlex_split(
salt.utils.stringutils.to_unicode(line).strip()
)
if repo not in cols:
output.append(line)
else:
output.append(salt.utils.stringutils.to_str(repostr + '\n'))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def del_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Delete a repo from ``/etc/opkg/*.conf``
If the file does not contain any other repo configuration, the file itself
will be deleted.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo repo
'''
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
repos = list_repos()
if repos:
deleted_from = dict()
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
deleted_from[source['file']] = 0
_del_repo_from_file(repo, source['file'])
if deleted_from:
ret = ''
for repository in repos:
source = repos[repository][0]
if source['file'] in deleted_from:
deleted_from[source['file']] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 1 and os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.\n')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
if refresh:
refresh_db()
return ret
return "Repo {0} doesn't exist in the opkg repo lists".format(repo)
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as uri is defined.
The following options are available to modify a repo definition:
repo
alias by which opkg refers to the repo.
uri
the URI to the repo.
compressed
defines (True or False) if the index file is compressed
enabled
enable or disable (True or False) repository
but do not remove if disabled.
refresh
enable or disable (True or False) auto-refresh of the repositories
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo repo uri=http://new/uri
salt '*' pkg.mod_repo repo enabled=False
'''
repos = list_repos()
found = False
uri = ''
if 'uri' in kwargs:
uri = kwargs['uri']
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
found = True
repostr = ''
if 'enabled' in kwargs and not kwargs['enabled']:
repostr += '# '
if 'compressed' in kwargs:
repostr += 'src/gz ' if kwargs['compressed'] else 'src'
else:
repostr += 'src/gz' if source['compressed'] else 'src'
repo_alias = kwargs['alias'] if 'alias' in kwargs else repo
if ' ' in repo_alias:
repostr += ' "{0}"'.format(repo_alias)
else:
repostr += ' {0}'.format(repo_alias)
repostr += ' {0}'.format(kwargs['uri'] if 'uri' in kwargs else source['uri'])
trusted = kwargs.get('trusted')
repostr = _set_trusted_option_if_needed(repostr, trusted) if trusted is not None else \
_set_trusted_option_if_needed(repostr, source.get('trusted'))
_mod_repo_in_file(repo, repostr, source['file'])
elif uri and source['uri'] == uri:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(uri, source['name']))
if not found:
# Need to add a new repo
if 'uri' not in kwargs:
raise CommandExecutionError(
'Repository \'{0}\' not found and no URI passed to create one.'.format(repo))
properties = {'uri': kwargs['uri']}
# If compressed is not defined, assume True
properties['compressed'] = kwargs['compressed'] if 'compressed' in kwargs else True
# If enabled is not defined, assume True
properties['enabled'] = kwargs['enabled'] if 'enabled' in kwargs else True
properties['trusted'] = kwargs.get('trusted')
_add_new_repo(repo, properties)
if 'refresh' in kwargs:
refresh_db()
def file_list(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
output = file_dict(*packages)
files = []
for package in list(output['packages'].values()):
files.extend(package)
return {'errors': output['errors'], 'files': files}
def file_dict(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
errors = []
ret = {}
cmd_files = ['opkg', 'files']
if not packages:
packages = list(list_pkgs().keys())
for package in packages:
files = []
cmd = cmd_files[:]
cmd.append(package)
out = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
for line in out['stdout'].splitlines():
if line.startswith('/'):
files.append(line)
elif line.startswith(' * '):
errors.append(line[3:])
break
else:
continue
if files:
ret[package] = files
return {'errors': errors, 'packages': ret}
def owner(*paths, **kwargs): # pylint: disable=unused-argument
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.opkg.version`, if a single
path is passed, a string will be returned, and if multiple paths are passed,
a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
cmd_search = ['opkg', 'search']
for path in paths:
cmd = cmd_search[:]
cmd.append(path)
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
if output:
ret[path] = output.split(' - ')[0].strip()
else:
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def version_clean(version):
'''
Clean the version string removing extra data.
There's nothing do to here for nipkg.py, therefore it will always
return the given version.
'''
return version
def check_extra_requirements(pkgname, pkgver):
'''
Check if the installed package already has the given requirements.
There's nothing do to here for nipkg.py, therefore it will always
return True.
'''
return True
|
saltstack/salt
|
salt/modules/opkg.py
|
_del_repo_from_file
|
python
|
def _del_repo_from_file(repo, filepath):
'''
Remove a repo from filepath
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
regex = re.compile(REPO_REGEXP)
for line in fhandle:
line = salt.utils.stringutils.to_unicode(line)
if regex.search(line):
if line.startswith('#'):
line = line[1:]
cols = salt.utils.args.shlex_split(line.strip())
if repo != cols[1]:
output.append(salt.utils.stringutils.to_str(line))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
|
Remove a repo from filepath
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/opkg.py#L1349-L1365
|
[
"def fopen(*args, **kwargs):\n '''\n Wrapper around open() built-in to set CLOEXEC on the fd.\n\n This flag specifies that the file descriptor should be closed when an exec\n function is invoked;\n\n When a file descriptor is allocated (as with open or dup), this bit is\n initially cleared on the new file descriptor, meaning that descriptor will\n survive into the new program after exec.\n\n NB! We still have small race condition between open and fcntl.\n '''\n if six.PY3:\n try:\n # Don't permit stdin/stdout/stderr to be opened. The boolean False\n # and True are treated by Python 3's open() as file descriptors 0\n # and 1, respectively.\n if args[0] in (0, 1, 2):\n raise TypeError(\n '{0} is not a permitted file descriptor'.format(args[0])\n )\n except IndexError:\n pass\n binary = None\n # ensure 'binary' mode is always used on Windows in Python 2\n if ((six.PY2 and salt.utils.platform.is_windows() and 'binary' not in kwargs) or\n kwargs.pop('binary', False)):\n if len(args) > 1:\n args = list(args)\n if 'b' not in args[1]:\n args[1] = args[1].replace('t', 'b')\n if 'b' not in args[1]:\n args[1] += 'b'\n elif kwargs.get('mode'):\n if 'b' not in kwargs['mode']:\n kwargs['mode'] = kwargs['mode'].replace('t', 'b')\n if 'b' not in kwargs['mode']:\n kwargs['mode'] += 'b'\n else:\n # the default is to read\n kwargs['mode'] = 'rb'\n elif six.PY3 and 'encoding' not in kwargs:\n # In Python 3, if text mode is used and the encoding\n # is not specified, set the encoding to 'utf-8'.\n binary = False\n if len(args) > 1:\n args = list(args)\n if 'b' in args[1]:\n binary = True\n if kwargs.get('mode', None):\n if 'b' in kwargs['mode']:\n binary = True\n if not binary:\n kwargs['encoding'] = __salt_system_encoding__\n\n if six.PY3 and not binary and not kwargs.get('newline', None):\n kwargs['newline'] = ''\n\n f_handle = open(*args, **kwargs) # pylint: disable=resource-leakage\n\n if is_fcntl_available():\n # modify the file descriptor on systems with fcntl\n # unix and unix-like systems only\n try:\n FD_CLOEXEC = fcntl.FD_CLOEXEC # pylint: disable=C0103\n except AttributeError:\n FD_CLOEXEC = 1 # pylint: disable=C0103\n old_flags = fcntl.fcntl(f_handle.fileno(), fcntl.F_GETFD)\n fcntl.fcntl(f_handle.fileno(), fcntl.F_SETFD, old_flags | FD_CLOEXEC)\n\n return f_handle\n",
"def to_unicode(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str or unicode, return unicode (str for python 3)\n '''\n def _normalize(s):\n return unicodedata.normalize('NFC', s) if normalize else s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n exc = None\n if six.PY3:\n if isinstance(s, str):\n return _normalize(s)\n elif isinstance(s, (bytes, bytearray)):\n return _normalize(to_str(s, encoding, errors))\n raise TypeError('expected str, bytes, or bytearray')\n else:\n # This needs to be str and not six.string_types, since if the string is\n # already a unicode type, it does not need to be decoded (and doing so\n # will raise an exception).\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n return _normalize(s)\n elif isinstance(s, (str, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str or bytearray')\n",
"def to_str(s, encoding=None, errors='strict', normalize=False):\n '''\n Given str, bytes, bytearray, or unicode (py2), return str\n '''\n def _normalize(s):\n try:\n return unicodedata.normalize('NFC', s) if normalize else s\n except TypeError:\n return s\n\n if encoding is None:\n # Try utf-8 first, and fall back to detected encoding\n encoding = ('utf-8', __salt_system_encoding__)\n if not isinstance(encoding, (tuple, list)):\n encoding = (encoding,)\n\n if not encoding:\n raise ValueError('encoding cannot be empty')\n\n # This shouldn't be six.string_types because if we're on PY2 and we already\n # have a string, we should just return it.\n if isinstance(s, str):\n return _normalize(s)\n\n exc = None\n if six.PY3:\n if isinstance(s, (bytes, bytearray)):\n for enc in encoding:\n try:\n return _normalize(s.decode(enc, errors))\n except UnicodeDecodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytes, or bytearray not {}'.format(type(s)))\n else:\n if isinstance(s, bytearray):\n return str(s) # future lint: disable=blacklisted-function\n if isinstance(s, unicode): # pylint: disable=incompatible-py3-code,undefined-variable\n for enc in encoding:\n try:\n return _normalize(s).encode(enc, errors)\n except UnicodeEncodeError as err:\n exc = err\n continue\n # The only way we get this far is if a UnicodeDecodeError was\n # raised, otherwise we would have already returned (or raised some\n # other exception).\n raise exc # pylint: disable=raising-bad-type\n raise TypeError('expected str, bytearray, or unicode')\n",
"def shlex_split(s, **kwargs):\n '''\n Only split if variable is a string\n '''\n if isinstance(s, six.string_types):\n # On PY2, shlex.split will fail with unicode types if there are\n # non-ascii characters in the string. So, we need to make sure we\n # invoke it with a str type, and then decode the resulting string back\n # to unicode to return it.\n return salt.utils.data.decode(\n shlex.split(salt.utils.stringutils.to_str(s), **kwargs)\n )\n else:\n return s\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Opkg
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
.. versionadded: 2016.3.0
.. note::
For version comparison support on opkg < 0.3.4, the ``opkg-utils`` package
must be installed.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import os
import re
import logging
import errno
# Import salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.itertools
import salt.utils.path
import salt.utils.pkg
import salt.utils.stringutils
import salt.utils.versions
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import shlex_quote as _cmd_quote # pylint: disable=import-error
from salt.ext.six.moves import map # pylint: disable=import-error,redefined-builtin
REPO_REGEXP = r'^#?\s*(src|src/gz)\s+([^\s<>]+|"[^<>]+")\s+[^\s<>]+'
OPKG_CONFDIR = '/etc/opkg'
ATTR_MAP = {
'Architecture': 'arch',
'Homepage': 'url',
'Installed-Time': 'install_date_time_t',
'Maintainer': 'packager',
'Package': 'name',
'Section': 'group'
}
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
NILRT_RESTARTCHECK_STATE_PATH = '/var/lib/salt/restartcheck_state'
def _update_nilrt_restart_state():
'''
NILRT systems determine whether to reboot after various package operations
including but not limited to kernel module installs/removals by checking
specific file md5sums & timestamps. These files are touched/modified by
the post-install/post-remove functions of their respective packages.
The opkg module uses this function to store/update those file timestamps
and checksums to be used later by the restartcheck module.
'''
__salt__['cmd.shell']('stat -c %Y /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.timestamp'
.format(NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.md5sum'
.format(NILRT_RESTARTCHECK_STATE_PATH))
# We can't assume nisysapi.ini always exists like modules.dep
nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'
if os.path.exists(nisysapi_path):
__salt__['cmd.shell']('stat -c %Y {0} >{1}/nisysapi.ini.timestamp'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0} >{1}/nisysapi.ini.md5sum'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
# Expert plugin files get added to a conf.d dir, so keep track of the total
# no. of files, their timestamps and content hashes
nisysapi_conf_d_path = "/usr/lib/{0}/nisysapi/conf.d/experts/".format(
'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'
)
if os.path.exists(nisysapi_conf_d_path):
with salt.utils.files.fopen('{0}/sysapi.conf.d.count'.format(
NILRT_RESTARTCHECK_STATE_PATH), 'w') as fcount:
fcount.write(str(len(os.listdir(nisysapi_conf_d_path))))
for fexpert in os.listdir(nisysapi_conf_d_path):
__salt__['cmd.shell']('stat -c %Y {0}/{1} >{2}/{1}.timestamp'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0}/{1} >{2}/{1}.md5sum'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
def _get_restartcheck_result(errors):
'''
Return restartcheck result and append errors (if any) to ``errors``
'''
rs_result = __salt__['restartcheck.restartcheck'](verbose=False)
if isinstance(rs_result, dict) and 'comment' in rs_result:
errors.append(rs_result['comment'])
return rs_result
def _process_restartcheck_result(rs_result, **kwargs):
'''
Check restartcheck output to see if system/service restarts were requested
and take appropriate action.
'''
if 'No packages seem to need to be restarted' in rs_result:
return
reboot_required = False
for rstr in rs_result:
if 'System restart required' in rstr:
_update_nilrt_restart_state()
__salt__['system.set_reboot_required_witnessed']()
reboot_required = True
if kwargs.get('always_restart_services', True) or not reboot_required:
for rstr in rs_result:
if 'System restart required' not in rstr:
service = os.path.join('/etc/init.d', rstr)
if os.path.exists(service):
__salt__['cmd.run']([service, 'restart'])
def __virtual__():
'''
Confirm this module is on a nilrt based system
'''
if __grains__.get('os_family') == 'NILinuxRT':
try:
os.makedirs(NILRT_RESTARTCHECK_STATE_PATH)
except OSError as exc:
if exc.errno != errno.EEXIST:
return False, 'Error creating {0} (-{1}): {2}'.format(
NILRT_RESTARTCHECK_STATE_PATH,
exc.errno,
exc.strerror)
# populate state dir if empty
if not os.listdir(NILRT_RESTARTCHECK_STATE_PATH):
_update_nilrt_restart_state()
return __virtualname__
if os.path.isdir(OPKG_CONFDIR):
return __virtualname__
return False, "Module opkg only works on OpenEmbedded based systems"
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
if not names:
return ''
ret = {}
for name in names:
ret[name] = ''
# Refresh before looking for the latest version available
if refresh:
refresh_db()
cmd = ['opkg', 'list-upgradable']
out = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
try:
name, _oldversion, newversion = line.split(' - ')
if name in names:
ret[name] = newversion
except ValueError:
pass
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = latest_version
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(failhard=False, **kwargs): # pylint: disable=unused-argument
'''
Updates the opkg database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
failhard
If False, return results of failed lines as ``False`` for the package
database that encountered the error.
If True, raise an error with a list of the package databases that
encountered errors.
.. versionadded:: 2018.3.0
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
error_repos = []
cmd = ['opkg', 'update']
# opkg returns a non-zero retcode when there is a failure to refresh
# from one or more repos. Due to this, ignore the retcode.
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True,
redirect_stderr=True)
out = call['stdout']
prev_line = ''
for line in salt.utils.itertools.split(out, '\n'):
if 'Inflating' in line:
key = line.strip().split()[1][:-1]
ret[key] = True
elif 'Updated source' in line:
# Use the previous line.
key = prev_line.strip().split()[1][:-1]
ret[key] = True
elif 'Failed to download' in line:
key = line.strip().split()[5].split(',')[0]
ret[key] = False
error_repos.append(key)
prev_line = line
if failhard and error_repos:
raise CommandExecutionError(
'Error getting repos: {0}'.format(', '.join(error_repos))
)
# On a non-zero exit code where no failed repos were found, raise an
# exception because this appears to be a different kind of error.
if call['retcode'] != 0 and not error_repos:
raise CommandExecutionError(out)
return ret
def _is_testmode(**kwargs):
'''
Returns whether a test mode (noaction) operation was requested.
'''
return bool(kwargs.get('test') or __opts__.get('test'))
def _append_noaction_if_testmode(cmd, **kwargs):
'''
Adds the --noaction flag to the command if it's running in the test mode.
'''
if _is_testmode(**kwargs):
cmd.append('--noaction')
def _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall):
'''
Builds a list of install commands to be executed in sequence in order to process
each of the to_install, to_downgrade, and to_reinstall lists.
'''
cmds = []
if to_install:
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(to_install)
cmds.append(cmd)
if to_downgrade:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-downgrade')
cmd.extend(to_downgrade)
cmds.append(cmd)
if to_reinstall:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-reinstall')
cmd.extend(to_reinstall)
cmds.append(cmd)
return cmds
def _parse_reported_packages_from_install_output(output):
'''
Parses the output of "opkg install" to determine what packages would have been
installed by an operation run with the --noaction flag.
We are looking for lines like:
Installing <package> (<version>) on <target>
or
Upgrading <package> from <oldVersion> to <version> on root
'''
reported_pkgs = {}
install_pattern = re.compile(r'Installing\s(?P<package>.*?)\s\((?P<version>.*?)\)\son\s(?P<target>.*?)')
upgrade_pattern = re.compile(r'Upgrading\s(?P<package>.*?)\sfrom\s(?P<oldVersion>.*?)\sto\s(?P<version>.*?)\son\s(?P<target>.*?)')
for line in salt.utils.itertools.split(output, '\n'):
match = install_pattern.match(line)
if match is None:
match = upgrade_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = match.group('version')
return reported_pkgs
def _execute_install_command(cmd, parse_output, errors, parsed_packages):
'''
Executes a command for the install operation.
If the command fails, its error output will be appended to the errors list.
If the command succeeds and parse_output is true, updated packages will be appended
to the parsed_packages dictionary.
'''
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors.append(out['stderr'])
else:
errors.append(out['stdout'])
elif parse_output:
parsed_packages.update(_parse_reported_packages_from_install_output(out['stdout']))
def install(name=None,
refresh=False,
pkgs=None,
sources=None,
reinstall=False,
**kwargs):
'''
Install the passed package, add refresh=True to update the opkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionadded:: 2017.7.0
reinstall : False
Specifying reinstall=True will use ``opkg install --force-reinstall``
rather than simply ``opkg install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``opkg
install --force-reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2017.7.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of IPK packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
install_recommends
Whether to install the packages marked as recommended. Default is True.
only_upgrade
Only upgrade the packages (disallow downgrades), if they are already
installed. Default is False.
.. versionadded:: 2017.7.0
always_restart_services
Whether to restart services even if a reboot is required. Default is True.
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
refreshdb = salt.utils.data.is_true(refresh)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
cmd_prefix = ['opkg', 'install']
to_install = []
to_reinstall = []
to_downgrade = []
_append_noaction_if_testmode(cmd_prefix, **kwargs)
if not pkg_params:
return {}
elif pkg_type == 'file':
if reinstall:
cmd_prefix.append('--force-reinstall')
if not kwargs.get('only_upgrade', False):
cmd_prefix.append('--force-downgrade')
to_install.extend(pkg_params)
elif pkg_type == 'repository':
if not kwargs.get('install_recommends', True):
cmd_prefix.append('--no-install-recommends')
for pkgname, pkgversion in six.iteritems(pkg_params):
if (name and pkgs is None and kwargs.get('version') and
len(pkg_params) == 1):
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
version_num = pkgversion
if version_num is None:
# Don't allow downgrades if the version
# number is not specified.
if reinstall and pkgname in old:
to_reinstall.append(pkgname)
else:
to_install.append(pkgname)
else:
pkgstr = '{0}={1}'.format(pkgname, version_num)
cver = old.get(pkgname, '')
if reinstall and cver and salt.utils.versions.compare(
ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall.append(pkgstr)
elif not cver or salt.utils.versions.compare(
ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
to_install.append(pkgstr)
else:
if not kwargs.get('only_upgrade', False):
to_downgrade.append(pkgstr)
else:
# This should cause the command to fail.
to_install.append(pkgstr)
cmds = _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall)
if not cmds:
return {}
if refreshdb:
refresh_db()
errors = []
is_testmode = _is_testmode(**kwargs)
test_packages = {}
for cmd in cmds:
_execute_install_command(cmd, is_testmode, errors, test_packages)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if is_testmode:
new = copy.deepcopy(new)
new.update(test_packages)
ret = salt.utils.data.compare_dicts(old, new)
if pkg_type == 'file' and reinstall:
# For file-based packages, prepare 'to_reinstall' to have a list
# of all the package names that may have been reinstalled.
# This way, we could include reinstalled packages in 'ret'.
for pkgfile in to_install:
# Convert from file name to package name.
cmd = ['opkg', 'info', pkgfile]
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] == 0:
# Just need the package name.
pkginfo_dict = _process_info_installed_output(
out['stdout'], []
)
if pkginfo_dict:
to_reinstall.append(list(pkginfo_dict.keys())[0])
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def _parse_reported_packages_from_remove_output(output):
'''
Parses the output of "opkg remove" to determine what packages would have been
removed by an operation run with the --noaction flag.
We are looking for lines like
Removing <package> (<version>) from <Target>...
'''
reported_pkgs = {}
remove_pattern = re.compile(r'Removing\s(?P<package>.*?)\s\((?P<version>.*?)\)\sfrom\s(?P<target>.*?)...')
for line in salt.utils.itertools.split(output, '\n'):
match = remove_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = ''
return reported_pkgs
def remove(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Remove packages using ``opkg remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
remove_dependencies
Remove package and all dependencies
.. versionadded:: 2019.2.0
auto_remove_deps
Remove packages that were installed automatically to satisfy dependencies
.. versionadded:: 2019.2.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
salt '*' pkg.remove pkgs='["foo", "bar"]' remove_dependencies=True auto_remove_deps=True
'''
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 {}
cmd = ['opkg', 'remove']
_append_noaction_if_testmode(cmd, **kwargs)
if kwargs.get('remove_dependencies', False):
cmd.append('--force-removal-of-dependent-packages')
if kwargs.get('auto_remove_deps', False):
cmd.append('--autoremove')
cmd.extend(targets)
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors = [out['stderr']]
else:
errors = [out['stdout']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if _is_testmode(**kwargs):
reportedPkgs = _parse_reported_packages_from_remove_output(out['stdout'])
new = {k: v for k, v in new.items() if k not in reportedPkgs}
ret = salt.utils.data.compare_dicts(old, new)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def purge(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Package purges are not supported by opkg, this function is identical to
:mod:`pkg.remove <salt.modules.opkg.remove>`.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name, pkgs=pkgs)
def upgrade(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
Upgrades all packages via ``opkg upgrade``
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
errors = []
if salt.utils.data.is_true(refresh):
refresh_db()
old = list_pkgs()
cmd = ['opkg', 'upgrade']
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
errors.append(result)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif state != 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = _set_state(target, 'hold')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif state == 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret['comment'] = ('Package {0} is set not to be held.'
.format(target))
else:
result = _set_state(target, 'ok')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def _get_state(pkg):
'''
View package state from the opkg database
Return the state of pkg
'''
cmd = ['opkg', 'status']
cmd.append(pkg)
out = __salt__['cmd.run'](cmd, python_shell=False)
state_flag = ''
for line in salt.utils.itertools.split(out, '\n'):
if line.startswith('Status'):
_status, _state_want, state_flag, _state_status = line.split()
return state_flag
def _set_state(pkg, state):
'''
Change package state on the opkg database
The state can be any of:
- hold
- noprune
- user
- ok
- installed
- unpacked
This command is commonly used to mark a specific package to be held from
being upgraded, that is, to be kept at a certain version.
Returns a dict containing the package name, and the new and old
versions.
'''
ret = {}
valid_states = ('hold', 'noprune', 'user', 'ok', 'installed', 'unpacked')
if state not in valid_states:
raise SaltInvocationError('Invalid state: {0}'.format(state))
oldstate = _get_state(pkg)
cmd = ['opkg', 'flag']
cmd.append(state)
cmd.append(pkg)
_out = __salt__['cmd.run'](cmd, python_shell=False)
# Missing return value check due to opkg issue 160
ret[pkg] = {'old': oldstate,
'new': state}
return ret
def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
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
cmd = ['opkg', 'list-installed']
ret = {}
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
# This is a continuation of package description
if not line or line[0] == ' ':
continue
# This contains package name, version, and description.
# Extract the first two.
pkg_name, pkg_version = line.split(' - ', 2)[:2]
__salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version)
__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 list_upgrades(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
List all available package upgrades.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
ret = {}
if salt.utils.data.is_true(refresh):
refresh_db()
cmd = ['opkg', 'list-upgradable']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
if 'stdout' in call:
comment += call['stdout']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
name, _oldversion, newversion = line.split(' - ')
ret[name] = newversion
return ret
def _convert_to_standard_attr(attr):
'''
Helper function for _process_info_installed_output()
Converts an opkg attribute name to a standard attribute
name which is used across 'pkg' modules.
'''
ret_attr = ATTR_MAP.get(attr, None)
if ret_attr is None:
# All others convert to lowercase
return attr.lower()
return ret_attr
def _process_info_installed_output(out, filter_attrs):
'''
Helper function for info_installed()
Processes stdout output from a single invocation of
'opkg status'.
'''
ret = {}
name = None
attrs = {}
attr = None
for line in salt.utils.itertools.split(out, '\n'):
if line and line[0] == ' ':
# This is a continuation of the last attr
if filter_attrs is None or attr in filter_attrs:
line = line.strip()
if attrs[attr]:
# If attr is empty, don't add leading newline
attrs[attr] += '\n'
attrs[attr] += line
continue
line = line.strip()
if not line:
# Separator between different packages
if name:
ret[name] = attrs
name = None
attrs = {}
attr = None
continue
key, value = line.split(':', 1)
value = value.lstrip()
attr = _convert_to_standard_attr(key)
if attr == 'name':
name = value
elif filter_attrs is None or attr in filter_attrs:
attrs[attr] = value
if name:
ret[name] = attrs
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
.. versionadded:: 2017.7.0
:param names:
Names of the packages to get information about. If none are specified,
will return information for all installed packages.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
arch, conffiles, conflicts, depends, description, filename, group,
install_date_time_t, md5sum, packager, provides, recommends,
replaces, size, source, suggests, url, version
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed
salt '*' pkg.info_installed attr=version,packager
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> attr=version,packager
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,packager
'''
attr = kwargs.pop('attr', None)
if attr is None:
filter_attrs = None
elif isinstance(attr, six.string_types):
filter_attrs = set(attr.split(','))
else:
filter_attrs = set(attr)
ret = {}
if names:
# Specific list of names of installed packages
for name in names:
cmd = ['opkg', 'status', name]
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
else:
# All installed packages
cmd = ['opkg', 'status']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
return ret
def upgrade_available(name, **kwargs): # pylint: disable=unused-argument
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs): # pylint: disable=unused-argument
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2016.3.4
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0' '0.2.4.1-0'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] if ignore_epoch else six.text_type(x)
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
output = __salt__['cmd.run_stdout'](['opkg', '--version'],
output_loglevel='trace',
python_shell=False)
opkg_version = output.split(' ')[2].strip()
if salt.utils.versions.LooseVersion(opkg_version) >= \
salt.utils.versions.LooseVersion('0.3.4'):
cmd_compare = ['opkg', 'compare-versions']
elif salt.utils.path.which('opkg-compare-versions'):
cmd_compare = ['opkg-compare-versions']
else:
log.warning('Unable to find a compare-versions utility installed. Either upgrade opkg to '
'version > 0.3.4 (preferred) or install the older opkg-compare-versions script.')
return None
for oper, ret in (("<<", -1), ("=", 0), (">>", 1)):
cmd = cmd_compare[:]
cmd.append(_cmd_quote(pkg1))
cmd.append(oper)
cmd.append(_cmd_quote(pkg2))
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
ignore_retcode=True,
python_shell=False)
if retcode == 0:
return ret
return None
def _set_repo_option(repo, option):
'''
Set the option to repo
'''
if not option:
return
opt = option.split('=')
if len(opt) != 2:
return
if opt[0] == 'trusted':
repo['trusted'] = opt[1] == 'yes'
else:
repo[opt[0]] = opt[1]
def _set_repo_options(repo, options):
'''
Set the options to the repo.
'''
delimiters = "[", "]"
pattern = '|'.join(map(re.escape, delimiters))
for option in options:
splitted = re.split(pattern, option)
for opt in splitted:
_set_repo_option(repo, opt)
def _create_repo(line, filename):
'''
Create repo
'''
repo = {}
if line.startswith('#'):
repo['enabled'] = False
line = line[1:]
else:
repo['enabled'] = True
cols = salt.utils.args.shlex_split(line.strip())
repo['compressed'] = not cols[0] in 'src'
repo['name'] = cols[1]
repo['uri'] = cols[2]
repo['file'] = os.path.join(OPKG_CONFDIR, filename)
if len(cols) > 3:
_set_repo_options(repo, cols[3:])
return repo
def _read_repos(conf_file, repos, filename, regex):
'''
Read repos from configuration file
'''
for line in conf_file:
line = salt.utils.stringutils.to_unicode(line)
if not regex.search(line):
continue
repo = _create_repo(line, filename)
# do not store duplicated uri's
if repo['uri'] not in repos:
repos[repo['uri']] = [repo]
def list_repos(**kwargs): # pylint: disable=unused-argument
'''
Lists all repos on ``/etc/opkg/*.conf``
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos = {}
regex = re.compile(REPO_REGEXP)
for filename in os.listdir(OPKG_CONFDIR):
if not filename.endswith(".conf"):
continue
with salt.utils.files.fopen(os.path.join(OPKG_CONFDIR, filename)) as conf_file:
_read_repos(conf_file, repos, filename, regex)
return repos
def get_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Display a repo from the ``/etc/opkg/*.conf``
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo repo
'''
repos = list_repos()
if repos:
for source in six.itervalues(repos):
for sub in source:
if sub['name'] == repo:
return sub
return {}
def _set_trusted_option_if_needed(repostr, trusted):
'''
Set trusted option to repo if needed
'''
if trusted is True:
repostr += ' [trusted=yes]'
elif trusted is False:
repostr += ' [trusted=no]'
return repostr
def _add_new_repo(repo, properties):
'''
Add a new repo entry
'''
repostr = '# ' if not properties.get('enabled') else ''
repostr += 'src/gz ' if properties.get('compressed') else 'src '
if ' ' in repo:
repostr += '"' + repo + '" '
else:
repostr += repo + ' '
repostr += properties.get('uri')
repostr = _set_trusted_option_if_needed(repostr, properties.get('trusted'))
repostr += '\n'
conffile = os.path.join(OPKG_CONFDIR, repo + '.conf')
with salt.utils.files.fopen(conffile, 'a') as fhandle:
fhandle.write(salt.utils.stringutils.to_str(repostr))
def _mod_repo_in_file(repo, repostr, filepath):
'''
Replace a repo entry in filepath with repostr
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
for line in fhandle:
cols = salt.utils.args.shlex_split(
salt.utils.stringutils.to_unicode(line).strip()
)
if repo not in cols:
output.append(line)
else:
output.append(salt.utils.stringutils.to_str(repostr + '\n'))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def del_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Delete a repo from ``/etc/opkg/*.conf``
If the file does not contain any other repo configuration, the file itself
will be deleted.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo repo
'''
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
repos = list_repos()
if repos:
deleted_from = dict()
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
deleted_from[source['file']] = 0
_del_repo_from_file(repo, source['file'])
if deleted_from:
ret = ''
for repository in repos:
source = repos[repository][0]
if source['file'] in deleted_from:
deleted_from[source['file']] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 1 and os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.\n')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
if refresh:
refresh_db()
return ret
return "Repo {0} doesn't exist in the opkg repo lists".format(repo)
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as uri is defined.
The following options are available to modify a repo definition:
repo
alias by which opkg refers to the repo.
uri
the URI to the repo.
compressed
defines (True or False) if the index file is compressed
enabled
enable or disable (True or False) repository
but do not remove if disabled.
refresh
enable or disable (True or False) auto-refresh of the repositories
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo repo uri=http://new/uri
salt '*' pkg.mod_repo repo enabled=False
'''
repos = list_repos()
found = False
uri = ''
if 'uri' in kwargs:
uri = kwargs['uri']
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
found = True
repostr = ''
if 'enabled' in kwargs and not kwargs['enabled']:
repostr += '# '
if 'compressed' in kwargs:
repostr += 'src/gz ' if kwargs['compressed'] else 'src'
else:
repostr += 'src/gz' if source['compressed'] else 'src'
repo_alias = kwargs['alias'] if 'alias' in kwargs else repo
if ' ' in repo_alias:
repostr += ' "{0}"'.format(repo_alias)
else:
repostr += ' {0}'.format(repo_alias)
repostr += ' {0}'.format(kwargs['uri'] if 'uri' in kwargs else source['uri'])
trusted = kwargs.get('trusted')
repostr = _set_trusted_option_if_needed(repostr, trusted) if trusted is not None else \
_set_trusted_option_if_needed(repostr, source.get('trusted'))
_mod_repo_in_file(repo, repostr, source['file'])
elif uri and source['uri'] == uri:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(uri, source['name']))
if not found:
# Need to add a new repo
if 'uri' not in kwargs:
raise CommandExecutionError(
'Repository \'{0}\' not found and no URI passed to create one.'.format(repo))
properties = {'uri': kwargs['uri']}
# If compressed is not defined, assume True
properties['compressed'] = kwargs['compressed'] if 'compressed' in kwargs else True
# If enabled is not defined, assume True
properties['enabled'] = kwargs['enabled'] if 'enabled' in kwargs else True
properties['trusted'] = kwargs.get('trusted')
_add_new_repo(repo, properties)
if 'refresh' in kwargs:
refresh_db()
def file_list(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
output = file_dict(*packages)
files = []
for package in list(output['packages'].values()):
files.extend(package)
return {'errors': output['errors'], 'files': files}
def file_dict(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
errors = []
ret = {}
cmd_files = ['opkg', 'files']
if not packages:
packages = list(list_pkgs().keys())
for package in packages:
files = []
cmd = cmd_files[:]
cmd.append(package)
out = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
for line in out['stdout'].splitlines():
if line.startswith('/'):
files.append(line)
elif line.startswith(' * '):
errors.append(line[3:])
break
else:
continue
if files:
ret[package] = files
return {'errors': errors, 'packages': ret}
def owner(*paths, **kwargs): # pylint: disable=unused-argument
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.opkg.version`, if a single
path is passed, a string will be returned, and if multiple paths are passed,
a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
cmd_search = ['opkg', 'search']
for path in paths:
cmd = cmd_search[:]
cmd.append(path)
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
if output:
ret[path] = output.split(' - ')[0].strip()
else:
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def version_clean(version):
'''
Clean the version string removing extra data.
There's nothing do to here for nipkg.py, therefore it will always
return the given version.
'''
return version
def check_extra_requirements(pkgname, pkgver):
'''
Check if the installed package already has the given requirements.
There's nothing do to here for nipkg.py, therefore it will always
return True.
'''
return True
|
saltstack/salt
|
salt/modules/opkg.py
|
_set_trusted_option_if_needed
|
python
|
def _set_trusted_option_if_needed(repostr, trusted):
'''
Set trusted option to repo if needed
'''
if trusted is True:
repostr += ' [trusted=yes]'
elif trusted is False:
repostr += ' [trusted=no]'
return repostr
|
Set trusted option to repo if needed
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/opkg.py#L1368-L1376
| null |
# -*- coding: utf-8 -*-
'''
Support for Opkg
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
.. versionadded: 2016.3.0
.. note::
For version comparison support on opkg < 0.3.4, the ``opkg-utils`` package
must be installed.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import os
import re
import logging
import errno
# Import salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.itertools
import salt.utils.path
import salt.utils.pkg
import salt.utils.stringutils
import salt.utils.versions
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import shlex_quote as _cmd_quote # pylint: disable=import-error
from salt.ext.six.moves import map # pylint: disable=import-error,redefined-builtin
REPO_REGEXP = r'^#?\s*(src|src/gz)\s+([^\s<>]+|"[^<>]+")\s+[^\s<>]+'
OPKG_CONFDIR = '/etc/opkg'
ATTR_MAP = {
'Architecture': 'arch',
'Homepage': 'url',
'Installed-Time': 'install_date_time_t',
'Maintainer': 'packager',
'Package': 'name',
'Section': 'group'
}
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
NILRT_RESTARTCHECK_STATE_PATH = '/var/lib/salt/restartcheck_state'
def _update_nilrt_restart_state():
'''
NILRT systems determine whether to reboot after various package operations
including but not limited to kernel module installs/removals by checking
specific file md5sums & timestamps. These files are touched/modified by
the post-install/post-remove functions of their respective packages.
The opkg module uses this function to store/update those file timestamps
and checksums to be used later by the restartcheck module.
'''
__salt__['cmd.shell']('stat -c %Y /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.timestamp'
.format(NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.md5sum'
.format(NILRT_RESTARTCHECK_STATE_PATH))
# We can't assume nisysapi.ini always exists like modules.dep
nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'
if os.path.exists(nisysapi_path):
__salt__['cmd.shell']('stat -c %Y {0} >{1}/nisysapi.ini.timestamp'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0} >{1}/nisysapi.ini.md5sum'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
# Expert plugin files get added to a conf.d dir, so keep track of the total
# no. of files, their timestamps and content hashes
nisysapi_conf_d_path = "/usr/lib/{0}/nisysapi/conf.d/experts/".format(
'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'
)
if os.path.exists(nisysapi_conf_d_path):
with salt.utils.files.fopen('{0}/sysapi.conf.d.count'.format(
NILRT_RESTARTCHECK_STATE_PATH), 'w') as fcount:
fcount.write(str(len(os.listdir(nisysapi_conf_d_path))))
for fexpert in os.listdir(nisysapi_conf_d_path):
__salt__['cmd.shell']('stat -c %Y {0}/{1} >{2}/{1}.timestamp'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0}/{1} >{2}/{1}.md5sum'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
def _get_restartcheck_result(errors):
'''
Return restartcheck result and append errors (if any) to ``errors``
'''
rs_result = __salt__['restartcheck.restartcheck'](verbose=False)
if isinstance(rs_result, dict) and 'comment' in rs_result:
errors.append(rs_result['comment'])
return rs_result
def _process_restartcheck_result(rs_result, **kwargs):
'''
Check restartcheck output to see if system/service restarts were requested
and take appropriate action.
'''
if 'No packages seem to need to be restarted' in rs_result:
return
reboot_required = False
for rstr in rs_result:
if 'System restart required' in rstr:
_update_nilrt_restart_state()
__salt__['system.set_reboot_required_witnessed']()
reboot_required = True
if kwargs.get('always_restart_services', True) or not reboot_required:
for rstr in rs_result:
if 'System restart required' not in rstr:
service = os.path.join('/etc/init.d', rstr)
if os.path.exists(service):
__salt__['cmd.run']([service, 'restart'])
def __virtual__():
'''
Confirm this module is on a nilrt based system
'''
if __grains__.get('os_family') == 'NILinuxRT':
try:
os.makedirs(NILRT_RESTARTCHECK_STATE_PATH)
except OSError as exc:
if exc.errno != errno.EEXIST:
return False, 'Error creating {0} (-{1}): {2}'.format(
NILRT_RESTARTCHECK_STATE_PATH,
exc.errno,
exc.strerror)
# populate state dir if empty
if not os.listdir(NILRT_RESTARTCHECK_STATE_PATH):
_update_nilrt_restart_state()
return __virtualname__
if os.path.isdir(OPKG_CONFDIR):
return __virtualname__
return False, "Module opkg only works on OpenEmbedded based systems"
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
if not names:
return ''
ret = {}
for name in names:
ret[name] = ''
# Refresh before looking for the latest version available
if refresh:
refresh_db()
cmd = ['opkg', 'list-upgradable']
out = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
try:
name, _oldversion, newversion = line.split(' - ')
if name in names:
ret[name] = newversion
except ValueError:
pass
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = latest_version
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(failhard=False, **kwargs): # pylint: disable=unused-argument
'''
Updates the opkg database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
failhard
If False, return results of failed lines as ``False`` for the package
database that encountered the error.
If True, raise an error with a list of the package databases that
encountered errors.
.. versionadded:: 2018.3.0
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
error_repos = []
cmd = ['opkg', 'update']
# opkg returns a non-zero retcode when there is a failure to refresh
# from one or more repos. Due to this, ignore the retcode.
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True,
redirect_stderr=True)
out = call['stdout']
prev_line = ''
for line in salt.utils.itertools.split(out, '\n'):
if 'Inflating' in line:
key = line.strip().split()[1][:-1]
ret[key] = True
elif 'Updated source' in line:
# Use the previous line.
key = prev_line.strip().split()[1][:-1]
ret[key] = True
elif 'Failed to download' in line:
key = line.strip().split()[5].split(',')[0]
ret[key] = False
error_repos.append(key)
prev_line = line
if failhard and error_repos:
raise CommandExecutionError(
'Error getting repos: {0}'.format(', '.join(error_repos))
)
# On a non-zero exit code where no failed repos were found, raise an
# exception because this appears to be a different kind of error.
if call['retcode'] != 0 and not error_repos:
raise CommandExecutionError(out)
return ret
def _is_testmode(**kwargs):
'''
Returns whether a test mode (noaction) operation was requested.
'''
return bool(kwargs.get('test') or __opts__.get('test'))
def _append_noaction_if_testmode(cmd, **kwargs):
'''
Adds the --noaction flag to the command if it's running in the test mode.
'''
if _is_testmode(**kwargs):
cmd.append('--noaction')
def _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall):
'''
Builds a list of install commands to be executed in sequence in order to process
each of the to_install, to_downgrade, and to_reinstall lists.
'''
cmds = []
if to_install:
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(to_install)
cmds.append(cmd)
if to_downgrade:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-downgrade')
cmd.extend(to_downgrade)
cmds.append(cmd)
if to_reinstall:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-reinstall')
cmd.extend(to_reinstall)
cmds.append(cmd)
return cmds
def _parse_reported_packages_from_install_output(output):
'''
Parses the output of "opkg install" to determine what packages would have been
installed by an operation run with the --noaction flag.
We are looking for lines like:
Installing <package> (<version>) on <target>
or
Upgrading <package> from <oldVersion> to <version> on root
'''
reported_pkgs = {}
install_pattern = re.compile(r'Installing\s(?P<package>.*?)\s\((?P<version>.*?)\)\son\s(?P<target>.*?)')
upgrade_pattern = re.compile(r'Upgrading\s(?P<package>.*?)\sfrom\s(?P<oldVersion>.*?)\sto\s(?P<version>.*?)\son\s(?P<target>.*?)')
for line in salt.utils.itertools.split(output, '\n'):
match = install_pattern.match(line)
if match is None:
match = upgrade_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = match.group('version')
return reported_pkgs
def _execute_install_command(cmd, parse_output, errors, parsed_packages):
'''
Executes a command for the install operation.
If the command fails, its error output will be appended to the errors list.
If the command succeeds and parse_output is true, updated packages will be appended
to the parsed_packages dictionary.
'''
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors.append(out['stderr'])
else:
errors.append(out['stdout'])
elif parse_output:
parsed_packages.update(_parse_reported_packages_from_install_output(out['stdout']))
def install(name=None,
refresh=False,
pkgs=None,
sources=None,
reinstall=False,
**kwargs):
'''
Install the passed package, add refresh=True to update the opkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionadded:: 2017.7.0
reinstall : False
Specifying reinstall=True will use ``opkg install --force-reinstall``
rather than simply ``opkg install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``opkg
install --force-reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2017.7.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of IPK packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
install_recommends
Whether to install the packages marked as recommended. Default is True.
only_upgrade
Only upgrade the packages (disallow downgrades), if they are already
installed. Default is False.
.. versionadded:: 2017.7.0
always_restart_services
Whether to restart services even if a reboot is required. Default is True.
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
refreshdb = salt.utils.data.is_true(refresh)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
cmd_prefix = ['opkg', 'install']
to_install = []
to_reinstall = []
to_downgrade = []
_append_noaction_if_testmode(cmd_prefix, **kwargs)
if not pkg_params:
return {}
elif pkg_type == 'file':
if reinstall:
cmd_prefix.append('--force-reinstall')
if not kwargs.get('only_upgrade', False):
cmd_prefix.append('--force-downgrade')
to_install.extend(pkg_params)
elif pkg_type == 'repository':
if not kwargs.get('install_recommends', True):
cmd_prefix.append('--no-install-recommends')
for pkgname, pkgversion in six.iteritems(pkg_params):
if (name and pkgs is None and kwargs.get('version') and
len(pkg_params) == 1):
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
version_num = pkgversion
if version_num is None:
# Don't allow downgrades if the version
# number is not specified.
if reinstall and pkgname in old:
to_reinstall.append(pkgname)
else:
to_install.append(pkgname)
else:
pkgstr = '{0}={1}'.format(pkgname, version_num)
cver = old.get(pkgname, '')
if reinstall and cver and salt.utils.versions.compare(
ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall.append(pkgstr)
elif not cver or salt.utils.versions.compare(
ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
to_install.append(pkgstr)
else:
if not kwargs.get('only_upgrade', False):
to_downgrade.append(pkgstr)
else:
# This should cause the command to fail.
to_install.append(pkgstr)
cmds = _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall)
if not cmds:
return {}
if refreshdb:
refresh_db()
errors = []
is_testmode = _is_testmode(**kwargs)
test_packages = {}
for cmd in cmds:
_execute_install_command(cmd, is_testmode, errors, test_packages)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if is_testmode:
new = copy.deepcopy(new)
new.update(test_packages)
ret = salt.utils.data.compare_dicts(old, new)
if pkg_type == 'file' and reinstall:
# For file-based packages, prepare 'to_reinstall' to have a list
# of all the package names that may have been reinstalled.
# This way, we could include reinstalled packages in 'ret'.
for pkgfile in to_install:
# Convert from file name to package name.
cmd = ['opkg', 'info', pkgfile]
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] == 0:
# Just need the package name.
pkginfo_dict = _process_info_installed_output(
out['stdout'], []
)
if pkginfo_dict:
to_reinstall.append(list(pkginfo_dict.keys())[0])
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def _parse_reported_packages_from_remove_output(output):
'''
Parses the output of "opkg remove" to determine what packages would have been
removed by an operation run with the --noaction flag.
We are looking for lines like
Removing <package> (<version>) from <Target>...
'''
reported_pkgs = {}
remove_pattern = re.compile(r'Removing\s(?P<package>.*?)\s\((?P<version>.*?)\)\sfrom\s(?P<target>.*?)...')
for line in salt.utils.itertools.split(output, '\n'):
match = remove_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = ''
return reported_pkgs
def remove(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Remove packages using ``opkg remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
remove_dependencies
Remove package and all dependencies
.. versionadded:: 2019.2.0
auto_remove_deps
Remove packages that were installed automatically to satisfy dependencies
.. versionadded:: 2019.2.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
salt '*' pkg.remove pkgs='["foo", "bar"]' remove_dependencies=True auto_remove_deps=True
'''
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 {}
cmd = ['opkg', 'remove']
_append_noaction_if_testmode(cmd, **kwargs)
if kwargs.get('remove_dependencies', False):
cmd.append('--force-removal-of-dependent-packages')
if kwargs.get('auto_remove_deps', False):
cmd.append('--autoremove')
cmd.extend(targets)
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors = [out['stderr']]
else:
errors = [out['stdout']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if _is_testmode(**kwargs):
reportedPkgs = _parse_reported_packages_from_remove_output(out['stdout'])
new = {k: v for k, v in new.items() if k not in reportedPkgs}
ret = salt.utils.data.compare_dicts(old, new)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def purge(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Package purges are not supported by opkg, this function is identical to
:mod:`pkg.remove <salt.modules.opkg.remove>`.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name, pkgs=pkgs)
def upgrade(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
Upgrades all packages via ``opkg upgrade``
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
errors = []
if salt.utils.data.is_true(refresh):
refresh_db()
old = list_pkgs()
cmd = ['opkg', 'upgrade']
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
errors.append(result)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif state != 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = _set_state(target, 'hold')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif state == 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret['comment'] = ('Package {0} is set not to be held.'
.format(target))
else:
result = _set_state(target, 'ok')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def _get_state(pkg):
'''
View package state from the opkg database
Return the state of pkg
'''
cmd = ['opkg', 'status']
cmd.append(pkg)
out = __salt__['cmd.run'](cmd, python_shell=False)
state_flag = ''
for line in salt.utils.itertools.split(out, '\n'):
if line.startswith('Status'):
_status, _state_want, state_flag, _state_status = line.split()
return state_flag
def _set_state(pkg, state):
'''
Change package state on the opkg database
The state can be any of:
- hold
- noprune
- user
- ok
- installed
- unpacked
This command is commonly used to mark a specific package to be held from
being upgraded, that is, to be kept at a certain version.
Returns a dict containing the package name, and the new and old
versions.
'''
ret = {}
valid_states = ('hold', 'noprune', 'user', 'ok', 'installed', 'unpacked')
if state not in valid_states:
raise SaltInvocationError('Invalid state: {0}'.format(state))
oldstate = _get_state(pkg)
cmd = ['opkg', 'flag']
cmd.append(state)
cmd.append(pkg)
_out = __salt__['cmd.run'](cmd, python_shell=False)
# Missing return value check due to opkg issue 160
ret[pkg] = {'old': oldstate,
'new': state}
return ret
def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
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
cmd = ['opkg', 'list-installed']
ret = {}
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
# This is a continuation of package description
if not line or line[0] == ' ':
continue
# This contains package name, version, and description.
# Extract the first two.
pkg_name, pkg_version = line.split(' - ', 2)[:2]
__salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version)
__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 list_upgrades(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
List all available package upgrades.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
ret = {}
if salt.utils.data.is_true(refresh):
refresh_db()
cmd = ['opkg', 'list-upgradable']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
if 'stdout' in call:
comment += call['stdout']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
name, _oldversion, newversion = line.split(' - ')
ret[name] = newversion
return ret
def _convert_to_standard_attr(attr):
'''
Helper function for _process_info_installed_output()
Converts an opkg attribute name to a standard attribute
name which is used across 'pkg' modules.
'''
ret_attr = ATTR_MAP.get(attr, None)
if ret_attr is None:
# All others convert to lowercase
return attr.lower()
return ret_attr
def _process_info_installed_output(out, filter_attrs):
'''
Helper function for info_installed()
Processes stdout output from a single invocation of
'opkg status'.
'''
ret = {}
name = None
attrs = {}
attr = None
for line in salt.utils.itertools.split(out, '\n'):
if line and line[0] == ' ':
# This is a continuation of the last attr
if filter_attrs is None or attr in filter_attrs:
line = line.strip()
if attrs[attr]:
# If attr is empty, don't add leading newline
attrs[attr] += '\n'
attrs[attr] += line
continue
line = line.strip()
if not line:
# Separator between different packages
if name:
ret[name] = attrs
name = None
attrs = {}
attr = None
continue
key, value = line.split(':', 1)
value = value.lstrip()
attr = _convert_to_standard_attr(key)
if attr == 'name':
name = value
elif filter_attrs is None or attr in filter_attrs:
attrs[attr] = value
if name:
ret[name] = attrs
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
.. versionadded:: 2017.7.0
:param names:
Names of the packages to get information about. If none are specified,
will return information for all installed packages.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
arch, conffiles, conflicts, depends, description, filename, group,
install_date_time_t, md5sum, packager, provides, recommends,
replaces, size, source, suggests, url, version
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed
salt '*' pkg.info_installed attr=version,packager
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> attr=version,packager
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,packager
'''
attr = kwargs.pop('attr', None)
if attr is None:
filter_attrs = None
elif isinstance(attr, six.string_types):
filter_attrs = set(attr.split(','))
else:
filter_attrs = set(attr)
ret = {}
if names:
# Specific list of names of installed packages
for name in names:
cmd = ['opkg', 'status', name]
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
else:
# All installed packages
cmd = ['opkg', 'status']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
return ret
def upgrade_available(name, **kwargs): # pylint: disable=unused-argument
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs): # pylint: disable=unused-argument
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2016.3.4
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0' '0.2.4.1-0'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] if ignore_epoch else six.text_type(x)
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
output = __salt__['cmd.run_stdout'](['opkg', '--version'],
output_loglevel='trace',
python_shell=False)
opkg_version = output.split(' ')[2].strip()
if salt.utils.versions.LooseVersion(opkg_version) >= \
salt.utils.versions.LooseVersion('0.3.4'):
cmd_compare = ['opkg', 'compare-versions']
elif salt.utils.path.which('opkg-compare-versions'):
cmd_compare = ['opkg-compare-versions']
else:
log.warning('Unable to find a compare-versions utility installed. Either upgrade opkg to '
'version > 0.3.4 (preferred) or install the older opkg-compare-versions script.')
return None
for oper, ret in (("<<", -1), ("=", 0), (">>", 1)):
cmd = cmd_compare[:]
cmd.append(_cmd_quote(pkg1))
cmd.append(oper)
cmd.append(_cmd_quote(pkg2))
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
ignore_retcode=True,
python_shell=False)
if retcode == 0:
return ret
return None
def _set_repo_option(repo, option):
'''
Set the option to repo
'''
if not option:
return
opt = option.split('=')
if len(opt) != 2:
return
if opt[0] == 'trusted':
repo['trusted'] = opt[1] == 'yes'
else:
repo[opt[0]] = opt[1]
def _set_repo_options(repo, options):
'''
Set the options to the repo.
'''
delimiters = "[", "]"
pattern = '|'.join(map(re.escape, delimiters))
for option in options:
splitted = re.split(pattern, option)
for opt in splitted:
_set_repo_option(repo, opt)
def _create_repo(line, filename):
'''
Create repo
'''
repo = {}
if line.startswith('#'):
repo['enabled'] = False
line = line[1:]
else:
repo['enabled'] = True
cols = salt.utils.args.shlex_split(line.strip())
repo['compressed'] = not cols[0] in 'src'
repo['name'] = cols[1]
repo['uri'] = cols[2]
repo['file'] = os.path.join(OPKG_CONFDIR, filename)
if len(cols) > 3:
_set_repo_options(repo, cols[3:])
return repo
def _read_repos(conf_file, repos, filename, regex):
'''
Read repos from configuration file
'''
for line in conf_file:
line = salt.utils.stringutils.to_unicode(line)
if not regex.search(line):
continue
repo = _create_repo(line, filename)
# do not store duplicated uri's
if repo['uri'] not in repos:
repos[repo['uri']] = [repo]
def list_repos(**kwargs): # pylint: disable=unused-argument
'''
Lists all repos on ``/etc/opkg/*.conf``
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos = {}
regex = re.compile(REPO_REGEXP)
for filename in os.listdir(OPKG_CONFDIR):
if not filename.endswith(".conf"):
continue
with salt.utils.files.fopen(os.path.join(OPKG_CONFDIR, filename)) as conf_file:
_read_repos(conf_file, repos, filename, regex)
return repos
def get_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Display a repo from the ``/etc/opkg/*.conf``
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo repo
'''
repos = list_repos()
if repos:
for source in six.itervalues(repos):
for sub in source:
if sub['name'] == repo:
return sub
return {}
def _del_repo_from_file(repo, filepath):
'''
Remove a repo from filepath
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
regex = re.compile(REPO_REGEXP)
for line in fhandle:
line = salt.utils.stringutils.to_unicode(line)
if regex.search(line):
if line.startswith('#'):
line = line[1:]
cols = salt.utils.args.shlex_split(line.strip())
if repo != cols[1]:
output.append(salt.utils.stringutils.to_str(line))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def _add_new_repo(repo, properties):
'''
Add a new repo entry
'''
repostr = '# ' if not properties.get('enabled') else ''
repostr += 'src/gz ' if properties.get('compressed') else 'src '
if ' ' in repo:
repostr += '"' + repo + '" '
else:
repostr += repo + ' '
repostr += properties.get('uri')
repostr = _set_trusted_option_if_needed(repostr, properties.get('trusted'))
repostr += '\n'
conffile = os.path.join(OPKG_CONFDIR, repo + '.conf')
with salt.utils.files.fopen(conffile, 'a') as fhandle:
fhandle.write(salt.utils.stringutils.to_str(repostr))
def _mod_repo_in_file(repo, repostr, filepath):
'''
Replace a repo entry in filepath with repostr
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
for line in fhandle:
cols = salt.utils.args.shlex_split(
salt.utils.stringutils.to_unicode(line).strip()
)
if repo not in cols:
output.append(line)
else:
output.append(salt.utils.stringutils.to_str(repostr + '\n'))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def del_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Delete a repo from ``/etc/opkg/*.conf``
If the file does not contain any other repo configuration, the file itself
will be deleted.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo repo
'''
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
repos = list_repos()
if repos:
deleted_from = dict()
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
deleted_from[source['file']] = 0
_del_repo_from_file(repo, source['file'])
if deleted_from:
ret = ''
for repository in repos:
source = repos[repository][0]
if source['file'] in deleted_from:
deleted_from[source['file']] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 1 and os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.\n')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
if refresh:
refresh_db()
return ret
return "Repo {0} doesn't exist in the opkg repo lists".format(repo)
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as uri is defined.
The following options are available to modify a repo definition:
repo
alias by which opkg refers to the repo.
uri
the URI to the repo.
compressed
defines (True or False) if the index file is compressed
enabled
enable or disable (True or False) repository
but do not remove if disabled.
refresh
enable or disable (True or False) auto-refresh of the repositories
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo repo uri=http://new/uri
salt '*' pkg.mod_repo repo enabled=False
'''
repos = list_repos()
found = False
uri = ''
if 'uri' in kwargs:
uri = kwargs['uri']
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
found = True
repostr = ''
if 'enabled' in kwargs and not kwargs['enabled']:
repostr += '# '
if 'compressed' in kwargs:
repostr += 'src/gz ' if kwargs['compressed'] else 'src'
else:
repostr += 'src/gz' if source['compressed'] else 'src'
repo_alias = kwargs['alias'] if 'alias' in kwargs else repo
if ' ' in repo_alias:
repostr += ' "{0}"'.format(repo_alias)
else:
repostr += ' {0}'.format(repo_alias)
repostr += ' {0}'.format(kwargs['uri'] if 'uri' in kwargs else source['uri'])
trusted = kwargs.get('trusted')
repostr = _set_trusted_option_if_needed(repostr, trusted) if trusted is not None else \
_set_trusted_option_if_needed(repostr, source.get('trusted'))
_mod_repo_in_file(repo, repostr, source['file'])
elif uri and source['uri'] == uri:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(uri, source['name']))
if not found:
# Need to add a new repo
if 'uri' not in kwargs:
raise CommandExecutionError(
'Repository \'{0}\' not found and no URI passed to create one.'.format(repo))
properties = {'uri': kwargs['uri']}
# If compressed is not defined, assume True
properties['compressed'] = kwargs['compressed'] if 'compressed' in kwargs else True
# If enabled is not defined, assume True
properties['enabled'] = kwargs['enabled'] if 'enabled' in kwargs else True
properties['trusted'] = kwargs.get('trusted')
_add_new_repo(repo, properties)
if 'refresh' in kwargs:
refresh_db()
def file_list(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
output = file_dict(*packages)
files = []
for package in list(output['packages'].values()):
files.extend(package)
return {'errors': output['errors'], 'files': files}
def file_dict(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
errors = []
ret = {}
cmd_files = ['opkg', 'files']
if not packages:
packages = list(list_pkgs().keys())
for package in packages:
files = []
cmd = cmd_files[:]
cmd.append(package)
out = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
for line in out['stdout'].splitlines():
if line.startswith('/'):
files.append(line)
elif line.startswith(' * '):
errors.append(line[3:])
break
else:
continue
if files:
ret[package] = files
return {'errors': errors, 'packages': ret}
def owner(*paths, **kwargs): # pylint: disable=unused-argument
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.opkg.version`, if a single
path is passed, a string will be returned, and if multiple paths are passed,
a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
cmd_search = ['opkg', 'search']
for path in paths:
cmd = cmd_search[:]
cmd.append(path)
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
if output:
ret[path] = output.split(' - ')[0].strip()
else:
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def version_clean(version):
'''
Clean the version string removing extra data.
There's nothing do to here for nipkg.py, therefore it will always
return the given version.
'''
return version
def check_extra_requirements(pkgname, pkgver):
'''
Check if the installed package already has the given requirements.
There's nothing do to here for nipkg.py, therefore it will always
return True.
'''
return True
|
saltstack/salt
|
salt/modules/opkg.py
|
_add_new_repo
|
python
|
def _add_new_repo(repo, properties):
'''
Add a new repo entry
'''
repostr = '# ' if not properties.get('enabled') else ''
repostr += 'src/gz ' if properties.get('compressed') else 'src '
if ' ' in repo:
repostr += '"' + repo + '" '
else:
repostr += repo + ' '
repostr += properties.get('uri')
repostr = _set_trusted_option_if_needed(repostr, properties.get('trusted'))
repostr += '\n'
conffile = os.path.join(OPKG_CONFDIR, repo + '.conf')
with salt.utils.files.fopen(conffile, 'a') as fhandle:
fhandle.write(salt.utils.stringutils.to_str(repostr))
|
Add a new repo entry
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/opkg.py#L1379-L1395
| null |
# -*- coding: utf-8 -*-
'''
Support for Opkg
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
.. versionadded: 2016.3.0
.. note::
For version comparison support on opkg < 0.3.4, the ``opkg-utils`` package
must be installed.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import os
import re
import logging
import errno
# Import salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.itertools
import salt.utils.path
import salt.utils.pkg
import salt.utils.stringutils
import salt.utils.versions
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import shlex_quote as _cmd_quote # pylint: disable=import-error
from salt.ext.six.moves import map # pylint: disable=import-error,redefined-builtin
REPO_REGEXP = r'^#?\s*(src|src/gz)\s+([^\s<>]+|"[^<>]+")\s+[^\s<>]+'
OPKG_CONFDIR = '/etc/opkg'
ATTR_MAP = {
'Architecture': 'arch',
'Homepage': 'url',
'Installed-Time': 'install_date_time_t',
'Maintainer': 'packager',
'Package': 'name',
'Section': 'group'
}
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
NILRT_RESTARTCHECK_STATE_PATH = '/var/lib/salt/restartcheck_state'
def _update_nilrt_restart_state():
'''
NILRT systems determine whether to reboot after various package operations
including but not limited to kernel module installs/removals by checking
specific file md5sums & timestamps. These files are touched/modified by
the post-install/post-remove functions of their respective packages.
The opkg module uses this function to store/update those file timestamps
and checksums to be used later by the restartcheck module.
'''
__salt__['cmd.shell']('stat -c %Y /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.timestamp'
.format(NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.md5sum'
.format(NILRT_RESTARTCHECK_STATE_PATH))
# We can't assume nisysapi.ini always exists like modules.dep
nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'
if os.path.exists(nisysapi_path):
__salt__['cmd.shell']('stat -c %Y {0} >{1}/nisysapi.ini.timestamp'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0} >{1}/nisysapi.ini.md5sum'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
# Expert plugin files get added to a conf.d dir, so keep track of the total
# no. of files, their timestamps and content hashes
nisysapi_conf_d_path = "/usr/lib/{0}/nisysapi/conf.d/experts/".format(
'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'
)
if os.path.exists(nisysapi_conf_d_path):
with salt.utils.files.fopen('{0}/sysapi.conf.d.count'.format(
NILRT_RESTARTCHECK_STATE_PATH), 'w') as fcount:
fcount.write(str(len(os.listdir(nisysapi_conf_d_path))))
for fexpert in os.listdir(nisysapi_conf_d_path):
__salt__['cmd.shell']('stat -c %Y {0}/{1} >{2}/{1}.timestamp'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0}/{1} >{2}/{1}.md5sum'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
def _get_restartcheck_result(errors):
'''
Return restartcheck result and append errors (if any) to ``errors``
'''
rs_result = __salt__['restartcheck.restartcheck'](verbose=False)
if isinstance(rs_result, dict) and 'comment' in rs_result:
errors.append(rs_result['comment'])
return rs_result
def _process_restartcheck_result(rs_result, **kwargs):
'''
Check restartcheck output to see if system/service restarts were requested
and take appropriate action.
'''
if 'No packages seem to need to be restarted' in rs_result:
return
reboot_required = False
for rstr in rs_result:
if 'System restart required' in rstr:
_update_nilrt_restart_state()
__salt__['system.set_reboot_required_witnessed']()
reboot_required = True
if kwargs.get('always_restart_services', True) or not reboot_required:
for rstr in rs_result:
if 'System restart required' not in rstr:
service = os.path.join('/etc/init.d', rstr)
if os.path.exists(service):
__salt__['cmd.run']([service, 'restart'])
def __virtual__():
'''
Confirm this module is on a nilrt based system
'''
if __grains__.get('os_family') == 'NILinuxRT':
try:
os.makedirs(NILRT_RESTARTCHECK_STATE_PATH)
except OSError as exc:
if exc.errno != errno.EEXIST:
return False, 'Error creating {0} (-{1}): {2}'.format(
NILRT_RESTARTCHECK_STATE_PATH,
exc.errno,
exc.strerror)
# populate state dir if empty
if not os.listdir(NILRT_RESTARTCHECK_STATE_PATH):
_update_nilrt_restart_state()
return __virtualname__
if os.path.isdir(OPKG_CONFDIR):
return __virtualname__
return False, "Module opkg only works on OpenEmbedded based systems"
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
if not names:
return ''
ret = {}
for name in names:
ret[name] = ''
# Refresh before looking for the latest version available
if refresh:
refresh_db()
cmd = ['opkg', 'list-upgradable']
out = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
try:
name, _oldversion, newversion = line.split(' - ')
if name in names:
ret[name] = newversion
except ValueError:
pass
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = latest_version
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(failhard=False, **kwargs): # pylint: disable=unused-argument
'''
Updates the opkg database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
failhard
If False, return results of failed lines as ``False`` for the package
database that encountered the error.
If True, raise an error with a list of the package databases that
encountered errors.
.. versionadded:: 2018.3.0
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
error_repos = []
cmd = ['opkg', 'update']
# opkg returns a non-zero retcode when there is a failure to refresh
# from one or more repos. Due to this, ignore the retcode.
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True,
redirect_stderr=True)
out = call['stdout']
prev_line = ''
for line in salt.utils.itertools.split(out, '\n'):
if 'Inflating' in line:
key = line.strip().split()[1][:-1]
ret[key] = True
elif 'Updated source' in line:
# Use the previous line.
key = prev_line.strip().split()[1][:-1]
ret[key] = True
elif 'Failed to download' in line:
key = line.strip().split()[5].split(',')[0]
ret[key] = False
error_repos.append(key)
prev_line = line
if failhard and error_repos:
raise CommandExecutionError(
'Error getting repos: {0}'.format(', '.join(error_repos))
)
# On a non-zero exit code where no failed repos were found, raise an
# exception because this appears to be a different kind of error.
if call['retcode'] != 0 and not error_repos:
raise CommandExecutionError(out)
return ret
def _is_testmode(**kwargs):
'''
Returns whether a test mode (noaction) operation was requested.
'''
return bool(kwargs.get('test') or __opts__.get('test'))
def _append_noaction_if_testmode(cmd, **kwargs):
'''
Adds the --noaction flag to the command if it's running in the test mode.
'''
if _is_testmode(**kwargs):
cmd.append('--noaction')
def _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall):
'''
Builds a list of install commands to be executed in sequence in order to process
each of the to_install, to_downgrade, and to_reinstall lists.
'''
cmds = []
if to_install:
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(to_install)
cmds.append(cmd)
if to_downgrade:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-downgrade')
cmd.extend(to_downgrade)
cmds.append(cmd)
if to_reinstall:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-reinstall')
cmd.extend(to_reinstall)
cmds.append(cmd)
return cmds
def _parse_reported_packages_from_install_output(output):
'''
Parses the output of "opkg install" to determine what packages would have been
installed by an operation run with the --noaction flag.
We are looking for lines like:
Installing <package> (<version>) on <target>
or
Upgrading <package> from <oldVersion> to <version> on root
'''
reported_pkgs = {}
install_pattern = re.compile(r'Installing\s(?P<package>.*?)\s\((?P<version>.*?)\)\son\s(?P<target>.*?)')
upgrade_pattern = re.compile(r'Upgrading\s(?P<package>.*?)\sfrom\s(?P<oldVersion>.*?)\sto\s(?P<version>.*?)\son\s(?P<target>.*?)')
for line in salt.utils.itertools.split(output, '\n'):
match = install_pattern.match(line)
if match is None:
match = upgrade_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = match.group('version')
return reported_pkgs
def _execute_install_command(cmd, parse_output, errors, parsed_packages):
'''
Executes a command for the install operation.
If the command fails, its error output will be appended to the errors list.
If the command succeeds and parse_output is true, updated packages will be appended
to the parsed_packages dictionary.
'''
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors.append(out['stderr'])
else:
errors.append(out['stdout'])
elif parse_output:
parsed_packages.update(_parse_reported_packages_from_install_output(out['stdout']))
def install(name=None,
refresh=False,
pkgs=None,
sources=None,
reinstall=False,
**kwargs):
'''
Install the passed package, add refresh=True to update the opkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionadded:: 2017.7.0
reinstall : False
Specifying reinstall=True will use ``opkg install --force-reinstall``
rather than simply ``opkg install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``opkg
install --force-reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2017.7.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of IPK packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
install_recommends
Whether to install the packages marked as recommended. Default is True.
only_upgrade
Only upgrade the packages (disallow downgrades), if they are already
installed. Default is False.
.. versionadded:: 2017.7.0
always_restart_services
Whether to restart services even if a reboot is required. Default is True.
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
refreshdb = salt.utils.data.is_true(refresh)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
cmd_prefix = ['opkg', 'install']
to_install = []
to_reinstall = []
to_downgrade = []
_append_noaction_if_testmode(cmd_prefix, **kwargs)
if not pkg_params:
return {}
elif pkg_type == 'file':
if reinstall:
cmd_prefix.append('--force-reinstall')
if not kwargs.get('only_upgrade', False):
cmd_prefix.append('--force-downgrade')
to_install.extend(pkg_params)
elif pkg_type == 'repository':
if not kwargs.get('install_recommends', True):
cmd_prefix.append('--no-install-recommends')
for pkgname, pkgversion in six.iteritems(pkg_params):
if (name and pkgs is None and kwargs.get('version') and
len(pkg_params) == 1):
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
version_num = pkgversion
if version_num is None:
# Don't allow downgrades if the version
# number is not specified.
if reinstall and pkgname in old:
to_reinstall.append(pkgname)
else:
to_install.append(pkgname)
else:
pkgstr = '{0}={1}'.format(pkgname, version_num)
cver = old.get(pkgname, '')
if reinstall and cver and salt.utils.versions.compare(
ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall.append(pkgstr)
elif not cver or salt.utils.versions.compare(
ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
to_install.append(pkgstr)
else:
if not kwargs.get('only_upgrade', False):
to_downgrade.append(pkgstr)
else:
# This should cause the command to fail.
to_install.append(pkgstr)
cmds = _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall)
if not cmds:
return {}
if refreshdb:
refresh_db()
errors = []
is_testmode = _is_testmode(**kwargs)
test_packages = {}
for cmd in cmds:
_execute_install_command(cmd, is_testmode, errors, test_packages)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if is_testmode:
new = copy.deepcopy(new)
new.update(test_packages)
ret = salt.utils.data.compare_dicts(old, new)
if pkg_type == 'file' and reinstall:
# For file-based packages, prepare 'to_reinstall' to have a list
# of all the package names that may have been reinstalled.
# This way, we could include reinstalled packages in 'ret'.
for pkgfile in to_install:
# Convert from file name to package name.
cmd = ['opkg', 'info', pkgfile]
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] == 0:
# Just need the package name.
pkginfo_dict = _process_info_installed_output(
out['stdout'], []
)
if pkginfo_dict:
to_reinstall.append(list(pkginfo_dict.keys())[0])
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def _parse_reported_packages_from_remove_output(output):
'''
Parses the output of "opkg remove" to determine what packages would have been
removed by an operation run with the --noaction flag.
We are looking for lines like
Removing <package> (<version>) from <Target>...
'''
reported_pkgs = {}
remove_pattern = re.compile(r'Removing\s(?P<package>.*?)\s\((?P<version>.*?)\)\sfrom\s(?P<target>.*?)...')
for line in salt.utils.itertools.split(output, '\n'):
match = remove_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = ''
return reported_pkgs
def remove(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Remove packages using ``opkg remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
remove_dependencies
Remove package and all dependencies
.. versionadded:: 2019.2.0
auto_remove_deps
Remove packages that were installed automatically to satisfy dependencies
.. versionadded:: 2019.2.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
salt '*' pkg.remove pkgs='["foo", "bar"]' remove_dependencies=True auto_remove_deps=True
'''
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 {}
cmd = ['opkg', 'remove']
_append_noaction_if_testmode(cmd, **kwargs)
if kwargs.get('remove_dependencies', False):
cmd.append('--force-removal-of-dependent-packages')
if kwargs.get('auto_remove_deps', False):
cmd.append('--autoremove')
cmd.extend(targets)
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors = [out['stderr']]
else:
errors = [out['stdout']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if _is_testmode(**kwargs):
reportedPkgs = _parse_reported_packages_from_remove_output(out['stdout'])
new = {k: v for k, v in new.items() if k not in reportedPkgs}
ret = salt.utils.data.compare_dicts(old, new)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def purge(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Package purges are not supported by opkg, this function is identical to
:mod:`pkg.remove <salt.modules.opkg.remove>`.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name, pkgs=pkgs)
def upgrade(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
Upgrades all packages via ``opkg upgrade``
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
errors = []
if salt.utils.data.is_true(refresh):
refresh_db()
old = list_pkgs()
cmd = ['opkg', 'upgrade']
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
errors.append(result)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif state != 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = _set_state(target, 'hold')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif state == 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret['comment'] = ('Package {0} is set not to be held.'
.format(target))
else:
result = _set_state(target, 'ok')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def _get_state(pkg):
'''
View package state from the opkg database
Return the state of pkg
'''
cmd = ['opkg', 'status']
cmd.append(pkg)
out = __salt__['cmd.run'](cmd, python_shell=False)
state_flag = ''
for line in salt.utils.itertools.split(out, '\n'):
if line.startswith('Status'):
_status, _state_want, state_flag, _state_status = line.split()
return state_flag
def _set_state(pkg, state):
'''
Change package state on the opkg database
The state can be any of:
- hold
- noprune
- user
- ok
- installed
- unpacked
This command is commonly used to mark a specific package to be held from
being upgraded, that is, to be kept at a certain version.
Returns a dict containing the package name, and the new and old
versions.
'''
ret = {}
valid_states = ('hold', 'noprune', 'user', 'ok', 'installed', 'unpacked')
if state not in valid_states:
raise SaltInvocationError('Invalid state: {0}'.format(state))
oldstate = _get_state(pkg)
cmd = ['opkg', 'flag']
cmd.append(state)
cmd.append(pkg)
_out = __salt__['cmd.run'](cmd, python_shell=False)
# Missing return value check due to opkg issue 160
ret[pkg] = {'old': oldstate,
'new': state}
return ret
def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
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
cmd = ['opkg', 'list-installed']
ret = {}
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
# This is a continuation of package description
if not line or line[0] == ' ':
continue
# This contains package name, version, and description.
# Extract the first two.
pkg_name, pkg_version = line.split(' - ', 2)[:2]
__salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version)
__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 list_upgrades(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
List all available package upgrades.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
ret = {}
if salt.utils.data.is_true(refresh):
refresh_db()
cmd = ['opkg', 'list-upgradable']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
if 'stdout' in call:
comment += call['stdout']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
name, _oldversion, newversion = line.split(' - ')
ret[name] = newversion
return ret
def _convert_to_standard_attr(attr):
'''
Helper function for _process_info_installed_output()
Converts an opkg attribute name to a standard attribute
name which is used across 'pkg' modules.
'''
ret_attr = ATTR_MAP.get(attr, None)
if ret_attr is None:
# All others convert to lowercase
return attr.lower()
return ret_attr
def _process_info_installed_output(out, filter_attrs):
'''
Helper function for info_installed()
Processes stdout output from a single invocation of
'opkg status'.
'''
ret = {}
name = None
attrs = {}
attr = None
for line in salt.utils.itertools.split(out, '\n'):
if line and line[0] == ' ':
# This is a continuation of the last attr
if filter_attrs is None or attr in filter_attrs:
line = line.strip()
if attrs[attr]:
# If attr is empty, don't add leading newline
attrs[attr] += '\n'
attrs[attr] += line
continue
line = line.strip()
if not line:
# Separator between different packages
if name:
ret[name] = attrs
name = None
attrs = {}
attr = None
continue
key, value = line.split(':', 1)
value = value.lstrip()
attr = _convert_to_standard_attr(key)
if attr == 'name':
name = value
elif filter_attrs is None or attr in filter_attrs:
attrs[attr] = value
if name:
ret[name] = attrs
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
.. versionadded:: 2017.7.0
:param names:
Names of the packages to get information about. If none are specified,
will return information for all installed packages.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
arch, conffiles, conflicts, depends, description, filename, group,
install_date_time_t, md5sum, packager, provides, recommends,
replaces, size, source, suggests, url, version
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed
salt '*' pkg.info_installed attr=version,packager
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> attr=version,packager
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,packager
'''
attr = kwargs.pop('attr', None)
if attr is None:
filter_attrs = None
elif isinstance(attr, six.string_types):
filter_attrs = set(attr.split(','))
else:
filter_attrs = set(attr)
ret = {}
if names:
# Specific list of names of installed packages
for name in names:
cmd = ['opkg', 'status', name]
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
else:
# All installed packages
cmd = ['opkg', 'status']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
return ret
def upgrade_available(name, **kwargs): # pylint: disable=unused-argument
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs): # pylint: disable=unused-argument
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2016.3.4
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0' '0.2.4.1-0'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] if ignore_epoch else six.text_type(x)
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
output = __salt__['cmd.run_stdout'](['opkg', '--version'],
output_loglevel='trace',
python_shell=False)
opkg_version = output.split(' ')[2].strip()
if salt.utils.versions.LooseVersion(opkg_version) >= \
salt.utils.versions.LooseVersion('0.3.4'):
cmd_compare = ['opkg', 'compare-versions']
elif salt.utils.path.which('opkg-compare-versions'):
cmd_compare = ['opkg-compare-versions']
else:
log.warning('Unable to find a compare-versions utility installed. Either upgrade opkg to '
'version > 0.3.4 (preferred) or install the older opkg-compare-versions script.')
return None
for oper, ret in (("<<", -1), ("=", 0), (">>", 1)):
cmd = cmd_compare[:]
cmd.append(_cmd_quote(pkg1))
cmd.append(oper)
cmd.append(_cmd_quote(pkg2))
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
ignore_retcode=True,
python_shell=False)
if retcode == 0:
return ret
return None
def _set_repo_option(repo, option):
'''
Set the option to repo
'''
if not option:
return
opt = option.split('=')
if len(opt) != 2:
return
if opt[0] == 'trusted':
repo['trusted'] = opt[1] == 'yes'
else:
repo[opt[0]] = opt[1]
def _set_repo_options(repo, options):
'''
Set the options to the repo.
'''
delimiters = "[", "]"
pattern = '|'.join(map(re.escape, delimiters))
for option in options:
splitted = re.split(pattern, option)
for opt in splitted:
_set_repo_option(repo, opt)
def _create_repo(line, filename):
'''
Create repo
'''
repo = {}
if line.startswith('#'):
repo['enabled'] = False
line = line[1:]
else:
repo['enabled'] = True
cols = salt.utils.args.shlex_split(line.strip())
repo['compressed'] = not cols[0] in 'src'
repo['name'] = cols[1]
repo['uri'] = cols[2]
repo['file'] = os.path.join(OPKG_CONFDIR, filename)
if len(cols) > 3:
_set_repo_options(repo, cols[3:])
return repo
def _read_repos(conf_file, repos, filename, regex):
'''
Read repos from configuration file
'''
for line in conf_file:
line = salt.utils.stringutils.to_unicode(line)
if not regex.search(line):
continue
repo = _create_repo(line, filename)
# do not store duplicated uri's
if repo['uri'] not in repos:
repos[repo['uri']] = [repo]
def list_repos(**kwargs): # pylint: disable=unused-argument
'''
Lists all repos on ``/etc/opkg/*.conf``
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos = {}
regex = re.compile(REPO_REGEXP)
for filename in os.listdir(OPKG_CONFDIR):
if not filename.endswith(".conf"):
continue
with salt.utils.files.fopen(os.path.join(OPKG_CONFDIR, filename)) as conf_file:
_read_repos(conf_file, repos, filename, regex)
return repos
def get_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Display a repo from the ``/etc/opkg/*.conf``
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo repo
'''
repos = list_repos()
if repos:
for source in six.itervalues(repos):
for sub in source:
if sub['name'] == repo:
return sub
return {}
def _del_repo_from_file(repo, filepath):
'''
Remove a repo from filepath
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
regex = re.compile(REPO_REGEXP)
for line in fhandle:
line = salt.utils.stringutils.to_unicode(line)
if regex.search(line):
if line.startswith('#'):
line = line[1:]
cols = salt.utils.args.shlex_split(line.strip())
if repo != cols[1]:
output.append(salt.utils.stringutils.to_str(line))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def _set_trusted_option_if_needed(repostr, trusted):
'''
Set trusted option to repo if needed
'''
if trusted is True:
repostr += ' [trusted=yes]'
elif trusted is False:
repostr += ' [trusted=no]'
return repostr
def _mod_repo_in_file(repo, repostr, filepath):
'''
Replace a repo entry in filepath with repostr
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
for line in fhandle:
cols = salt.utils.args.shlex_split(
salt.utils.stringutils.to_unicode(line).strip()
)
if repo not in cols:
output.append(line)
else:
output.append(salt.utils.stringutils.to_str(repostr + '\n'))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def del_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Delete a repo from ``/etc/opkg/*.conf``
If the file does not contain any other repo configuration, the file itself
will be deleted.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo repo
'''
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
repos = list_repos()
if repos:
deleted_from = dict()
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
deleted_from[source['file']] = 0
_del_repo_from_file(repo, source['file'])
if deleted_from:
ret = ''
for repository in repos:
source = repos[repository][0]
if source['file'] in deleted_from:
deleted_from[source['file']] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 1 and os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.\n')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
if refresh:
refresh_db()
return ret
return "Repo {0} doesn't exist in the opkg repo lists".format(repo)
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as uri is defined.
The following options are available to modify a repo definition:
repo
alias by which opkg refers to the repo.
uri
the URI to the repo.
compressed
defines (True or False) if the index file is compressed
enabled
enable or disable (True or False) repository
but do not remove if disabled.
refresh
enable or disable (True or False) auto-refresh of the repositories
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo repo uri=http://new/uri
salt '*' pkg.mod_repo repo enabled=False
'''
repos = list_repos()
found = False
uri = ''
if 'uri' in kwargs:
uri = kwargs['uri']
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
found = True
repostr = ''
if 'enabled' in kwargs and not kwargs['enabled']:
repostr += '# '
if 'compressed' in kwargs:
repostr += 'src/gz ' if kwargs['compressed'] else 'src'
else:
repostr += 'src/gz' if source['compressed'] else 'src'
repo_alias = kwargs['alias'] if 'alias' in kwargs else repo
if ' ' in repo_alias:
repostr += ' "{0}"'.format(repo_alias)
else:
repostr += ' {0}'.format(repo_alias)
repostr += ' {0}'.format(kwargs['uri'] if 'uri' in kwargs else source['uri'])
trusted = kwargs.get('trusted')
repostr = _set_trusted_option_if_needed(repostr, trusted) if trusted is not None else \
_set_trusted_option_if_needed(repostr, source.get('trusted'))
_mod_repo_in_file(repo, repostr, source['file'])
elif uri and source['uri'] == uri:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(uri, source['name']))
if not found:
# Need to add a new repo
if 'uri' not in kwargs:
raise CommandExecutionError(
'Repository \'{0}\' not found and no URI passed to create one.'.format(repo))
properties = {'uri': kwargs['uri']}
# If compressed is not defined, assume True
properties['compressed'] = kwargs['compressed'] if 'compressed' in kwargs else True
# If enabled is not defined, assume True
properties['enabled'] = kwargs['enabled'] if 'enabled' in kwargs else True
properties['trusted'] = kwargs.get('trusted')
_add_new_repo(repo, properties)
if 'refresh' in kwargs:
refresh_db()
def file_list(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
output = file_dict(*packages)
files = []
for package in list(output['packages'].values()):
files.extend(package)
return {'errors': output['errors'], 'files': files}
def file_dict(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
errors = []
ret = {}
cmd_files = ['opkg', 'files']
if not packages:
packages = list(list_pkgs().keys())
for package in packages:
files = []
cmd = cmd_files[:]
cmd.append(package)
out = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
for line in out['stdout'].splitlines():
if line.startswith('/'):
files.append(line)
elif line.startswith(' * '):
errors.append(line[3:])
break
else:
continue
if files:
ret[package] = files
return {'errors': errors, 'packages': ret}
def owner(*paths, **kwargs): # pylint: disable=unused-argument
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.opkg.version`, if a single
path is passed, a string will be returned, and if multiple paths are passed,
a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
cmd_search = ['opkg', 'search']
for path in paths:
cmd = cmd_search[:]
cmd.append(path)
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
if output:
ret[path] = output.split(' - ')[0].strip()
else:
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def version_clean(version):
'''
Clean the version string removing extra data.
There's nothing do to here for nipkg.py, therefore it will always
return the given version.
'''
return version
def check_extra_requirements(pkgname, pkgver):
'''
Check if the installed package already has the given requirements.
There's nothing do to here for nipkg.py, therefore it will always
return True.
'''
return True
|
saltstack/salt
|
salt/modules/opkg.py
|
_mod_repo_in_file
|
python
|
def _mod_repo_in_file(repo, repostr, filepath):
'''
Replace a repo entry in filepath with repostr
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
for line in fhandle:
cols = salt.utils.args.shlex_split(
salt.utils.stringutils.to_unicode(line).strip()
)
if repo not in cols:
output.append(line)
else:
output.append(salt.utils.stringutils.to_str(repostr + '\n'))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
|
Replace a repo entry in filepath with repostr
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/opkg.py#L1398-L1413
| null |
# -*- coding: utf-8 -*-
'''
Support for Opkg
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
.. versionadded: 2016.3.0
.. note::
For version comparison support on opkg < 0.3.4, the ``opkg-utils`` package
must be installed.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import os
import re
import logging
import errno
# Import salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.itertools
import salt.utils.path
import salt.utils.pkg
import salt.utils.stringutils
import salt.utils.versions
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import shlex_quote as _cmd_quote # pylint: disable=import-error
from salt.ext.six.moves import map # pylint: disable=import-error,redefined-builtin
REPO_REGEXP = r'^#?\s*(src|src/gz)\s+([^\s<>]+|"[^<>]+")\s+[^\s<>]+'
OPKG_CONFDIR = '/etc/opkg'
ATTR_MAP = {
'Architecture': 'arch',
'Homepage': 'url',
'Installed-Time': 'install_date_time_t',
'Maintainer': 'packager',
'Package': 'name',
'Section': 'group'
}
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
NILRT_RESTARTCHECK_STATE_PATH = '/var/lib/salt/restartcheck_state'
def _update_nilrt_restart_state():
'''
NILRT systems determine whether to reboot after various package operations
including but not limited to kernel module installs/removals by checking
specific file md5sums & timestamps. These files are touched/modified by
the post-install/post-remove functions of their respective packages.
The opkg module uses this function to store/update those file timestamps
and checksums to be used later by the restartcheck module.
'''
__salt__['cmd.shell']('stat -c %Y /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.timestamp'
.format(NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.md5sum'
.format(NILRT_RESTARTCHECK_STATE_PATH))
# We can't assume nisysapi.ini always exists like modules.dep
nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'
if os.path.exists(nisysapi_path):
__salt__['cmd.shell']('stat -c %Y {0} >{1}/nisysapi.ini.timestamp'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0} >{1}/nisysapi.ini.md5sum'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
# Expert plugin files get added to a conf.d dir, so keep track of the total
# no. of files, their timestamps and content hashes
nisysapi_conf_d_path = "/usr/lib/{0}/nisysapi/conf.d/experts/".format(
'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'
)
if os.path.exists(nisysapi_conf_d_path):
with salt.utils.files.fopen('{0}/sysapi.conf.d.count'.format(
NILRT_RESTARTCHECK_STATE_PATH), 'w') as fcount:
fcount.write(str(len(os.listdir(nisysapi_conf_d_path))))
for fexpert in os.listdir(nisysapi_conf_d_path):
__salt__['cmd.shell']('stat -c %Y {0}/{1} >{2}/{1}.timestamp'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0}/{1} >{2}/{1}.md5sum'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
def _get_restartcheck_result(errors):
'''
Return restartcheck result and append errors (if any) to ``errors``
'''
rs_result = __salt__['restartcheck.restartcheck'](verbose=False)
if isinstance(rs_result, dict) and 'comment' in rs_result:
errors.append(rs_result['comment'])
return rs_result
def _process_restartcheck_result(rs_result, **kwargs):
'''
Check restartcheck output to see if system/service restarts were requested
and take appropriate action.
'''
if 'No packages seem to need to be restarted' in rs_result:
return
reboot_required = False
for rstr in rs_result:
if 'System restart required' in rstr:
_update_nilrt_restart_state()
__salt__['system.set_reboot_required_witnessed']()
reboot_required = True
if kwargs.get('always_restart_services', True) or not reboot_required:
for rstr in rs_result:
if 'System restart required' not in rstr:
service = os.path.join('/etc/init.d', rstr)
if os.path.exists(service):
__salt__['cmd.run']([service, 'restart'])
def __virtual__():
'''
Confirm this module is on a nilrt based system
'''
if __grains__.get('os_family') == 'NILinuxRT':
try:
os.makedirs(NILRT_RESTARTCHECK_STATE_PATH)
except OSError as exc:
if exc.errno != errno.EEXIST:
return False, 'Error creating {0} (-{1}): {2}'.format(
NILRT_RESTARTCHECK_STATE_PATH,
exc.errno,
exc.strerror)
# populate state dir if empty
if not os.listdir(NILRT_RESTARTCHECK_STATE_PATH):
_update_nilrt_restart_state()
return __virtualname__
if os.path.isdir(OPKG_CONFDIR):
return __virtualname__
return False, "Module opkg only works on OpenEmbedded based systems"
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
if not names:
return ''
ret = {}
for name in names:
ret[name] = ''
# Refresh before looking for the latest version available
if refresh:
refresh_db()
cmd = ['opkg', 'list-upgradable']
out = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
try:
name, _oldversion, newversion = line.split(' - ')
if name in names:
ret[name] = newversion
except ValueError:
pass
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = latest_version
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(failhard=False, **kwargs): # pylint: disable=unused-argument
'''
Updates the opkg database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
failhard
If False, return results of failed lines as ``False`` for the package
database that encountered the error.
If True, raise an error with a list of the package databases that
encountered errors.
.. versionadded:: 2018.3.0
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
error_repos = []
cmd = ['opkg', 'update']
# opkg returns a non-zero retcode when there is a failure to refresh
# from one or more repos. Due to this, ignore the retcode.
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True,
redirect_stderr=True)
out = call['stdout']
prev_line = ''
for line in salt.utils.itertools.split(out, '\n'):
if 'Inflating' in line:
key = line.strip().split()[1][:-1]
ret[key] = True
elif 'Updated source' in line:
# Use the previous line.
key = prev_line.strip().split()[1][:-1]
ret[key] = True
elif 'Failed to download' in line:
key = line.strip().split()[5].split(',')[0]
ret[key] = False
error_repos.append(key)
prev_line = line
if failhard and error_repos:
raise CommandExecutionError(
'Error getting repos: {0}'.format(', '.join(error_repos))
)
# On a non-zero exit code where no failed repos were found, raise an
# exception because this appears to be a different kind of error.
if call['retcode'] != 0 and not error_repos:
raise CommandExecutionError(out)
return ret
def _is_testmode(**kwargs):
'''
Returns whether a test mode (noaction) operation was requested.
'''
return bool(kwargs.get('test') or __opts__.get('test'))
def _append_noaction_if_testmode(cmd, **kwargs):
'''
Adds the --noaction flag to the command if it's running in the test mode.
'''
if _is_testmode(**kwargs):
cmd.append('--noaction')
def _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall):
'''
Builds a list of install commands to be executed in sequence in order to process
each of the to_install, to_downgrade, and to_reinstall lists.
'''
cmds = []
if to_install:
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(to_install)
cmds.append(cmd)
if to_downgrade:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-downgrade')
cmd.extend(to_downgrade)
cmds.append(cmd)
if to_reinstall:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-reinstall')
cmd.extend(to_reinstall)
cmds.append(cmd)
return cmds
def _parse_reported_packages_from_install_output(output):
'''
Parses the output of "opkg install" to determine what packages would have been
installed by an operation run with the --noaction flag.
We are looking for lines like:
Installing <package> (<version>) on <target>
or
Upgrading <package> from <oldVersion> to <version> on root
'''
reported_pkgs = {}
install_pattern = re.compile(r'Installing\s(?P<package>.*?)\s\((?P<version>.*?)\)\son\s(?P<target>.*?)')
upgrade_pattern = re.compile(r'Upgrading\s(?P<package>.*?)\sfrom\s(?P<oldVersion>.*?)\sto\s(?P<version>.*?)\son\s(?P<target>.*?)')
for line in salt.utils.itertools.split(output, '\n'):
match = install_pattern.match(line)
if match is None:
match = upgrade_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = match.group('version')
return reported_pkgs
def _execute_install_command(cmd, parse_output, errors, parsed_packages):
'''
Executes a command for the install operation.
If the command fails, its error output will be appended to the errors list.
If the command succeeds and parse_output is true, updated packages will be appended
to the parsed_packages dictionary.
'''
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors.append(out['stderr'])
else:
errors.append(out['stdout'])
elif parse_output:
parsed_packages.update(_parse_reported_packages_from_install_output(out['stdout']))
def install(name=None,
refresh=False,
pkgs=None,
sources=None,
reinstall=False,
**kwargs):
'''
Install the passed package, add refresh=True to update the opkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionadded:: 2017.7.0
reinstall : False
Specifying reinstall=True will use ``opkg install --force-reinstall``
rather than simply ``opkg install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``opkg
install --force-reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2017.7.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of IPK packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
install_recommends
Whether to install the packages marked as recommended. Default is True.
only_upgrade
Only upgrade the packages (disallow downgrades), if they are already
installed. Default is False.
.. versionadded:: 2017.7.0
always_restart_services
Whether to restart services even if a reboot is required. Default is True.
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
refreshdb = salt.utils.data.is_true(refresh)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
cmd_prefix = ['opkg', 'install']
to_install = []
to_reinstall = []
to_downgrade = []
_append_noaction_if_testmode(cmd_prefix, **kwargs)
if not pkg_params:
return {}
elif pkg_type == 'file':
if reinstall:
cmd_prefix.append('--force-reinstall')
if not kwargs.get('only_upgrade', False):
cmd_prefix.append('--force-downgrade')
to_install.extend(pkg_params)
elif pkg_type == 'repository':
if not kwargs.get('install_recommends', True):
cmd_prefix.append('--no-install-recommends')
for pkgname, pkgversion in six.iteritems(pkg_params):
if (name and pkgs is None and kwargs.get('version') and
len(pkg_params) == 1):
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
version_num = pkgversion
if version_num is None:
# Don't allow downgrades if the version
# number is not specified.
if reinstall and pkgname in old:
to_reinstall.append(pkgname)
else:
to_install.append(pkgname)
else:
pkgstr = '{0}={1}'.format(pkgname, version_num)
cver = old.get(pkgname, '')
if reinstall and cver and salt.utils.versions.compare(
ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall.append(pkgstr)
elif not cver or salt.utils.versions.compare(
ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
to_install.append(pkgstr)
else:
if not kwargs.get('only_upgrade', False):
to_downgrade.append(pkgstr)
else:
# This should cause the command to fail.
to_install.append(pkgstr)
cmds = _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall)
if not cmds:
return {}
if refreshdb:
refresh_db()
errors = []
is_testmode = _is_testmode(**kwargs)
test_packages = {}
for cmd in cmds:
_execute_install_command(cmd, is_testmode, errors, test_packages)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if is_testmode:
new = copy.deepcopy(new)
new.update(test_packages)
ret = salt.utils.data.compare_dicts(old, new)
if pkg_type == 'file' and reinstall:
# For file-based packages, prepare 'to_reinstall' to have a list
# of all the package names that may have been reinstalled.
# This way, we could include reinstalled packages in 'ret'.
for pkgfile in to_install:
# Convert from file name to package name.
cmd = ['opkg', 'info', pkgfile]
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] == 0:
# Just need the package name.
pkginfo_dict = _process_info_installed_output(
out['stdout'], []
)
if pkginfo_dict:
to_reinstall.append(list(pkginfo_dict.keys())[0])
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def _parse_reported_packages_from_remove_output(output):
'''
Parses the output of "opkg remove" to determine what packages would have been
removed by an operation run with the --noaction flag.
We are looking for lines like
Removing <package> (<version>) from <Target>...
'''
reported_pkgs = {}
remove_pattern = re.compile(r'Removing\s(?P<package>.*?)\s\((?P<version>.*?)\)\sfrom\s(?P<target>.*?)...')
for line in salt.utils.itertools.split(output, '\n'):
match = remove_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = ''
return reported_pkgs
def remove(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Remove packages using ``opkg remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
remove_dependencies
Remove package and all dependencies
.. versionadded:: 2019.2.0
auto_remove_deps
Remove packages that were installed automatically to satisfy dependencies
.. versionadded:: 2019.2.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
salt '*' pkg.remove pkgs='["foo", "bar"]' remove_dependencies=True auto_remove_deps=True
'''
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 {}
cmd = ['opkg', 'remove']
_append_noaction_if_testmode(cmd, **kwargs)
if kwargs.get('remove_dependencies', False):
cmd.append('--force-removal-of-dependent-packages')
if kwargs.get('auto_remove_deps', False):
cmd.append('--autoremove')
cmd.extend(targets)
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors = [out['stderr']]
else:
errors = [out['stdout']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if _is_testmode(**kwargs):
reportedPkgs = _parse_reported_packages_from_remove_output(out['stdout'])
new = {k: v for k, v in new.items() if k not in reportedPkgs}
ret = salt.utils.data.compare_dicts(old, new)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def purge(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Package purges are not supported by opkg, this function is identical to
:mod:`pkg.remove <salt.modules.opkg.remove>`.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name, pkgs=pkgs)
def upgrade(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
Upgrades all packages via ``opkg upgrade``
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
errors = []
if salt.utils.data.is_true(refresh):
refresh_db()
old = list_pkgs()
cmd = ['opkg', 'upgrade']
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
errors.append(result)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif state != 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = _set_state(target, 'hold')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif state == 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret['comment'] = ('Package {0} is set not to be held.'
.format(target))
else:
result = _set_state(target, 'ok')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def _get_state(pkg):
'''
View package state from the opkg database
Return the state of pkg
'''
cmd = ['opkg', 'status']
cmd.append(pkg)
out = __salt__['cmd.run'](cmd, python_shell=False)
state_flag = ''
for line in salt.utils.itertools.split(out, '\n'):
if line.startswith('Status'):
_status, _state_want, state_flag, _state_status = line.split()
return state_flag
def _set_state(pkg, state):
'''
Change package state on the opkg database
The state can be any of:
- hold
- noprune
- user
- ok
- installed
- unpacked
This command is commonly used to mark a specific package to be held from
being upgraded, that is, to be kept at a certain version.
Returns a dict containing the package name, and the new and old
versions.
'''
ret = {}
valid_states = ('hold', 'noprune', 'user', 'ok', 'installed', 'unpacked')
if state not in valid_states:
raise SaltInvocationError('Invalid state: {0}'.format(state))
oldstate = _get_state(pkg)
cmd = ['opkg', 'flag']
cmd.append(state)
cmd.append(pkg)
_out = __salt__['cmd.run'](cmd, python_shell=False)
# Missing return value check due to opkg issue 160
ret[pkg] = {'old': oldstate,
'new': state}
return ret
def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
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
cmd = ['opkg', 'list-installed']
ret = {}
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
# This is a continuation of package description
if not line or line[0] == ' ':
continue
# This contains package name, version, and description.
# Extract the first two.
pkg_name, pkg_version = line.split(' - ', 2)[:2]
__salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version)
__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 list_upgrades(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
List all available package upgrades.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
ret = {}
if salt.utils.data.is_true(refresh):
refresh_db()
cmd = ['opkg', 'list-upgradable']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
if 'stdout' in call:
comment += call['stdout']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
name, _oldversion, newversion = line.split(' - ')
ret[name] = newversion
return ret
def _convert_to_standard_attr(attr):
'''
Helper function for _process_info_installed_output()
Converts an opkg attribute name to a standard attribute
name which is used across 'pkg' modules.
'''
ret_attr = ATTR_MAP.get(attr, None)
if ret_attr is None:
# All others convert to lowercase
return attr.lower()
return ret_attr
def _process_info_installed_output(out, filter_attrs):
'''
Helper function for info_installed()
Processes stdout output from a single invocation of
'opkg status'.
'''
ret = {}
name = None
attrs = {}
attr = None
for line in salt.utils.itertools.split(out, '\n'):
if line and line[0] == ' ':
# This is a continuation of the last attr
if filter_attrs is None or attr in filter_attrs:
line = line.strip()
if attrs[attr]:
# If attr is empty, don't add leading newline
attrs[attr] += '\n'
attrs[attr] += line
continue
line = line.strip()
if not line:
# Separator between different packages
if name:
ret[name] = attrs
name = None
attrs = {}
attr = None
continue
key, value = line.split(':', 1)
value = value.lstrip()
attr = _convert_to_standard_attr(key)
if attr == 'name':
name = value
elif filter_attrs is None or attr in filter_attrs:
attrs[attr] = value
if name:
ret[name] = attrs
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
.. versionadded:: 2017.7.0
:param names:
Names of the packages to get information about. If none are specified,
will return information for all installed packages.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
arch, conffiles, conflicts, depends, description, filename, group,
install_date_time_t, md5sum, packager, provides, recommends,
replaces, size, source, suggests, url, version
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed
salt '*' pkg.info_installed attr=version,packager
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> attr=version,packager
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,packager
'''
attr = kwargs.pop('attr', None)
if attr is None:
filter_attrs = None
elif isinstance(attr, six.string_types):
filter_attrs = set(attr.split(','))
else:
filter_attrs = set(attr)
ret = {}
if names:
# Specific list of names of installed packages
for name in names:
cmd = ['opkg', 'status', name]
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
else:
# All installed packages
cmd = ['opkg', 'status']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
return ret
def upgrade_available(name, **kwargs): # pylint: disable=unused-argument
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs): # pylint: disable=unused-argument
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2016.3.4
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0' '0.2.4.1-0'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] if ignore_epoch else six.text_type(x)
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
output = __salt__['cmd.run_stdout'](['opkg', '--version'],
output_loglevel='trace',
python_shell=False)
opkg_version = output.split(' ')[2].strip()
if salt.utils.versions.LooseVersion(opkg_version) >= \
salt.utils.versions.LooseVersion('0.3.4'):
cmd_compare = ['opkg', 'compare-versions']
elif salt.utils.path.which('opkg-compare-versions'):
cmd_compare = ['opkg-compare-versions']
else:
log.warning('Unable to find a compare-versions utility installed. Either upgrade opkg to '
'version > 0.3.4 (preferred) or install the older opkg-compare-versions script.')
return None
for oper, ret in (("<<", -1), ("=", 0), (">>", 1)):
cmd = cmd_compare[:]
cmd.append(_cmd_quote(pkg1))
cmd.append(oper)
cmd.append(_cmd_quote(pkg2))
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
ignore_retcode=True,
python_shell=False)
if retcode == 0:
return ret
return None
def _set_repo_option(repo, option):
'''
Set the option to repo
'''
if not option:
return
opt = option.split('=')
if len(opt) != 2:
return
if opt[0] == 'trusted':
repo['trusted'] = opt[1] == 'yes'
else:
repo[opt[0]] = opt[1]
def _set_repo_options(repo, options):
'''
Set the options to the repo.
'''
delimiters = "[", "]"
pattern = '|'.join(map(re.escape, delimiters))
for option in options:
splitted = re.split(pattern, option)
for opt in splitted:
_set_repo_option(repo, opt)
def _create_repo(line, filename):
'''
Create repo
'''
repo = {}
if line.startswith('#'):
repo['enabled'] = False
line = line[1:]
else:
repo['enabled'] = True
cols = salt.utils.args.shlex_split(line.strip())
repo['compressed'] = not cols[0] in 'src'
repo['name'] = cols[1]
repo['uri'] = cols[2]
repo['file'] = os.path.join(OPKG_CONFDIR, filename)
if len(cols) > 3:
_set_repo_options(repo, cols[3:])
return repo
def _read_repos(conf_file, repos, filename, regex):
'''
Read repos from configuration file
'''
for line in conf_file:
line = salt.utils.stringutils.to_unicode(line)
if not regex.search(line):
continue
repo = _create_repo(line, filename)
# do not store duplicated uri's
if repo['uri'] not in repos:
repos[repo['uri']] = [repo]
def list_repos(**kwargs): # pylint: disable=unused-argument
'''
Lists all repos on ``/etc/opkg/*.conf``
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos = {}
regex = re.compile(REPO_REGEXP)
for filename in os.listdir(OPKG_CONFDIR):
if not filename.endswith(".conf"):
continue
with salt.utils.files.fopen(os.path.join(OPKG_CONFDIR, filename)) as conf_file:
_read_repos(conf_file, repos, filename, regex)
return repos
def get_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Display a repo from the ``/etc/opkg/*.conf``
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo repo
'''
repos = list_repos()
if repos:
for source in six.itervalues(repos):
for sub in source:
if sub['name'] == repo:
return sub
return {}
def _del_repo_from_file(repo, filepath):
'''
Remove a repo from filepath
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
regex = re.compile(REPO_REGEXP)
for line in fhandle:
line = salt.utils.stringutils.to_unicode(line)
if regex.search(line):
if line.startswith('#'):
line = line[1:]
cols = salt.utils.args.shlex_split(line.strip())
if repo != cols[1]:
output.append(salt.utils.stringutils.to_str(line))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def _set_trusted_option_if_needed(repostr, trusted):
'''
Set trusted option to repo if needed
'''
if trusted is True:
repostr += ' [trusted=yes]'
elif trusted is False:
repostr += ' [trusted=no]'
return repostr
def _add_new_repo(repo, properties):
'''
Add a new repo entry
'''
repostr = '# ' if not properties.get('enabled') else ''
repostr += 'src/gz ' if properties.get('compressed') else 'src '
if ' ' in repo:
repostr += '"' + repo + '" '
else:
repostr += repo + ' '
repostr += properties.get('uri')
repostr = _set_trusted_option_if_needed(repostr, properties.get('trusted'))
repostr += '\n'
conffile = os.path.join(OPKG_CONFDIR, repo + '.conf')
with salt.utils.files.fopen(conffile, 'a') as fhandle:
fhandle.write(salt.utils.stringutils.to_str(repostr))
def del_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Delete a repo from ``/etc/opkg/*.conf``
If the file does not contain any other repo configuration, the file itself
will be deleted.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo repo
'''
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
repos = list_repos()
if repos:
deleted_from = dict()
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
deleted_from[source['file']] = 0
_del_repo_from_file(repo, source['file'])
if deleted_from:
ret = ''
for repository in repos:
source = repos[repository][0]
if source['file'] in deleted_from:
deleted_from[source['file']] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 1 and os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.\n')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
if refresh:
refresh_db()
return ret
return "Repo {0} doesn't exist in the opkg repo lists".format(repo)
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as uri is defined.
The following options are available to modify a repo definition:
repo
alias by which opkg refers to the repo.
uri
the URI to the repo.
compressed
defines (True or False) if the index file is compressed
enabled
enable or disable (True or False) repository
but do not remove if disabled.
refresh
enable or disable (True or False) auto-refresh of the repositories
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo repo uri=http://new/uri
salt '*' pkg.mod_repo repo enabled=False
'''
repos = list_repos()
found = False
uri = ''
if 'uri' in kwargs:
uri = kwargs['uri']
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
found = True
repostr = ''
if 'enabled' in kwargs and not kwargs['enabled']:
repostr += '# '
if 'compressed' in kwargs:
repostr += 'src/gz ' if kwargs['compressed'] else 'src'
else:
repostr += 'src/gz' if source['compressed'] else 'src'
repo_alias = kwargs['alias'] if 'alias' in kwargs else repo
if ' ' in repo_alias:
repostr += ' "{0}"'.format(repo_alias)
else:
repostr += ' {0}'.format(repo_alias)
repostr += ' {0}'.format(kwargs['uri'] if 'uri' in kwargs else source['uri'])
trusted = kwargs.get('trusted')
repostr = _set_trusted_option_if_needed(repostr, trusted) if trusted is not None else \
_set_trusted_option_if_needed(repostr, source.get('trusted'))
_mod_repo_in_file(repo, repostr, source['file'])
elif uri and source['uri'] == uri:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(uri, source['name']))
if not found:
# Need to add a new repo
if 'uri' not in kwargs:
raise CommandExecutionError(
'Repository \'{0}\' not found and no URI passed to create one.'.format(repo))
properties = {'uri': kwargs['uri']}
# If compressed is not defined, assume True
properties['compressed'] = kwargs['compressed'] if 'compressed' in kwargs else True
# If enabled is not defined, assume True
properties['enabled'] = kwargs['enabled'] if 'enabled' in kwargs else True
properties['trusted'] = kwargs.get('trusted')
_add_new_repo(repo, properties)
if 'refresh' in kwargs:
refresh_db()
def file_list(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
output = file_dict(*packages)
files = []
for package in list(output['packages'].values()):
files.extend(package)
return {'errors': output['errors'], 'files': files}
def file_dict(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
errors = []
ret = {}
cmd_files = ['opkg', 'files']
if not packages:
packages = list(list_pkgs().keys())
for package in packages:
files = []
cmd = cmd_files[:]
cmd.append(package)
out = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
for line in out['stdout'].splitlines():
if line.startswith('/'):
files.append(line)
elif line.startswith(' * '):
errors.append(line[3:])
break
else:
continue
if files:
ret[package] = files
return {'errors': errors, 'packages': ret}
def owner(*paths, **kwargs): # pylint: disable=unused-argument
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.opkg.version`, if a single
path is passed, a string will be returned, and if multiple paths are passed,
a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
cmd_search = ['opkg', 'search']
for path in paths:
cmd = cmd_search[:]
cmd.append(path)
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
if output:
ret[path] = output.split(' - ')[0].strip()
else:
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def version_clean(version):
'''
Clean the version string removing extra data.
There's nothing do to here for nipkg.py, therefore it will always
return the given version.
'''
return version
def check_extra_requirements(pkgname, pkgver):
'''
Check if the installed package already has the given requirements.
There's nothing do to here for nipkg.py, therefore it will always
return True.
'''
return True
|
saltstack/salt
|
salt/modules/opkg.py
|
del_repo
|
python
|
def del_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Delete a repo from ``/etc/opkg/*.conf``
If the file does not contain any other repo configuration, the file itself
will be deleted.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo repo
'''
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
repos = list_repos()
if repos:
deleted_from = dict()
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
deleted_from[source['file']] = 0
_del_repo_from_file(repo, source['file'])
if deleted_from:
ret = ''
for repository in repos:
source = repos[repository][0]
if source['file'] in deleted_from:
deleted_from[source['file']] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 1 and os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.\n')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
if refresh:
refresh_db()
return ret
return "Repo {0} doesn't exist in the opkg repo lists".format(repo)
|
Delete a repo from ``/etc/opkg/*.conf``
If the file does not contain any other repo configuration, the file itself
will be deleted.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo repo
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/opkg.py#L1416-L1459
|
[
"def iteritems(d, **kw):\n return d.iteritems(**kw)\n",
"def is_true(value=None):\n '''\n Returns a boolean value representing the \"truth\" of the value passed. The\n rules for what is a \"True\" value are:\n\n 1. Integer/float values greater than 0\n 2. The string values \"True\" and \"true\"\n 3. Any object for which bool(obj) returns True\n '''\n # First, try int/float conversion\n try:\n value = int(value)\n except (ValueError, TypeError):\n pass\n try:\n value = float(value)\n except (ValueError, TypeError):\n pass\n\n # Now check for truthiness\n if isinstance(value, (six.integer_types, float)):\n return value > 0\n elif isinstance(value, six.string_types):\n return six.text_type(value).lower() == 'true'\n else:\n return bool(value)\n",
"def refresh_db(failhard=False, **kwargs): # pylint: disable=unused-argument\n '''\n Updates the opkg database to latest packages based upon repositories\n\n Returns a dict, with the keys being package databases and the values being\n the result of the update attempt. Values can be one of the following:\n\n - ``True``: Database updated successfully\n - ``False``: Problem updating database\n\n failhard\n If False, return results of failed lines as ``False`` for the package\n database that encountered the error.\n If True, raise an error with a list of the package databases that\n encountered errors.\n\n .. versionadded:: 2018.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.refresh_db\n '''\n # Remove rtag file to keep multiple refreshes from happening in pkg states\n salt.utils.pkg.clear_rtag(__opts__)\n ret = {}\n error_repos = []\n cmd = ['opkg', 'update']\n # opkg returns a non-zero retcode when there is a failure to refresh\n # from one or more repos. Due to this, ignore the retcode.\n call = __salt__['cmd.run_all'](cmd,\n output_loglevel='trace',\n python_shell=False,\n ignore_retcode=True,\n redirect_stderr=True)\n\n out = call['stdout']\n prev_line = ''\n for line in salt.utils.itertools.split(out, '\\n'):\n if 'Inflating' in line:\n key = line.strip().split()[1][:-1]\n ret[key] = True\n elif 'Updated source' in line:\n # Use the previous line.\n key = prev_line.strip().split()[1][:-1]\n ret[key] = True\n elif 'Failed to download' in line:\n key = line.strip().split()[5].split(',')[0]\n ret[key] = False\n error_repos.append(key)\n prev_line = line\n\n if failhard and error_repos:\n raise CommandExecutionError(\n 'Error getting repos: {0}'.format(', '.join(error_repos))\n )\n\n # On a non-zero exit code where no failed repos were found, raise an\n # exception because this appears to be a different kind of error.\n if call['retcode'] != 0 and not error_repos:\n raise CommandExecutionError(out)\n\n return ret\n",
"def list_repos(**kwargs): # pylint: disable=unused-argument\n '''\n Lists all repos on ``/etc/opkg/*.conf``\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.list_repos\n '''\n repos = {}\n regex = re.compile(REPO_REGEXP)\n for filename in os.listdir(OPKG_CONFDIR):\n if not filename.endswith(\".conf\"):\n continue\n with salt.utils.files.fopen(os.path.join(OPKG_CONFDIR, filename)) as conf_file:\n _read_repos(conf_file, repos, filename, regex)\n return repos\n",
"def _del_repo_from_file(repo, filepath):\n '''\n Remove a repo from filepath\n '''\n with salt.utils.files.fopen(filepath) as fhandle:\n output = []\n regex = re.compile(REPO_REGEXP)\n for line in fhandle:\n line = salt.utils.stringutils.to_unicode(line)\n if regex.search(line):\n if line.startswith('#'):\n line = line[1:]\n cols = salt.utils.args.shlex_split(line.strip())\n if repo != cols[1]:\n output.append(salt.utils.stringutils.to_str(line))\n with salt.utils.files.fopen(filepath, 'w') as fhandle:\n fhandle.writelines(output)\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Opkg
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
.. versionadded: 2016.3.0
.. note::
For version comparison support on opkg < 0.3.4, the ``opkg-utils`` package
must be installed.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import os
import re
import logging
import errno
# Import salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.itertools
import salt.utils.path
import salt.utils.pkg
import salt.utils.stringutils
import salt.utils.versions
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import shlex_quote as _cmd_quote # pylint: disable=import-error
from salt.ext.six.moves import map # pylint: disable=import-error,redefined-builtin
REPO_REGEXP = r'^#?\s*(src|src/gz)\s+([^\s<>]+|"[^<>]+")\s+[^\s<>]+'
OPKG_CONFDIR = '/etc/opkg'
ATTR_MAP = {
'Architecture': 'arch',
'Homepage': 'url',
'Installed-Time': 'install_date_time_t',
'Maintainer': 'packager',
'Package': 'name',
'Section': 'group'
}
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
NILRT_RESTARTCHECK_STATE_PATH = '/var/lib/salt/restartcheck_state'
def _update_nilrt_restart_state():
'''
NILRT systems determine whether to reboot after various package operations
including but not limited to kernel module installs/removals by checking
specific file md5sums & timestamps. These files are touched/modified by
the post-install/post-remove functions of their respective packages.
The opkg module uses this function to store/update those file timestamps
and checksums to be used later by the restartcheck module.
'''
__salt__['cmd.shell']('stat -c %Y /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.timestamp'
.format(NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.md5sum'
.format(NILRT_RESTARTCHECK_STATE_PATH))
# We can't assume nisysapi.ini always exists like modules.dep
nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'
if os.path.exists(nisysapi_path):
__salt__['cmd.shell']('stat -c %Y {0} >{1}/nisysapi.ini.timestamp'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0} >{1}/nisysapi.ini.md5sum'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
# Expert plugin files get added to a conf.d dir, so keep track of the total
# no. of files, their timestamps and content hashes
nisysapi_conf_d_path = "/usr/lib/{0}/nisysapi/conf.d/experts/".format(
'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'
)
if os.path.exists(nisysapi_conf_d_path):
with salt.utils.files.fopen('{0}/sysapi.conf.d.count'.format(
NILRT_RESTARTCHECK_STATE_PATH), 'w') as fcount:
fcount.write(str(len(os.listdir(nisysapi_conf_d_path))))
for fexpert in os.listdir(nisysapi_conf_d_path):
__salt__['cmd.shell']('stat -c %Y {0}/{1} >{2}/{1}.timestamp'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0}/{1} >{2}/{1}.md5sum'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
def _get_restartcheck_result(errors):
'''
Return restartcheck result and append errors (if any) to ``errors``
'''
rs_result = __salt__['restartcheck.restartcheck'](verbose=False)
if isinstance(rs_result, dict) and 'comment' in rs_result:
errors.append(rs_result['comment'])
return rs_result
def _process_restartcheck_result(rs_result, **kwargs):
'''
Check restartcheck output to see if system/service restarts were requested
and take appropriate action.
'''
if 'No packages seem to need to be restarted' in rs_result:
return
reboot_required = False
for rstr in rs_result:
if 'System restart required' in rstr:
_update_nilrt_restart_state()
__salt__['system.set_reboot_required_witnessed']()
reboot_required = True
if kwargs.get('always_restart_services', True) or not reboot_required:
for rstr in rs_result:
if 'System restart required' not in rstr:
service = os.path.join('/etc/init.d', rstr)
if os.path.exists(service):
__salt__['cmd.run']([service, 'restart'])
def __virtual__():
'''
Confirm this module is on a nilrt based system
'''
if __grains__.get('os_family') == 'NILinuxRT':
try:
os.makedirs(NILRT_RESTARTCHECK_STATE_PATH)
except OSError as exc:
if exc.errno != errno.EEXIST:
return False, 'Error creating {0} (-{1}): {2}'.format(
NILRT_RESTARTCHECK_STATE_PATH,
exc.errno,
exc.strerror)
# populate state dir if empty
if not os.listdir(NILRT_RESTARTCHECK_STATE_PATH):
_update_nilrt_restart_state()
return __virtualname__
if os.path.isdir(OPKG_CONFDIR):
return __virtualname__
return False, "Module opkg only works on OpenEmbedded based systems"
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
if not names:
return ''
ret = {}
for name in names:
ret[name] = ''
# Refresh before looking for the latest version available
if refresh:
refresh_db()
cmd = ['opkg', 'list-upgradable']
out = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
try:
name, _oldversion, newversion = line.split(' - ')
if name in names:
ret[name] = newversion
except ValueError:
pass
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = latest_version
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(failhard=False, **kwargs): # pylint: disable=unused-argument
'''
Updates the opkg database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
failhard
If False, return results of failed lines as ``False`` for the package
database that encountered the error.
If True, raise an error with a list of the package databases that
encountered errors.
.. versionadded:: 2018.3.0
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
error_repos = []
cmd = ['opkg', 'update']
# opkg returns a non-zero retcode when there is a failure to refresh
# from one or more repos. Due to this, ignore the retcode.
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True,
redirect_stderr=True)
out = call['stdout']
prev_line = ''
for line in salt.utils.itertools.split(out, '\n'):
if 'Inflating' in line:
key = line.strip().split()[1][:-1]
ret[key] = True
elif 'Updated source' in line:
# Use the previous line.
key = prev_line.strip().split()[1][:-1]
ret[key] = True
elif 'Failed to download' in line:
key = line.strip().split()[5].split(',')[0]
ret[key] = False
error_repos.append(key)
prev_line = line
if failhard and error_repos:
raise CommandExecutionError(
'Error getting repos: {0}'.format(', '.join(error_repos))
)
# On a non-zero exit code where no failed repos were found, raise an
# exception because this appears to be a different kind of error.
if call['retcode'] != 0 and not error_repos:
raise CommandExecutionError(out)
return ret
def _is_testmode(**kwargs):
'''
Returns whether a test mode (noaction) operation was requested.
'''
return bool(kwargs.get('test') or __opts__.get('test'))
def _append_noaction_if_testmode(cmd, **kwargs):
'''
Adds the --noaction flag to the command if it's running in the test mode.
'''
if _is_testmode(**kwargs):
cmd.append('--noaction')
def _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall):
'''
Builds a list of install commands to be executed in sequence in order to process
each of the to_install, to_downgrade, and to_reinstall lists.
'''
cmds = []
if to_install:
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(to_install)
cmds.append(cmd)
if to_downgrade:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-downgrade')
cmd.extend(to_downgrade)
cmds.append(cmd)
if to_reinstall:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-reinstall')
cmd.extend(to_reinstall)
cmds.append(cmd)
return cmds
def _parse_reported_packages_from_install_output(output):
'''
Parses the output of "opkg install" to determine what packages would have been
installed by an operation run with the --noaction flag.
We are looking for lines like:
Installing <package> (<version>) on <target>
or
Upgrading <package> from <oldVersion> to <version> on root
'''
reported_pkgs = {}
install_pattern = re.compile(r'Installing\s(?P<package>.*?)\s\((?P<version>.*?)\)\son\s(?P<target>.*?)')
upgrade_pattern = re.compile(r'Upgrading\s(?P<package>.*?)\sfrom\s(?P<oldVersion>.*?)\sto\s(?P<version>.*?)\son\s(?P<target>.*?)')
for line in salt.utils.itertools.split(output, '\n'):
match = install_pattern.match(line)
if match is None:
match = upgrade_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = match.group('version')
return reported_pkgs
def _execute_install_command(cmd, parse_output, errors, parsed_packages):
'''
Executes a command for the install operation.
If the command fails, its error output will be appended to the errors list.
If the command succeeds and parse_output is true, updated packages will be appended
to the parsed_packages dictionary.
'''
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors.append(out['stderr'])
else:
errors.append(out['stdout'])
elif parse_output:
parsed_packages.update(_parse_reported_packages_from_install_output(out['stdout']))
def install(name=None,
refresh=False,
pkgs=None,
sources=None,
reinstall=False,
**kwargs):
'''
Install the passed package, add refresh=True to update the opkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionadded:: 2017.7.0
reinstall : False
Specifying reinstall=True will use ``opkg install --force-reinstall``
rather than simply ``opkg install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``opkg
install --force-reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2017.7.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of IPK packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
install_recommends
Whether to install the packages marked as recommended. Default is True.
only_upgrade
Only upgrade the packages (disallow downgrades), if they are already
installed. Default is False.
.. versionadded:: 2017.7.0
always_restart_services
Whether to restart services even if a reboot is required. Default is True.
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
refreshdb = salt.utils.data.is_true(refresh)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
cmd_prefix = ['opkg', 'install']
to_install = []
to_reinstall = []
to_downgrade = []
_append_noaction_if_testmode(cmd_prefix, **kwargs)
if not pkg_params:
return {}
elif pkg_type == 'file':
if reinstall:
cmd_prefix.append('--force-reinstall')
if not kwargs.get('only_upgrade', False):
cmd_prefix.append('--force-downgrade')
to_install.extend(pkg_params)
elif pkg_type == 'repository':
if not kwargs.get('install_recommends', True):
cmd_prefix.append('--no-install-recommends')
for pkgname, pkgversion in six.iteritems(pkg_params):
if (name and pkgs is None and kwargs.get('version') and
len(pkg_params) == 1):
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
version_num = pkgversion
if version_num is None:
# Don't allow downgrades if the version
# number is not specified.
if reinstall and pkgname in old:
to_reinstall.append(pkgname)
else:
to_install.append(pkgname)
else:
pkgstr = '{0}={1}'.format(pkgname, version_num)
cver = old.get(pkgname, '')
if reinstall and cver and salt.utils.versions.compare(
ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall.append(pkgstr)
elif not cver or salt.utils.versions.compare(
ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
to_install.append(pkgstr)
else:
if not kwargs.get('only_upgrade', False):
to_downgrade.append(pkgstr)
else:
# This should cause the command to fail.
to_install.append(pkgstr)
cmds = _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall)
if not cmds:
return {}
if refreshdb:
refresh_db()
errors = []
is_testmode = _is_testmode(**kwargs)
test_packages = {}
for cmd in cmds:
_execute_install_command(cmd, is_testmode, errors, test_packages)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if is_testmode:
new = copy.deepcopy(new)
new.update(test_packages)
ret = salt.utils.data.compare_dicts(old, new)
if pkg_type == 'file' and reinstall:
# For file-based packages, prepare 'to_reinstall' to have a list
# of all the package names that may have been reinstalled.
# This way, we could include reinstalled packages in 'ret'.
for pkgfile in to_install:
# Convert from file name to package name.
cmd = ['opkg', 'info', pkgfile]
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] == 0:
# Just need the package name.
pkginfo_dict = _process_info_installed_output(
out['stdout'], []
)
if pkginfo_dict:
to_reinstall.append(list(pkginfo_dict.keys())[0])
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def _parse_reported_packages_from_remove_output(output):
'''
Parses the output of "opkg remove" to determine what packages would have been
removed by an operation run with the --noaction flag.
We are looking for lines like
Removing <package> (<version>) from <Target>...
'''
reported_pkgs = {}
remove_pattern = re.compile(r'Removing\s(?P<package>.*?)\s\((?P<version>.*?)\)\sfrom\s(?P<target>.*?)...')
for line in salt.utils.itertools.split(output, '\n'):
match = remove_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = ''
return reported_pkgs
def remove(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Remove packages using ``opkg remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
remove_dependencies
Remove package and all dependencies
.. versionadded:: 2019.2.0
auto_remove_deps
Remove packages that were installed automatically to satisfy dependencies
.. versionadded:: 2019.2.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
salt '*' pkg.remove pkgs='["foo", "bar"]' remove_dependencies=True auto_remove_deps=True
'''
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 {}
cmd = ['opkg', 'remove']
_append_noaction_if_testmode(cmd, **kwargs)
if kwargs.get('remove_dependencies', False):
cmd.append('--force-removal-of-dependent-packages')
if kwargs.get('auto_remove_deps', False):
cmd.append('--autoremove')
cmd.extend(targets)
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors = [out['stderr']]
else:
errors = [out['stdout']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if _is_testmode(**kwargs):
reportedPkgs = _parse_reported_packages_from_remove_output(out['stdout'])
new = {k: v for k, v in new.items() if k not in reportedPkgs}
ret = salt.utils.data.compare_dicts(old, new)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def purge(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Package purges are not supported by opkg, this function is identical to
:mod:`pkg.remove <salt.modules.opkg.remove>`.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name, pkgs=pkgs)
def upgrade(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
Upgrades all packages via ``opkg upgrade``
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
errors = []
if salt.utils.data.is_true(refresh):
refresh_db()
old = list_pkgs()
cmd = ['opkg', 'upgrade']
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
errors.append(result)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif state != 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = _set_state(target, 'hold')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif state == 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret['comment'] = ('Package {0} is set not to be held.'
.format(target))
else:
result = _set_state(target, 'ok')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def _get_state(pkg):
'''
View package state from the opkg database
Return the state of pkg
'''
cmd = ['opkg', 'status']
cmd.append(pkg)
out = __salt__['cmd.run'](cmd, python_shell=False)
state_flag = ''
for line in salt.utils.itertools.split(out, '\n'):
if line.startswith('Status'):
_status, _state_want, state_flag, _state_status = line.split()
return state_flag
def _set_state(pkg, state):
'''
Change package state on the opkg database
The state can be any of:
- hold
- noprune
- user
- ok
- installed
- unpacked
This command is commonly used to mark a specific package to be held from
being upgraded, that is, to be kept at a certain version.
Returns a dict containing the package name, and the new and old
versions.
'''
ret = {}
valid_states = ('hold', 'noprune', 'user', 'ok', 'installed', 'unpacked')
if state not in valid_states:
raise SaltInvocationError('Invalid state: {0}'.format(state))
oldstate = _get_state(pkg)
cmd = ['opkg', 'flag']
cmd.append(state)
cmd.append(pkg)
_out = __salt__['cmd.run'](cmd, python_shell=False)
# Missing return value check due to opkg issue 160
ret[pkg] = {'old': oldstate,
'new': state}
return ret
def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
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
cmd = ['opkg', 'list-installed']
ret = {}
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
# This is a continuation of package description
if not line or line[0] == ' ':
continue
# This contains package name, version, and description.
# Extract the first two.
pkg_name, pkg_version = line.split(' - ', 2)[:2]
__salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version)
__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 list_upgrades(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
List all available package upgrades.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
ret = {}
if salt.utils.data.is_true(refresh):
refresh_db()
cmd = ['opkg', 'list-upgradable']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
if 'stdout' in call:
comment += call['stdout']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
name, _oldversion, newversion = line.split(' - ')
ret[name] = newversion
return ret
def _convert_to_standard_attr(attr):
'''
Helper function for _process_info_installed_output()
Converts an opkg attribute name to a standard attribute
name which is used across 'pkg' modules.
'''
ret_attr = ATTR_MAP.get(attr, None)
if ret_attr is None:
# All others convert to lowercase
return attr.lower()
return ret_attr
def _process_info_installed_output(out, filter_attrs):
'''
Helper function for info_installed()
Processes stdout output from a single invocation of
'opkg status'.
'''
ret = {}
name = None
attrs = {}
attr = None
for line in salt.utils.itertools.split(out, '\n'):
if line and line[0] == ' ':
# This is a continuation of the last attr
if filter_attrs is None or attr in filter_attrs:
line = line.strip()
if attrs[attr]:
# If attr is empty, don't add leading newline
attrs[attr] += '\n'
attrs[attr] += line
continue
line = line.strip()
if not line:
# Separator between different packages
if name:
ret[name] = attrs
name = None
attrs = {}
attr = None
continue
key, value = line.split(':', 1)
value = value.lstrip()
attr = _convert_to_standard_attr(key)
if attr == 'name':
name = value
elif filter_attrs is None or attr in filter_attrs:
attrs[attr] = value
if name:
ret[name] = attrs
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
.. versionadded:: 2017.7.0
:param names:
Names of the packages to get information about. If none are specified,
will return information for all installed packages.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
arch, conffiles, conflicts, depends, description, filename, group,
install_date_time_t, md5sum, packager, provides, recommends,
replaces, size, source, suggests, url, version
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed
salt '*' pkg.info_installed attr=version,packager
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> attr=version,packager
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,packager
'''
attr = kwargs.pop('attr', None)
if attr is None:
filter_attrs = None
elif isinstance(attr, six.string_types):
filter_attrs = set(attr.split(','))
else:
filter_attrs = set(attr)
ret = {}
if names:
# Specific list of names of installed packages
for name in names:
cmd = ['opkg', 'status', name]
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
else:
# All installed packages
cmd = ['opkg', 'status']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
return ret
def upgrade_available(name, **kwargs): # pylint: disable=unused-argument
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs): # pylint: disable=unused-argument
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2016.3.4
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0' '0.2.4.1-0'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] if ignore_epoch else six.text_type(x)
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
output = __salt__['cmd.run_stdout'](['opkg', '--version'],
output_loglevel='trace',
python_shell=False)
opkg_version = output.split(' ')[2].strip()
if salt.utils.versions.LooseVersion(opkg_version) >= \
salt.utils.versions.LooseVersion('0.3.4'):
cmd_compare = ['opkg', 'compare-versions']
elif salt.utils.path.which('opkg-compare-versions'):
cmd_compare = ['opkg-compare-versions']
else:
log.warning('Unable to find a compare-versions utility installed. Either upgrade opkg to '
'version > 0.3.4 (preferred) or install the older opkg-compare-versions script.')
return None
for oper, ret in (("<<", -1), ("=", 0), (">>", 1)):
cmd = cmd_compare[:]
cmd.append(_cmd_quote(pkg1))
cmd.append(oper)
cmd.append(_cmd_quote(pkg2))
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
ignore_retcode=True,
python_shell=False)
if retcode == 0:
return ret
return None
def _set_repo_option(repo, option):
'''
Set the option to repo
'''
if not option:
return
opt = option.split('=')
if len(opt) != 2:
return
if opt[0] == 'trusted':
repo['trusted'] = opt[1] == 'yes'
else:
repo[opt[0]] = opt[1]
def _set_repo_options(repo, options):
'''
Set the options to the repo.
'''
delimiters = "[", "]"
pattern = '|'.join(map(re.escape, delimiters))
for option in options:
splitted = re.split(pattern, option)
for opt in splitted:
_set_repo_option(repo, opt)
def _create_repo(line, filename):
'''
Create repo
'''
repo = {}
if line.startswith('#'):
repo['enabled'] = False
line = line[1:]
else:
repo['enabled'] = True
cols = salt.utils.args.shlex_split(line.strip())
repo['compressed'] = not cols[0] in 'src'
repo['name'] = cols[1]
repo['uri'] = cols[2]
repo['file'] = os.path.join(OPKG_CONFDIR, filename)
if len(cols) > 3:
_set_repo_options(repo, cols[3:])
return repo
def _read_repos(conf_file, repos, filename, regex):
'''
Read repos from configuration file
'''
for line in conf_file:
line = salt.utils.stringutils.to_unicode(line)
if not regex.search(line):
continue
repo = _create_repo(line, filename)
# do not store duplicated uri's
if repo['uri'] not in repos:
repos[repo['uri']] = [repo]
def list_repos(**kwargs): # pylint: disable=unused-argument
'''
Lists all repos on ``/etc/opkg/*.conf``
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos = {}
regex = re.compile(REPO_REGEXP)
for filename in os.listdir(OPKG_CONFDIR):
if not filename.endswith(".conf"):
continue
with salt.utils.files.fopen(os.path.join(OPKG_CONFDIR, filename)) as conf_file:
_read_repos(conf_file, repos, filename, regex)
return repos
def get_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Display a repo from the ``/etc/opkg/*.conf``
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo repo
'''
repos = list_repos()
if repos:
for source in six.itervalues(repos):
for sub in source:
if sub['name'] == repo:
return sub
return {}
def _del_repo_from_file(repo, filepath):
'''
Remove a repo from filepath
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
regex = re.compile(REPO_REGEXP)
for line in fhandle:
line = salt.utils.stringutils.to_unicode(line)
if regex.search(line):
if line.startswith('#'):
line = line[1:]
cols = salt.utils.args.shlex_split(line.strip())
if repo != cols[1]:
output.append(salt.utils.stringutils.to_str(line))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def _set_trusted_option_if_needed(repostr, trusted):
'''
Set trusted option to repo if needed
'''
if trusted is True:
repostr += ' [trusted=yes]'
elif trusted is False:
repostr += ' [trusted=no]'
return repostr
def _add_new_repo(repo, properties):
'''
Add a new repo entry
'''
repostr = '# ' if not properties.get('enabled') else ''
repostr += 'src/gz ' if properties.get('compressed') else 'src '
if ' ' in repo:
repostr += '"' + repo + '" '
else:
repostr += repo + ' '
repostr += properties.get('uri')
repostr = _set_trusted_option_if_needed(repostr, properties.get('trusted'))
repostr += '\n'
conffile = os.path.join(OPKG_CONFDIR, repo + '.conf')
with salt.utils.files.fopen(conffile, 'a') as fhandle:
fhandle.write(salt.utils.stringutils.to_str(repostr))
def _mod_repo_in_file(repo, repostr, filepath):
'''
Replace a repo entry in filepath with repostr
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
for line in fhandle:
cols = salt.utils.args.shlex_split(
salt.utils.stringutils.to_unicode(line).strip()
)
if repo not in cols:
output.append(line)
else:
output.append(salt.utils.stringutils.to_str(repostr + '\n'))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as uri is defined.
The following options are available to modify a repo definition:
repo
alias by which opkg refers to the repo.
uri
the URI to the repo.
compressed
defines (True or False) if the index file is compressed
enabled
enable or disable (True or False) repository
but do not remove if disabled.
refresh
enable or disable (True or False) auto-refresh of the repositories
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo repo uri=http://new/uri
salt '*' pkg.mod_repo repo enabled=False
'''
repos = list_repos()
found = False
uri = ''
if 'uri' in kwargs:
uri = kwargs['uri']
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
found = True
repostr = ''
if 'enabled' in kwargs and not kwargs['enabled']:
repostr += '# '
if 'compressed' in kwargs:
repostr += 'src/gz ' if kwargs['compressed'] else 'src'
else:
repostr += 'src/gz' if source['compressed'] else 'src'
repo_alias = kwargs['alias'] if 'alias' in kwargs else repo
if ' ' in repo_alias:
repostr += ' "{0}"'.format(repo_alias)
else:
repostr += ' {0}'.format(repo_alias)
repostr += ' {0}'.format(kwargs['uri'] if 'uri' in kwargs else source['uri'])
trusted = kwargs.get('trusted')
repostr = _set_trusted_option_if_needed(repostr, trusted) if trusted is not None else \
_set_trusted_option_if_needed(repostr, source.get('trusted'))
_mod_repo_in_file(repo, repostr, source['file'])
elif uri and source['uri'] == uri:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(uri, source['name']))
if not found:
# Need to add a new repo
if 'uri' not in kwargs:
raise CommandExecutionError(
'Repository \'{0}\' not found and no URI passed to create one.'.format(repo))
properties = {'uri': kwargs['uri']}
# If compressed is not defined, assume True
properties['compressed'] = kwargs['compressed'] if 'compressed' in kwargs else True
# If enabled is not defined, assume True
properties['enabled'] = kwargs['enabled'] if 'enabled' in kwargs else True
properties['trusted'] = kwargs.get('trusted')
_add_new_repo(repo, properties)
if 'refresh' in kwargs:
refresh_db()
def file_list(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
output = file_dict(*packages)
files = []
for package in list(output['packages'].values()):
files.extend(package)
return {'errors': output['errors'], 'files': files}
def file_dict(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
errors = []
ret = {}
cmd_files = ['opkg', 'files']
if not packages:
packages = list(list_pkgs().keys())
for package in packages:
files = []
cmd = cmd_files[:]
cmd.append(package)
out = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
for line in out['stdout'].splitlines():
if line.startswith('/'):
files.append(line)
elif line.startswith(' * '):
errors.append(line[3:])
break
else:
continue
if files:
ret[package] = files
return {'errors': errors, 'packages': ret}
def owner(*paths, **kwargs): # pylint: disable=unused-argument
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.opkg.version`, if a single
path is passed, a string will be returned, and if multiple paths are passed,
a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
cmd_search = ['opkg', 'search']
for path in paths:
cmd = cmd_search[:]
cmd.append(path)
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
if output:
ret[path] = output.split(' - ')[0].strip()
else:
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def version_clean(version):
'''
Clean the version string removing extra data.
There's nothing do to here for nipkg.py, therefore it will always
return the given version.
'''
return version
def check_extra_requirements(pkgname, pkgver):
'''
Check if the installed package already has the given requirements.
There's nothing do to here for nipkg.py, therefore it will always
return True.
'''
return True
|
saltstack/salt
|
salt/modules/opkg.py
|
mod_repo
|
python
|
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as uri is defined.
The following options are available to modify a repo definition:
repo
alias by which opkg refers to the repo.
uri
the URI to the repo.
compressed
defines (True or False) if the index file is compressed
enabled
enable or disable (True or False) repository
but do not remove if disabled.
refresh
enable or disable (True or False) auto-refresh of the repositories
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo repo uri=http://new/uri
salt '*' pkg.mod_repo repo enabled=False
'''
repos = list_repos()
found = False
uri = ''
if 'uri' in kwargs:
uri = kwargs['uri']
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
found = True
repostr = ''
if 'enabled' in kwargs and not kwargs['enabled']:
repostr += '# '
if 'compressed' in kwargs:
repostr += 'src/gz ' if kwargs['compressed'] else 'src'
else:
repostr += 'src/gz' if source['compressed'] else 'src'
repo_alias = kwargs['alias'] if 'alias' in kwargs else repo
if ' ' in repo_alias:
repostr += ' "{0}"'.format(repo_alias)
else:
repostr += ' {0}'.format(repo_alias)
repostr += ' {0}'.format(kwargs['uri'] if 'uri' in kwargs else source['uri'])
trusted = kwargs.get('trusted')
repostr = _set_trusted_option_if_needed(repostr, trusted) if trusted is not None else \
_set_trusted_option_if_needed(repostr, source.get('trusted'))
_mod_repo_in_file(repo, repostr, source['file'])
elif uri and source['uri'] == uri:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(uri, source['name']))
if not found:
# Need to add a new repo
if 'uri' not in kwargs:
raise CommandExecutionError(
'Repository \'{0}\' not found and no URI passed to create one.'.format(repo))
properties = {'uri': kwargs['uri']}
# If compressed is not defined, assume True
properties['compressed'] = kwargs['compressed'] if 'compressed' in kwargs else True
# If enabled is not defined, assume True
properties['enabled'] = kwargs['enabled'] if 'enabled' in kwargs else True
properties['trusted'] = kwargs.get('trusted')
_add_new_repo(repo, properties)
if 'refresh' in kwargs:
refresh_db()
|
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as uri is defined.
The following options are available to modify a repo definition:
repo
alias by which opkg refers to the repo.
uri
the URI to the repo.
compressed
defines (True or False) if the index file is compressed
enabled
enable or disable (True or False) repository
but do not remove if disabled.
refresh
enable or disable (True or False) auto-refresh of the repositories
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo repo uri=http://new/uri
salt '*' pkg.mod_repo repo enabled=False
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/opkg.py#L1462-L1533
|
[
"def refresh_db(failhard=False, **kwargs): # pylint: disable=unused-argument\n '''\n Updates the opkg database to latest packages based upon repositories\n\n Returns a dict, with the keys being package databases and the values being\n the result of the update attempt. Values can be one of the following:\n\n - ``True``: Database updated successfully\n - ``False``: Problem updating database\n\n failhard\n If False, return results of failed lines as ``False`` for the package\n database that encountered the error.\n If True, raise an error with a list of the package databases that\n encountered errors.\n\n .. versionadded:: 2018.3.0\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.refresh_db\n '''\n # Remove rtag file to keep multiple refreshes from happening in pkg states\n salt.utils.pkg.clear_rtag(__opts__)\n ret = {}\n error_repos = []\n cmd = ['opkg', 'update']\n # opkg returns a non-zero retcode when there is a failure to refresh\n # from one or more repos. Due to this, ignore the retcode.\n call = __salt__['cmd.run_all'](cmd,\n output_loglevel='trace',\n python_shell=False,\n ignore_retcode=True,\n redirect_stderr=True)\n\n out = call['stdout']\n prev_line = ''\n for line in salt.utils.itertools.split(out, '\\n'):\n if 'Inflating' in line:\n key = line.strip().split()[1][:-1]\n ret[key] = True\n elif 'Updated source' in line:\n # Use the previous line.\n key = prev_line.strip().split()[1][:-1]\n ret[key] = True\n elif 'Failed to download' in line:\n key = line.strip().split()[5].split(',')[0]\n ret[key] = False\n error_repos.append(key)\n prev_line = line\n\n if failhard and error_repos:\n raise CommandExecutionError(\n 'Error getting repos: {0}'.format(', '.join(error_repos))\n )\n\n # On a non-zero exit code where no failed repos were found, raise an\n # exception because this appears to be a different kind of error.\n if call['retcode'] != 0 and not error_repos:\n raise CommandExecutionError(out)\n\n return ret\n",
"def list_repos(**kwargs): # pylint: disable=unused-argument\n '''\n Lists all repos on ``/etc/opkg/*.conf``\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.list_repos\n '''\n repos = {}\n regex = re.compile(REPO_REGEXP)\n for filename in os.listdir(OPKG_CONFDIR):\n if not filename.endswith(\".conf\"):\n continue\n with salt.utils.files.fopen(os.path.join(OPKG_CONFDIR, filename)) as conf_file:\n _read_repos(conf_file, repos, filename, regex)\n return repos\n",
"def _set_trusted_option_if_needed(repostr, trusted):\n '''\n Set trusted option to repo if needed\n '''\n if trusted is True:\n repostr += ' [trusted=yes]'\n elif trusted is False:\n repostr += ' [trusted=no]'\n return repostr\n",
"def _add_new_repo(repo, properties):\n '''\n Add a new repo entry\n '''\n repostr = '# ' if not properties.get('enabled') else ''\n repostr += 'src/gz ' if properties.get('compressed') else 'src '\n if ' ' in repo:\n repostr += '\"' + repo + '\" '\n else:\n repostr += repo + ' '\n repostr += properties.get('uri')\n repostr = _set_trusted_option_if_needed(repostr, properties.get('trusted'))\n repostr += '\\n'\n conffile = os.path.join(OPKG_CONFDIR, repo + '.conf')\n\n with salt.utils.files.fopen(conffile, 'a') as fhandle:\n fhandle.write(salt.utils.stringutils.to_str(repostr))\n",
"def _mod_repo_in_file(repo, repostr, filepath):\n '''\n Replace a repo entry in filepath with repostr\n '''\n with salt.utils.files.fopen(filepath) as fhandle:\n output = []\n for line in fhandle:\n cols = salt.utils.args.shlex_split(\n salt.utils.stringutils.to_unicode(line).strip()\n )\n if repo not in cols:\n output.append(line)\n else:\n output.append(salt.utils.stringutils.to_str(repostr + '\\n'))\n with salt.utils.files.fopen(filepath, 'w') as fhandle:\n fhandle.writelines(output)\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Opkg
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
.. versionadded: 2016.3.0
.. note::
For version comparison support on opkg < 0.3.4, the ``opkg-utils`` package
must be installed.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import os
import re
import logging
import errno
# Import salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.itertools
import salt.utils.path
import salt.utils.pkg
import salt.utils.stringutils
import salt.utils.versions
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import shlex_quote as _cmd_quote # pylint: disable=import-error
from salt.ext.six.moves import map # pylint: disable=import-error,redefined-builtin
REPO_REGEXP = r'^#?\s*(src|src/gz)\s+([^\s<>]+|"[^<>]+")\s+[^\s<>]+'
OPKG_CONFDIR = '/etc/opkg'
ATTR_MAP = {
'Architecture': 'arch',
'Homepage': 'url',
'Installed-Time': 'install_date_time_t',
'Maintainer': 'packager',
'Package': 'name',
'Section': 'group'
}
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
NILRT_RESTARTCHECK_STATE_PATH = '/var/lib/salt/restartcheck_state'
def _update_nilrt_restart_state():
'''
NILRT systems determine whether to reboot after various package operations
including but not limited to kernel module installs/removals by checking
specific file md5sums & timestamps. These files are touched/modified by
the post-install/post-remove functions of their respective packages.
The opkg module uses this function to store/update those file timestamps
and checksums to be used later by the restartcheck module.
'''
__salt__['cmd.shell']('stat -c %Y /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.timestamp'
.format(NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.md5sum'
.format(NILRT_RESTARTCHECK_STATE_PATH))
# We can't assume nisysapi.ini always exists like modules.dep
nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'
if os.path.exists(nisysapi_path):
__salt__['cmd.shell']('stat -c %Y {0} >{1}/nisysapi.ini.timestamp'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0} >{1}/nisysapi.ini.md5sum'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
# Expert plugin files get added to a conf.d dir, so keep track of the total
# no. of files, their timestamps and content hashes
nisysapi_conf_d_path = "/usr/lib/{0}/nisysapi/conf.d/experts/".format(
'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'
)
if os.path.exists(nisysapi_conf_d_path):
with salt.utils.files.fopen('{0}/sysapi.conf.d.count'.format(
NILRT_RESTARTCHECK_STATE_PATH), 'w') as fcount:
fcount.write(str(len(os.listdir(nisysapi_conf_d_path))))
for fexpert in os.listdir(nisysapi_conf_d_path):
__salt__['cmd.shell']('stat -c %Y {0}/{1} >{2}/{1}.timestamp'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0}/{1} >{2}/{1}.md5sum'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
def _get_restartcheck_result(errors):
'''
Return restartcheck result and append errors (if any) to ``errors``
'''
rs_result = __salt__['restartcheck.restartcheck'](verbose=False)
if isinstance(rs_result, dict) and 'comment' in rs_result:
errors.append(rs_result['comment'])
return rs_result
def _process_restartcheck_result(rs_result, **kwargs):
'''
Check restartcheck output to see if system/service restarts were requested
and take appropriate action.
'''
if 'No packages seem to need to be restarted' in rs_result:
return
reboot_required = False
for rstr in rs_result:
if 'System restart required' in rstr:
_update_nilrt_restart_state()
__salt__['system.set_reboot_required_witnessed']()
reboot_required = True
if kwargs.get('always_restart_services', True) or not reboot_required:
for rstr in rs_result:
if 'System restart required' not in rstr:
service = os.path.join('/etc/init.d', rstr)
if os.path.exists(service):
__salt__['cmd.run']([service, 'restart'])
def __virtual__():
'''
Confirm this module is on a nilrt based system
'''
if __grains__.get('os_family') == 'NILinuxRT':
try:
os.makedirs(NILRT_RESTARTCHECK_STATE_PATH)
except OSError as exc:
if exc.errno != errno.EEXIST:
return False, 'Error creating {0} (-{1}): {2}'.format(
NILRT_RESTARTCHECK_STATE_PATH,
exc.errno,
exc.strerror)
# populate state dir if empty
if not os.listdir(NILRT_RESTARTCHECK_STATE_PATH):
_update_nilrt_restart_state()
return __virtualname__
if os.path.isdir(OPKG_CONFDIR):
return __virtualname__
return False, "Module opkg only works on OpenEmbedded based systems"
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
if not names:
return ''
ret = {}
for name in names:
ret[name] = ''
# Refresh before looking for the latest version available
if refresh:
refresh_db()
cmd = ['opkg', 'list-upgradable']
out = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
try:
name, _oldversion, newversion = line.split(' - ')
if name in names:
ret[name] = newversion
except ValueError:
pass
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = latest_version
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(failhard=False, **kwargs): # pylint: disable=unused-argument
'''
Updates the opkg database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
failhard
If False, return results of failed lines as ``False`` for the package
database that encountered the error.
If True, raise an error with a list of the package databases that
encountered errors.
.. versionadded:: 2018.3.0
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
error_repos = []
cmd = ['opkg', 'update']
# opkg returns a non-zero retcode when there is a failure to refresh
# from one or more repos. Due to this, ignore the retcode.
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True,
redirect_stderr=True)
out = call['stdout']
prev_line = ''
for line in salt.utils.itertools.split(out, '\n'):
if 'Inflating' in line:
key = line.strip().split()[1][:-1]
ret[key] = True
elif 'Updated source' in line:
# Use the previous line.
key = prev_line.strip().split()[1][:-1]
ret[key] = True
elif 'Failed to download' in line:
key = line.strip().split()[5].split(',')[0]
ret[key] = False
error_repos.append(key)
prev_line = line
if failhard and error_repos:
raise CommandExecutionError(
'Error getting repos: {0}'.format(', '.join(error_repos))
)
# On a non-zero exit code where no failed repos were found, raise an
# exception because this appears to be a different kind of error.
if call['retcode'] != 0 and not error_repos:
raise CommandExecutionError(out)
return ret
def _is_testmode(**kwargs):
'''
Returns whether a test mode (noaction) operation was requested.
'''
return bool(kwargs.get('test') or __opts__.get('test'))
def _append_noaction_if_testmode(cmd, **kwargs):
'''
Adds the --noaction flag to the command if it's running in the test mode.
'''
if _is_testmode(**kwargs):
cmd.append('--noaction')
def _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall):
'''
Builds a list of install commands to be executed in sequence in order to process
each of the to_install, to_downgrade, and to_reinstall lists.
'''
cmds = []
if to_install:
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(to_install)
cmds.append(cmd)
if to_downgrade:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-downgrade')
cmd.extend(to_downgrade)
cmds.append(cmd)
if to_reinstall:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-reinstall')
cmd.extend(to_reinstall)
cmds.append(cmd)
return cmds
def _parse_reported_packages_from_install_output(output):
'''
Parses the output of "opkg install" to determine what packages would have been
installed by an operation run with the --noaction flag.
We are looking for lines like:
Installing <package> (<version>) on <target>
or
Upgrading <package> from <oldVersion> to <version> on root
'''
reported_pkgs = {}
install_pattern = re.compile(r'Installing\s(?P<package>.*?)\s\((?P<version>.*?)\)\son\s(?P<target>.*?)')
upgrade_pattern = re.compile(r'Upgrading\s(?P<package>.*?)\sfrom\s(?P<oldVersion>.*?)\sto\s(?P<version>.*?)\son\s(?P<target>.*?)')
for line in salt.utils.itertools.split(output, '\n'):
match = install_pattern.match(line)
if match is None:
match = upgrade_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = match.group('version')
return reported_pkgs
def _execute_install_command(cmd, parse_output, errors, parsed_packages):
'''
Executes a command for the install operation.
If the command fails, its error output will be appended to the errors list.
If the command succeeds and parse_output is true, updated packages will be appended
to the parsed_packages dictionary.
'''
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors.append(out['stderr'])
else:
errors.append(out['stdout'])
elif parse_output:
parsed_packages.update(_parse_reported_packages_from_install_output(out['stdout']))
def install(name=None,
refresh=False,
pkgs=None,
sources=None,
reinstall=False,
**kwargs):
'''
Install the passed package, add refresh=True to update the opkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionadded:: 2017.7.0
reinstall : False
Specifying reinstall=True will use ``opkg install --force-reinstall``
rather than simply ``opkg install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``opkg
install --force-reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2017.7.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of IPK packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
install_recommends
Whether to install the packages marked as recommended. Default is True.
only_upgrade
Only upgrade the packages (disallow downgrades), if they are already
installed. Default is False.
.. versionadded:: 2017.7.0
always_restart_services
Whether to restart services even if a reboot is required. Default is True.
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
refreshdb = salt.utils.data.is_true(refresh)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
cmd_prefix = ['opkg', 'install']
to_install = []
to_reinstall = []
to_downgrade = []
_append_noaction_if_testmode(cmd_prefix, **kwargs)
if not pkg_params:
return {}
elif pkg_type == 'file':
if reinstall:
cmd_prefix.append('--force-reinstall')
if not kwargs.get('only_upgrade', False):
cmd_prefix.append('--force-downgrade')
to_install.extend(pkg_params)
elif pkg_type == 'repository':
if not kwargs.get('install_recommends', True):
cmd_prefix.append('--no-install-recommends')
for pkgname, pkgversion in six.iteritems(pkg_params):
if (name and pkgs is None and kwargs.get('version') and
len(pkg_params) == 1):
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
version_num = pkgversion
if version_num is None:
# Don't allow downgrades if the version
# number is not specified.
if reinstall and pkgname in old:
to_reinstall.append(pkgname)
else:
to_install.append(pkgname)
else:
pkgstr = '{0}={1}'.format(pkgname, version_num)
cver = old.get(pkgname, '')
if reinstall and cver and salt.utils.versions.compare(
ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall.append(pkgstr)
elif not cver or salt.utils.versions.compare(
ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
to_install.append(pkgstr)
else:
if not kwargs.get('only_upgrade', False):
to_downgrade.append(pkgstr)
else:
# This should cause the command to fail.
to_install.append(pkgstr)
cmds = _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall)
if not cmds:
return {}
if refreshdb:
refresh_db()
errors = []
is_testmode = _is_testmode(**kwargs)
test_packages = {}
for cmd in cmds:
_execute_install_command(cmd, is_testmode, errors, test_packages)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if is_testmode:
new = copy.deepcopy(new)
new.update(test_packages)
ret = salt.utils.data.compare_dicts(old, new)
if pkg_type == 'file' and reinstall:
# For file-based packages, prepare 'to_reinstall' to have a list
# of all the package names that may have been reinstalled.
# This way, we could include reinstalled packages in 'ret'.
for pkgfile in to_install:
# Convert from file name to package name.
cmd = ['opkg', 'info', pkgfile]
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] == 0:
# Just need the package name.
pkginfo_dict = _process_info_installed_output(
out['stdout'], []
)
if pkginfo_dict:
to_reinstall.append(list(pkginfo_dict.keys())[0])
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def _parse_reported_packages_from_remove_output(output):
'''
Parses the output of "opkg remove" to determine what packages would have been
removed by an operation run with the --noaction flag.
We are looking for lines like
Removing <package> (<version>) from <Target>...
'''
reported_pkgs = {}
remove_pattern = re.compile(r'Removing\s(?P<package>.*?)\s\((?P<version>.*?)\)\sfrom\s(?P<target>.*?)...')
for line in salt.utils.itertools.split(output, '\n'):
match = remove_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = ''
return reported_pkgs
def remove(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Remove packages using ``opkg remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
remove_dependencies
Remove package and all dependencies
.. versionadded:: 2019.2.0
auto_remove_deps
Remove packages that were installed automatically to satisfy dependencies
.. versionadded:: 2019.2.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
salt '*' pkg.remove pkgs='["foo", "bar"]' remove_dependencies=True auto_remove_deps=True
'''
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 {}
cmd = ['opkg', 'remove']
_append_noaction_if_testmode(cmd, **kwargs)
if kwargs.get('remove_dependencies', False):
cmd.append('--force-removal-of-dependent-packages')
if kwargs.get('auto_remove_deps', False):
cmd.append('--autoremove')
cmd.extend(targets)
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors = [out['stderr']]
else:
errors = [out['stdout']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if _is_testmode(**kwargs):
reportedPkgs = _parse_reported_packages_from_remove_output(out['stdout'])
new = {k: v for k, v in new.items() if k not in reportedPkgs}
ret = salt.utils.data.compare_dicts(old, new)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def purge(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Package purges are not supported by opkg, this function is identical to
:mod:`pkg.remove <salt.modules.opkg.remove>`.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name, pkgs=pkgs)
def upgrade(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
Upgrades all packages via ``opkg upgrade``
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
errors = []
if salt.utils.data.is_true(refresh):
refresh_db()
old = list_pkgs()
cmd = ['opkg', 'upgrade']
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
errors.append(result)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif state != 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = _set_state(target, 'hold')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif state == 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret['comment'] = ('Package {0} is set not to be held.'
.format(target))
else:
result = _set_state(target, 'ok')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def _get_state(pkg):
'''
View package state from the opkg database
Return the state of pkg
'''
cmd = ['opkg', 'status']
cmd.append(pkg)
out = __salt__['cmd.run'](cmd, python_shell=False)
state_flag = ''
for line in salt.utils.itertools.split(out, '\n'):
if line.startswith('Status'):
_status, _state_want, state_flag, _state_status = line.split()
return state_flag
def _set_state(pkg, state):
'''
Change package state on the opkg database
The state can be any of:
- hold
- noprune
- user
- ok
- installed
- unpacked
This command is commonly used to mark a specific package to be held from
being upgraded, that is, to be kept at a certain version.
Returns a dict containing the package name, and the new and old
versions.
'''
ret = {}
valid_states = ('hold', 'noprune', 'user', 'ok', 'installed', 'unpacked')
if state not in valid_states:
raise SaltInvocationError('Invalid state: {0}'.format(state))
oldstate = _get_state(pkg)
cmd = ['opkg', 'flag']
cmd.append(state)
cmd.append(pkg)
_out = __salt__['cmd.run'](cmd, python_shell=False)
# Missing return value check due to opkg issue 160
ret[pkg] = {'old': oldstate,
'new': state}
return ret
def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
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
cmd = ['opkg', 'list-installed']
ret = {}
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
# This is a continuation of package description
if not line or line[0] == ' ':
continue
# This contains package name, version, and description.
# Extract the first two.
pkg_name, pkg_version = line.split(' - ', 2)[:2]
__salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version)
__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 list_upgrades(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
List all available package upgrades.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
ret = {}
if salt.utils.data.is_true(refresh):
refresh_db()
cmd = ['opkg', 'list-upgradable']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
if 'stdout' in call:
comment += call['stdout']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
name, _oldversion, newversion = line.split(' - ')
ret[name] = newversion
return ret
def _convert_to_standard_attr(attr):
'''
Helper function for _process_info_installed_output()
Converts an opkg attribute name to a standard attribute
name which is used across 'pkg' modules.
'''
ret_attr = ATTR_MAP.get(attr, None)
if ret_attr is None:
# All others convert to lowercase
return attr.lower()
return ret_attr
def _process_info_installed_output(out, filter_attrs):
'''
Helper function for info_installed()
Processes stdout output from a single invocation of
'opkg status'.
'''
ret = {}
name = None
attrs = {}
attr = None
for line in salt.utils.itertools.split(out, '\n'):
if line and line[0] == ' ':
# This is a continuation of the last attr
if filter_attrs is None or attr in filter_attrs:
line = line.strip()
if attrs[attr]:
# If attr is empty, don't add leading newline
attrs[attr] += '\n'
attrs[attr] += line
continue
line = line.strip()
if not line:
# Separator between different packages
if name:
ret[name] = attrs
name = None
attrs = {}
attr = None
continue
key, value = line.split(':', 1)
value = value.lstrip()
attr = _convert_to_standard_attr(key)
if attr == 'name':
name = value
elif filter_attrs is None or attr in filter_attrs:
attrs[attr] = value
if name:
ret[name] = attrs
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
.. versionadded:: 2017.7.0
:param names:
Names of the packages to get information about. If none are specified,
will return information for all installed packages.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
arch, conffiles, conflicts, depends, description, filename, group,
install_date_time_t, md5sum, packager, provides, recommends,
replaces, size, source, suggests, url, version
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed
salt '*' pkg.info_installed attr=version,packager
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> attr=version,packager
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,packager
'''
attr = kwargs.pop('attr', None)
if attr is None:
filter_attrs = None
elif isinstance(attr, six.string_types):
filter_attrs = set(attr.split(','))
else:
filter_attrs = set(attr)
ret = {}
if names:
# Specific list of names of installed packages
for name in names:
cmd = ['opkg', 'status', name]
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
else:
# All installed packages
cmd = ['opkg', 'status']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
return ret
def upgrade_available(name, **kwargs): # pylint: disable=unused-argument
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs): # pylint: disable=unused-argument
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2016.3.4
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0' '0.2.4.1-0'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] if ignore_epoch else six.text_type(x)
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
output = __salt__['cmd.run_stdout'](['opkg', '--version'],
output_loglevel='trace',
python_shell=False)
opkg_version = output.split(' ')[2].strip()
if salt.utils.versions.LooseVersion(opkg_version) >= \
salt.utils.versions.LooseVersion('0.3.4'):
cmd_compare = ['opkg', 'compare-versions']
elif salt.utils.path.which('opkg-compare-versions'):
cmd_compare = ['opkg-compare-versions']
else:
log.warning('Unable to find a compare-versions utility installed. Either upgrade opkg to '
'version > 0.3.4 (preferred) or install the older opkg-compare-versions script.')
return None
for oper, ret in (("<<", -1), ("=", 0), (">>", 1)):
cmd = cmd_compare[:]
cmd.append(_cmd_quote(pkg1))
cmd.append(oper)
cmd.append(_cmd_quote(pkg2))
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
ignore_retcode=True,
python_shell=False)
if retcode == 0:
return ret
return None
def _set_repo_option(repo, option):
'''
Set the option to repo
'''
if not option:
return
opt = option.split('=')
if len(opt) != 2:
return
if opt[0] == 'trusted':
repo['trusted'] = opt[1] == 'yes'
else:
repo[opt[0]] = opt[1]
def _set_repo_options(repo, options):
'''
Set the options to the repo.
'''
delimiters = "[", "]"
pattern = '|'.join(map(re.escape, delimiters))
for option in options:
splitted = re.split(pattern, option)
for opt in splitted:
_set_repo_option(repo, opt)
def _create_repo(line, filename):
'''
Create repo
'''
repo = {}
if line.startswith('#'):
repo['enabled'] = False
line = line[1:]
else:
repo['enabled'] = True
cols = salt.utils.args.shlex_split(line.strip())
repo['compressed'] = not cols[0] in 'src'
repo['name'] = cols[1]
repo['uri'] = cols[2]
repo['file'] = os.path.join(OPKG_CONFDIR, filename)
if len(cols) > 3:
_set_repo_options(repo, cols[3:])
return repo
def _read_repos(conf_file, repos, filename, regex):
'''
Read repos from configuration file
'''
for line in conf_file:
line = salt.utils.stringutils.to_unicode(line)
if not regex.search(line):
continue
repo = _create_repo(line, filename)
# do not store duplicated uri's
if repo['uri'] not in repos:
repos[repo['uri']] = [repo]
def list_repos(**kwargs): # pylint: disable=unused-argument
'''
Lists all repos on ``/etc/opkg/*.conf``
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos = {}
regex = re.compile(REPO_REGEXP)
for filename in os.listdir(OPKG_CONFDIR):
if not filename.endswith(".conf"):
continue
with salt.utils.files.fopen(os.path.join(OPKG_CONFDIR, filename)) as conf_file:
_read_repos(conf_file, repos, filename, regex)
return repos
def get_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Display a repo from the ``/etc/opkg/*.conf``
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo repo
'''
repos = list_repos()
if repos:
for source in six.itervalues(repos):
for sub in source:
if sub['name'] == repo:
return sub
return {}
def _del_repo_from_file(repo, filepath):
'''
Remove a repo from filepath
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
regex = re.compile(REPO_REGEXP)
for line in fhandle:
line = salt.utils.stringutils.to_unicode(line)
if regex.search(line):
if line.startswith('#'):
line = line[1:]
cols = salt.utils.args.shlex_split(line.strip())
if repo != cols[1]:
output.append(salt.utils.stringutils.to_str(line))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def _set_trusted_option_if_needed(repostr, trusted):
'''
Set trusted option to repo if needed
'''
if trusted is True:
repostr += ' [trusted=yes]'
elif trusted is False:
repostr += ' [trusted=no]'
return repostr
def _add_new_repo(repo, properties):
'''
Add a new repo entry
'''
repostr = '# ' if not properties.get('enabled') else ''
repostr += 'src/gz ' if properties.get('compressed') else 'src '
if ' ' in repo:
repostr += '"' + repo + '" '
else:
repostr += repo + ' '
repostr += properties.get('uri')
repostr = _set_trusted_option_if_needed(repostr, properties.get('trusted'))
repostr += '\n'
conffile = os.path.join(OPKG_CONFDIR, repo + '.conf')
with salt.utils.files.fopen(conffile, 'a') as fhandle:
fhandle.write(salt.utils.stringutils.to_str(repostr))
def _mod_repo_in_file(repo, repostr, filepath):
'''
Replace a repo entry in filepath with repostr
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
for line in fhandle:
cols = salt.utils.args.shlex_split(
salt.utils.stringutils.to_unicode(line).strip()
)
if repo not in cols:
output.append(line)
else:
output.append(salt.utils.stringutils.to_str(repostr + '\n'))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def del_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Delete a repo from ``/etc/opkg/*.conf``
If the file does not contain any other repo configuration, the file itself
will be deleted.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo repo
'''
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
repos = list_repos()
if repos:
deleted_from = dict()
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
deleted_from[source['file']] = 0
_del_repo_from_file(repo, source['file'])
if deleted_from:
ret = ''
for repository in repos:
source = repos[repository][0]
if source['file'] in deleted_from:
deleted_from[source['file']] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 1 and os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.\n')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
if refresh:
refresh_db()
return ret
return "Repo {0} doesn't exist in the opkg repo lists".format(repo)
def file_list(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
output = file_dict(*packages)
files = []
for package in list(output['packages'].values()):
files.extend(package)
return {'errors': output['errors'], 'files': files}
def file_dict(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
errors = []
ret = {}
cmd_files = ['opkg', 'files']
if not packages:
packages = list(list_pkgs().keys())
for package in packages:
files = []
cmd = cmd_files[:]
cmd.append(package)
out = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
for line in out['stdout'].splitlines():
if line.startswith('/'):
files.append(line)
elif line.startswith(' * '):
errors.append(line[3:])
break
else:
continue
if files:
ret[package] = files
return {'errors': errors, 'packages': ret}
def owner(*paths, **kwargs): # pylint: disable=unused-argument
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.opkg.version`, if a single
path is passed, a string will be returned, and if multiple paths are passed,
a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
cmd_search = ['opkg', 'search']
for path in paths:
cmd = cmd_search[:]
cmd.append(path)
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
if output:
ret[path] = output.split(' - ')[0].strip()
else:
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def version_clean(version):
'''
Clean the version string removing extra data.
There's nothing do to here for nipkg.py, therefore it will always
return the given version.
'''
return version
def check_extra_requirements(pkgname, pkgver):
'''
Check if the installed package already has the given requirements.
There's nothing do to here for nipkg.py, therefore it will always
return True.
'''
return True
|
saltstack/salt
|
salt/modules/opkg.py
|
file_list
|
python
|
def file_list(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
output = file_dict(*packages)
files = []
for package in list(output['packages'].values()):
files.extend(package)
return {'errors': output['errors'], 'files': files}
|
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/opkg.py#L1536-L1554
|
[
"def file_dict(*packages, **kwargs): # pylint: disable=unused-argument\n '''\n List the files that belong to a package, grouped by package. Not\n specifying any packages will return a list of _every_ file on the system's\n package database (not generally recommended).\n\n CLI Examples:\n\n .. code-block:: bash\n\n salt '*' pkg.file_list httpd\n salt '*' pkg.file_list httpd postfix\n salt '*' pkg.file_list\n '''\n errors = []\n ret = {}\n cmd_files = ['opkg', 'files']\n\n if not packages:\n packages = list(list_pkgs().keys())\n\n for package in packages:\n files = []\n cmd = cmd_files[:]\n cmd.append(package)\n out = __salt__['cmd.run_all'](cmd,\n output_loglevel='trace',\n python_shell=False)\n for line in out['stdout'].splitlines():\n if line.startswith('/'):\n files.append(line)\n elif line.startswith(' * '):\n errors.append(line[3:])\n break\n else:\n continue\n if files:\n ret[package] = files\n\n return {'errors': errors, 'packages': ret}\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Opkg
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
.. versionadded: 2016.3.0
.. note::
For version comparison support on opkg < 0.3.4, the ``opkg-utils`` package
must be installed.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import os
import re
import logging
import errno
# Import salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.itertools
import salt.utils.path
import salt.utils.pkg
import salt.utils.stringutils
import salt.utils.versions
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import shlex_quote as _cmd_quote # pylint: disable=import-error
from salt.ext.six.moves import map # pylint: disable=import-error,redefined-builtin
REPO_REGEXP = r'^#?\s*(src|src/gz)\s+([^\s<>]+|"[^<>]+")\s+[^\s<>]+'
OPKG_CONFDIR = '/etc/opkg'
ATTR_MAP = {
'Architecture': 'arch',
'Homepage': 'url',
'Installed-Time': 'install_date_time_t',
'Maintainer': 'packager',
'Package': 'name',
'Section': 'group'
}
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
NILRT_RESTARTCHECK_STATE_PATH = '/var/lib/salt/restartcheck_state'
def _update_nilrt_restart_state():
'''
NILRT systems determine whether to reboot after various package operations
including but not limited to kernel module installs/removals by checking
specific file md5sums & timestamps. These files are touched/modified by
the post-install/post-remove functions of their respective packages.
The opkg module uses this function to store/update those file timestamps
and checksums to be used later by the restartcheck module.
'''
__salt__['cmd.shell']('stat -c %Y /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.timestamp'
.format(NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.md5sum'
.format(NILRT_RESTARTCHECK_STATE_PATH))
# We can't assume nisysapi.ini always exists like modules.dep
nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'
if os.path.exists(nisysapi_path):
__salt__['cmd.shell']('stat -c %Y {0} >{1}/nisysapi.ini.timestamp'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0} >{1}/nisysapi.ini.md5sum'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
# Expert plugin files get added to a conf.d dir, so keep track of the total
# no. of files, their timestamps and content hashes
nisysapi_conf_d_path = "/usr/lib/{0}/nisysapi/conf.d/experts/".format(
'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'
)
if os.path.exists(nisysapi_conf_d_path):
with salt.utils.files.fopen('{0}/sysapi.conf.d.count'.format(
NILRT_RESTARTCHECK_STATE_PATH), 'w') as fcount:
fcount.write(str(len(os.listdir(nisysapi_conf_d_path))))
for fexpert in os.listdir(nisysapi_conf_d_path):
__salt__['cmd.shell']('stat -c %Y {0}/{1} >{2}/{1}.timestamp'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0}/{1} >{2}/{1}.md5sum'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
def _get_restartcheck_result(errors):
'''
Return restartcheck result and append errors (if any) to ``errors``
'''
rs_result = __salt__['restartcheck.restartcheck'](verbose=False)
if isinstance(rs_result, dict) and 'comment' in rs_result:
errors.append(rs_result['comment'])
return rs_result
def _process_restartcheck_result(rs_result, **kwargs):
'''
Check restartcheck output to see if system/service restarts were requested
and take appropriate action.
'''
if 'No packages seem to need to be restarted' in rs_result:
return
reboot_required = False
for rstr in rs_result:
if 'System restart required' in rstr:
_update_nilrt_restart_state()
__salt__['system.set_reboot_required_witnessed']()
reboot_required = True
if kwargs.get('always_restart_services', True) or not reboot_required:
for rstr in rs_result:
if 'System restart required' not in rstr:
service = os.path.join('/etc/init.d', rstr)
if os.path.exists(service):
__salt__['cmd.run']([service, 'restart'])
def __virtual__():
'''
Confirm this module is on a nilrt based system
'''
if __grains__.get('os_family') == 'NILinuxRT':
try:
os.makedirs(NILRT_RESTARTCHECK_STATE_PATH)
except OSError as exc:
if exc.errno != errno.EEXIST:
return False, 'Error creating {0} (-{1}): {2}'.format(
NILRT_RESTARTCHECK_STATE_PATH,
exc.errno,
exc.strerror)
# populate state dir if empty
if not os.listdir(NILRT_RESTARTCHECK_STATE_PATH):
_update_nilrt_restart_state()
return __virtualname__
if os.path.isdir(OPKG_CONFDIR):
return __virtualname__
return False, "Module opkg only works on OpenEmbedded based systems"
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
if not names:
return ''
ret = {}
for name in names:
ret[name] = ''
# Refresh before looking for the latest version available
if refresh:
refresh_db()
cmd = ['opkg', 'list-upgradable']
out = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
try:
name, _oldversion, newversion = line.split(' - ')
if name in names:
ret[name] = newversion
except ValueError:
pass
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = latest_version
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(failhard=False, **kwargs): # pylint: disable=unused-argument
'''
Updates the opkg database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
failhard
If False, return results of failed lines as ``False`` for the package
database that encountered the error.
If True, raise an error with a list of the package databases that
encountered errors.
.. versionadded:: 2018.3.0
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
error_repos = []
cmd = ['opkg', 'update']
# opkg returns a non-zero retcode when there is a failure to refresh
# from one or more repos. Due to this, ignore the retcode.
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True,
redirect_stderr=True)
out = call['stdout']
prev_line = ''
for line in salt.utils.itertools.split(out, '\n'):
if 'Inflating' in line:
key = line.strip().split()[1][:-1]
ret[key] = True
elif 'Updated source' in line:
# Use the previous line.
key = prev_line.strip().split()[1][:-1]
ret[key] = True
elif 'Failed to download' in line:
key = line.strip().split()[5].split(',')[0]
ret[key] = False
error_repos.append(key)
prev_line = line
if failhard and error_repos:
raise CommandExecutionError(
'Error getting repos: {0}'.format(', '.join(error_repos))
)
# On a non-zero exit code where no failed repos were found, raise an
# exception because this appears to be a different kind of error.
if call['retcode'] != 0 and not error_repos:
raise CommandExecutionError(out)
return ret
def _is_testmode(**kwargs):
'''
Returns whether a test mode (noaction) operation was requested.
'''
return bool(kwargs.get('test') or __opts__.get('test'))
def _append_noaction_if_testmode(cmd, **kwargs):
'''
Adds the --noaction flag to the command if it's running in the test mode.
'''
if _is_testmode(**kwargs):
cmd.append('--noaction')
def _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall):
'''
Builds a list of install commands to be executed in sequence in order to process
each of the to_install, to_downgrade, and to_reinstall lists.
'''
cmds = []
if to_install:
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(to_install)
cmds.append(cmd)
if to_downgrade:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-downgrade')
cmd.extend(to_downgrade)
cmds.append(cmd)
if to_reinstall:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-reinstall')
cmd.extend(to_reinstall)
cmds.append(cmd)
return cmds
def _parse_reported_packages_from_install_output(output):
'''
Parses the output of "opkg install" to determine what packages would have been
installed by an operation run with the --noaction flag.
We are looking for lines like:
Installing <package> (<version>) on <target>
or
Upgrading <package> from <oldVersion> to <version> on root
'''
reported_pkgs = {}
install_pattern = re.compile(r'Installing\s(?P<package>.*?)\s\((?P<version>.*?)\)\son\s(?P<target>.*?)')
upgrade_pattern = re.compile(r'Upgrading\s(?P<package>.*?)\sfrom\s(?P<oldVersion>.*?)\sto\s(?P<version>.*?)\son\s(?P<target>.*?)')
for line in salt.utils.itertools.split(output, '\n'):
match = install_pattern.match(line)
if match is None:
match = upgrade_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = match.group('version')
return reported_pkgs
def _execute_install_command(cmd, parse_output, errors, parsed_packages):
'''
Executes a command for the install operation.
If the command fails, its error output will be appended to the errors list.
If the command succeeds and parse_output is true, updated packages will be appended
to the parsed_packages dictionary.
'''
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors.append(out['stderr'])
else:
errors.append(out['stdout'])
elif parse_output:
parsed_packages.update(_parse_reported_packages_from_install_output(out['stdout']))
def install(name=None,
refresh=False,
pkgs=None,
sources=None,
reinstall=False,
**kwargs):
'''
Install the passed package, add refresh=True to update the opkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionadded:: 2017.7.0
reinstall : False
Specifying reinstall=True will use ``opkg install --force-reinstall``
rather than simply ``opkg install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``opkg
install --force-reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2017.7.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of IPK packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
install_recommends
Whether to install the packages marked as recommended. Default is True.
only_upgrade
Only upgrade the packages (disallow downgrades), if they are already
installed. Default is False.
.. versionadded:: 2017.7.0
always_restart_services
Whether to restart services even if a reboot is required. Default is True.
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
refreshdb = salt.utils.data.is_true(refresh)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
cmd_prefix = ['opkg', 'install']
to_install = []
to_reinstall = []
to_downgrade = []
_append_noaction_if_testmode(cmd_prefix, **kwargs)
if not pkg_params:
return {}
elif pkg_type == 'file':
if reinstall:
cmd_prefix.append('--force-reinstall')
if not kwargs.get('only_upgrade', False):
cmd_prefix.append('--force-downgrade')
to_install.extend(pkg_params)
elif pkg_type == 'repository':
if not kwargs.get('install_recommends', True):
cmd_prefix.append('--no-install-recommends')
for pkgname, pkgversion in six.iteritems(pkg_params):
if (name and pkgs is None and kwargs.get('version') and
len(pkg_params) == 1):
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
version_num = pkgversion
if version_num is None:
# Don't allow downgrades if the version
# number is not specified.
if reinstall and pkgname in old:
to_reinstall.append(pkgname)
else:
to_install.append(pkgname)
else:
pkgstr = '{0}={1}'.format(pkgname, version_num)
cver = old.get(pkgname, '')
if reinstall and cver and salt.utils.versions.compare(
ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall.append(pkgstr)
elif not cver or salt.utils.versions.compare(
ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
to_install.append(pkgstr)
else:
if not kwargs.get('only_upgrade', False):
to_downgrade.append(pkgstr)
else:
# This should cause the command to fail.
to_install.append(pkgstr)
cmds = _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall)
if not cmds:
return {}
if refreshdb:
refresh_db()
errors = []
is_testmode = _is_testmode(**kwargs)
test_packages = {}
for cmd in cmds:
_execute_install_command(cmd, is_testmode, errors, test_packages)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if is_testmode:
new = copy.deepcopy(new)
new.update(test_packages)
ret = salt.utils.data.compare_dicts(old, new)
if pkg_type == 'file' and reinstall:
# For file-based packages, prepare 'to_reinstall' to have a list
# of all the package names that may have been reinstalled.
# This way, we could include reinstalled packages in 'ret'.
for pkgfile in to_install:
# Convert from file name to package name.
cmd = ['opkg', 'info', pkgfile]
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] == 0:
# Just need the package name.
pkginfo_dict = _process_info_installed_output(
out['stdout'], []
)
if pkginfo_dict:
to_reinstall.append(list(pkginfo_dict.keys())[0])
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def _parse_reported_packages_from_remove_output(output):
'''
Parses the output of "opkg remove" to determine what packages would have been
removed by an operation run with the --noaction flag.
We are looking for lines like
Removing <package> (<version>) from <Target>...
'''
reported_pkgs = {}
remove_pattern = re.compile(r'Removing\s(?P<package>.*?)\s\((?P<version>.*?)\)\sfrom\s(?P<target>.*?)...')
for line in salt.utils.itertools.split(output, '\n'):
match = remove_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = ''
return reported_pkgs
def remove(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Remove packages using ``opkg remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
remove_dependencies
Remove package and all dependencies
.. versionadded:: 2019.2.0
auto_remove_deps
Remove packages that were installed automatically to satisfy dependencies
.. versionadded:: 2019.2.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
salt '*' pkg.remove pkgs='["foo", "bar"]' remove_dependencies=True auto_remove_deps=True
'''
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 {}
cmd = ['opkg', 'remove']
_append_noaction_if_testmode(cmd, **kwargs)
if kwargs.get('remove_dependencies', False):
cmd.append('--force-removal-of-dependent-packages')
if kwargs.get('auto_remove_deps', False):
cmd.append('--autoremove')
cmd.extend(targets)
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors = [out['stderr']]
else:
errors = [out['stdout']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if _is_testmode(**kwargs):
reportedPkgs = _parse_reported_packages_from_remove_output(out['stdout'])
new = {k: v for k, v in new.items() if k not in reportedPkgs}
ret = salt.utils.data.compare_dicts(old, new)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def purge(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Package purges are not supported by opkg, this function is identical to
:mod:`pkg.remove <salt.modules.opkg.remove>`.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name, pkgs=pkgs)
def upgrade(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
Upgrades all packages via ``opkg upgrade``
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
errors = []
if salt.utils.data.is_true(refresh):
refresh_db()
old = list_pkgs()
cmd = ['opkg', 'upgrade']
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
errors.append(result)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif state != 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = _set_state(target, 'hold')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif state == 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret['comment'] = ('Package {0} is set not to be held.'
.format(target))
else:
result = _set_state(target, 'ok')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def _get_state(pkg):
'''
View package state from the opkg database
Return the state of pkg
'''
cmd = ['opkg', 'status']
cmd.append(pkg)
out = __salt__['cmd.run'](cmd, python_shell=False)
state_flag = ''
for line in salt.utils.itertools.split(out, '\n'):
if line.startswith('Status'):
_status, _state_want, state_flag, _state_status = line.split()
return state_flag
def _set_state(pkg, state):
'''
Change package state on the opkg database
The state can be any of:
- hold
- noprune
- user
- ok
- installed
- unpacked
This command is commonly used to mark a specific package to be held from
being upgraded, that is, to be kept at a certain version.
Returns a dict containing the package name, and the new and old
versions.
'''
ret = {}
valid_states = ('hold', 'noprune', 'user', 'ok', 'installed', 'unpacked')
if state not in valid_states:
raise SaltInvocationError('Invalid state: {0}'.format(state))
oldstate = _get_state(pkg)
cmd = ['opkg', 'flag']
cmd.append(state)
cmd.append(pkg)
_out = __salt__['cmd.run'](cmd, python_shell=False)
# Missing return value check due to opkg issue 160
ret[pkg] = {'old': oldstate,
'new': state}
return ret
def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
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
cmd = ['opkg', 'list-installed']
ret = {}
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
# This is a continuation of package description
if not line or line[0] == ' ':
continue
# This contains package name, version, and description.
# Extract the first two.
pkg_name, pkg_version = line.split(' - ', 2)[:2]
__salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version)
__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 list_upgrades(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
List all available package upgrades.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
ret = {}
if salt.utils.data.is_true(refresh):
refresh_db()
cmd = ['opkg', 'list-upgradable']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
if 'stdout' in call:
comment += call['stdout']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
name, _oldversion, newversion = line.split(' - ')
ret[name] = newversion
return ret
def _convert_to_standard_attr(attr):
'''
Helper function for _process_info_installed_output()
Converts an opkg attribute name to a standard attribute
name which is used across 'pkg' modules.
'''
ret_attr = ATTR_MAP.get(attr, None)
if ret_attr is None:
# All others convert to lowercase
return attr.lower()
return ret_attr
def _process_info_installed_output(out, filter_attrs):
'''
Helper function for info_installed()
Processes stdout output from a single invocation of
'opkg status'.
'''
ret = {}
name = None
attrs = {}
attr = None
for line in salt.utils.itertools.split(out, '\n'):
if line and line[0] == ' ':
# This is a continuation of the last attr
if filter_attrs is None or attr in filter_attrs:
line = line.strip()
if attrs[attr]:
# If attr is empty, don't add leading newline
attrs[attr] += '\n'
attrs[attr] += line
continue
line = line.strip()
if not line:
# Separator between different packages
if name:
ret[name] = attrs
name = None
attrs = {}
attr = None
continue
key, value = line.split(':', 1)
value = value.lstrip()
attr = _convert_to_standard_attr(key)
if attr == 'name':
name = value
elif filter_attrs is None or attr in filter_attrs:
attrs[attr] = value
if name:
ret[name] = attrs
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
.. versionadded:: 2017.7.0
:param names:
Names of the packages to get information about. If none are specified,
will return information for all installed packages.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
arch, conffiles, conflicts, depends, description, filename, group,
install_date_time_t, md5sum, packager, provides, recommends,
replaces, size, source, suggests, url, version
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed
salt '*' pkg.info_installed attr=version,packager
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> attr=version,packager
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,packager
'''
attr = kwargs.pop('attr', None)
if attr is None:
filter_attrs = None
elif isinstance(attr, six.string_types):
filter_attrs = set(attr.split(','))
else:
filter_attrs = set(attr)
ret = {}
if names:
# Specific list of names of installed packages
for name in names:
cmd = ['opkg', 'status', name]
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
else:
# All installed packages
cmd = ['opkg', 'status']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
return ret
def upgrade_available(name, **kwargs): # pylint: disable=unused-argument
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs): # pylint: disable=unused-argument
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2016.3.4
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0' '0.2.4.1-0'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] if ignore_epoch else six.text_type(x)
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
output = __salt__['cmd.run_stdout'](['opkg', '--version'],
output_loglevel='trace',
python_shell=False)
opkg_version = output.split(' ')[2].strip()
if salt.utils.versions.LooseVersion(opkg_version) >= \
salt.utils.versions.LooseVersion('0.3.4'):
cmd_compare = ['opkg', 'compare-versions']
elif salt.utils.path.which('opkg-compare-versions'):
cmd_compare = ['opkg-compare-versions']
else:
log.warning('Unable to find a compare-versions utility installed. Either upgrade opkg to '
'version > 0.3.4 (preferred) or install the older opkg-compare-versions script.')
return None
for oper, ret in (("<<", -1), ("=", 0), (">>", 1)):
cmd = cmd_compare[:]
cmd.append(_cmd_quote(pkg1))
cmd.append(oper)
cmd.append(_cmd_quote(pkg2))
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
ignore_retcode=True,
python_shell=False)
if retcode == 0:
return ret
return None
def _set_repo_option(repo, option):
'''
Set the option to repo
'''
if not option:
return
opt = option.split('=')
if len(opt) != 2:
return
if opt[0] == 'trusted':
repo['trusted'] = opt[1] == 'yes'
else:
repo[opt[0]] = opt[1]
def _set_repo_options(repo, options):
'''
Set the options to the repo.
'''
delimiters = "[", "]"
pattern = '|'.join(map(re.escape, delimiters))
for option in options:
splitted = re.split(pattern, option)
for opt in splitted:
_set_repo_option(repo, opt)
def _create_repo(line, filename):
'''
Create repo
'''
repo = {}
if line.startswith('#'):
repo['enabled'] = False
line = line[1:]
else:
repo['enabled'] = True
cols = salt.utils.args.shlex_split(line.strip())
repo['compressed'] = not cols[0] in 'src'
repo['name'] = cols[1]
repo['uri'] = cols[2]
repo['file'] = os.path.join(OPKG_CONFDIR, filename)
if len(cols) > 3:
_set_repo_options(repo, cols[3:])
return repo
def _read_repos(conf_file, repos, filename, regex):
'''
Read repos from configuration file
'''
for line in conf_file:
line = salt.utils.stringutils.to_unicode(line)
if not regex.search(line):
continue
repo = _create_repo(line, filename)
# do not store duplicated uri's
if repo['uri'] not in repos:
repos[repo['uri']] = [repo]
def list_repos(**kwargs): # pylint: disable=unused-argument
'''
Lists all repos on ``/etc/opkg/*.conf``
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos = {}
regex = re.compile(REPO_REGEXP)
for filename in os.listdir(OPKG_CONFDIR):
if not filename.endswith(".conf"):
continue
with salt.utils.files.fopen(os.path.join(OPKG_CONFDIR, filename)) as conf_file:
_read_repos(conf_file, repos, filename, regex)
return repos
def get_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Display a repo from the ``/etc/opkg/*.conf``
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo repo
'''
repos = list_repos()
if repos:
for source in six.itervalues(repos):
for sub in source:
if sub['name'] == repo:
return sub
return {}
def _del_repo_from_file(repo, filepath):
'''
Remove a repo from filepath
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
regex = re.compile(REPO_REGEXP)
for line in fhandle:
line = salt.utils.stringutils.to_unicode(line)
if regex.search(line):
if line.startswith('#'):
line = line[1:]
cols = salt.utils.args.shlex_split(line.strip())
if repo != cols[1]:
output.append(salt.utils.stringutils.to_str(line))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def _set_trusted_option_if_needed(repostr, trusted):
'''
Set trusted option to repo if needed
'''
if trusted is True:
repostr += ' [trusted=yes]'
elif trusted is False:
repostr += ' [trusted=no]'
return repostr
def _add_new_repo(repo, properties):
'''
Add a new repo entry
'''
repostr = '# ' if not properties.get('enabled') else ''
repostr += 'src/gz ' if properties.get('compressed') else 'src '
if ' ' in repo:
repostr += '"' + repo + '" '
else:
repostr += repo + ' '
repostr += properties.get('uri')
repostr = _set_trusted_option_if_needed(repostr, properties.get('trusted'))
repostr += '\n'
conffile = os.path.join(OPKG_CONFDIR, repo + '.conf')
with salt.utils.files.fopen(conffile, 'a') as fhandle:
fhandle.write(salt.utils.stringutils.to_str(repostr))
def _mod_repo_in_file(repo, repostr, filepath):
'''
Replace a repo entry in filepath with repostr
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
for line in fhandle:
cols = salt.utils.args.shlex_split(
salt.utils.stringutils.to_unicode(line).strip()
)
if repo not in cols:
output.append(line)
else:
output.append(salt.utils.stringutils.to_str(repostr + '\n'))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def del_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Delete a repo from ``/etc/opkg/*.conf``
If the file does not contain any other repo configuration, the file itself
will be deleted.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo repo
'''
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
repos = list_repos()
if repos:
deleted_from = dict()
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
deleted_from[source['file']] = 0
_del_repo_from_file(repo, source['file'])
if deleted_from:
ret = ''
for repository in repos:
source = repos[repository][0]
if source['file'] in deleted_from:
deleted_from[source['file']] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 1 and os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.\n')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
if refresh:
refresh_db()
return ret
return "Repo {0} doesn't exist in the opkg repo lists".format(repo)
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as uri is defined.
The following options are available to modify a repo definition:
repo
alias by which opkg refers to the repo.
uri
the URI to the repo.
compressed
defines (True or False) if the index file is compressed
enabled
enable or disable (True or False) repository
but do not remove if disabled.
refresh
enable or disable (True or False) auto-refresh of the repositories
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo repo uri=http://new/uri
salt '*' pkg.mod_repo repo enabled=False
'''
repos = list_repos()
found = False
uri = ''
if 'uri' in kwargs:
uri = kwargs['uri']
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
found = True
repostr = ''
if 'enabled' in kwargs and not kwargs['enabled']:
repostr += '# '
if 'compressed' in kwargs:
repostr += 'src/gz ' if kwargs['compressed'] else 'src'
else:
repostr += 'src/gz' if source['compressed'] else 'src'
repo_alias = kwargs['alias'] if 'alias' in kwargs else repo
if ' ' in repo_alias:
repostr += ' "{0}"'.format(repo_alias)
else:
repostr += ' {0}'.format(repo_alias)
repostr += ' {0}'.format(kwargs['uri'] if 'uri' in kwargs else source['uri'])
trusted = kwargs.get('trusted')
repostr = _set_trusted_option_if_needed(repostr, trusted) if trusted is not None else \
_set_trusted_option_if_needed(repostr, source.get('trusted'))
_mod_repo_in_file(repo, repostr, source['file'])
elif uri and source['uri'] == uri:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(uri, source['name']))
if not found:
# Need to add a new repo
if 'uri' not in kwargs:
raise CommandExecutionError(
'Repository \'{0}\' not found and no URI passed to create one.'.format(repo))
properties = {'uri': kwargs['uri']}
# If compressed is not defined, assume True
properties['compressed'] = kwargs['compressed'] if 'compressed' in kwargs else True
# If enabled is not defined, assume True
properties['enabled'] = kwargs['enabled'] if 'enabled' in kwargs else True
properties['trusted'] = kwargs.get('trusted')
_add_new_repo(repo, properties)
if 'refresh' in kwargs:
refresh_db()
def file_dict(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
errors = []
ret = {}
cmd_files = ['opkg', 'files']
if not packages:
packages = list(list_pkgs().keys())
for package in packages:
files = []
cmd = cmd_files[:]
cmd.append(package)
out = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
for line in out['stdout'].splitlines():
if line.startswith('/'):
files.append(line)
elif line.startswith(' * '):
errors.append(line[3:])
break
else:
continue
if files:
ret[package] = files
return {'errors': errors, 'packages': ret}
def owner(*paths, **kwargs): # pylint: disable=unused-argument
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.opkg.version`, if a single
path is passed, a string will be returned, and if multiple paths are passed,
a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
cmd_search = ['opkg', 'search']
for path in paths:
cmd = cmd_search[:]
cmd.append(path)
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
if output:
ret[path] = output.split(' - ')[0].strip()
else:
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def version_clean(version):
'''
Clean the version string removing extra data.
There's nothing do to here for nipkg.py, therefore it will always
return the given version.
'''
return version
def check_extra_requirements(pkgname, pkgver):
'''
Check if the installed package already has the given requirements.
There's nothing do to here for nipkg.py, therefore it will always
return True.
'''
return True
|
saltstack/salt
|
salt/modules/opkg.py
|
file_dict
|
python
|
def file_dict(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
errors = []
ret = {}
cmd_files = ['opkg', 'files']
if not packages:
packages = list(list_pkgs().keys())
for package in packages:
files = []
cmd = cmd_files[:]
cmd.append(package)
out = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
for line in out['stdout'].splitlines():
if line.startswith('/'):
files.append(line)
elif line.startswith(' * '):
errors.append(line[3:])
break
else:
continue
if files:
ret[package] = files
return {'errors': errors, 'packages': ret}
|
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
|
train
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/opkg.py#L1557-L1596
|
[
"def list_pkgs(versions_as_list=False, **kwargs):\n '''\n List the packages currently installed in a dict::\n\n {'<package_name>': '<version>'}\n\n CLI Example:\n\n .. code-block:: bash\n\n salt '*' pkg.list_pkgs\n salt '*' pkg.list_pkgs versions_as_list=True\n '''\n versions_as_list = salt.utils.data.is_true(versions_as_list)\n # not yet implemented or not applicable\n if any([salt.utils.data.is_true(kwargs.get(x))\n for x in ('removed', 'purge_desired')]):\n return {}\n\n if 'pkg.list_pkgs' in __context__:\n if versions_as_list:\n return __context__['pkg.list_pkgs']\n else:\n ret = copy.deepcopy(__context__['pkg.list_pkgs'])\n __salt__['pkg_resource.stringify'](ret)\n return ret\n\n cmd = ['opkg', 'list-installed']\n ret = {}\n out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)\n for line in salt.utils.itertools.split(out, '\\n'):\n # This is a continuation of package description\n if not line or line[0] == ' ':\n continue\n\n # This contains package name, version, and description.\n # Extract the first two.\n pkg_name, pkg_version = line.split(' - ', 2)[:2]\n __salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version)\n\n __salt__['pkg_resource.sort_pkglist'](ret)\n __context__['pkg.list_pkgs'] = copy.deepcopy(ret)\n if not versions_as_list:\n __salt__['pkg_resource.stringify'](ret)\n return ret\n"
] |
# -*- coding: utf-8 -*-
'''
Support for Opkg
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
.. versionadded: 2016.3.0
.. note::
For version comparison support on opkg < 0.3.4, the ``opkg-utils`` package
must be installed.
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import os
import re
import logging
import errno
# Import salt libs
import salt.utils.args
import salt.utils.data
import salt.utils.files
import salt.utils.itertools
import salt.utils.path
import salt.utils.pkg
import salt.utils.stringutils
import salt.utils.versions
from salt.exceptions import (
CommandExecutionError, MinionError, SaltInvocationError
)
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import shlex_quote as _cmd_quote # pylint: disable=import-error
from salt.ext.six.moves import map # pylint: disable=import-error,redefined-builtin
REPO_REGEXP = r'^#?\s*(src|src/gz)\s+([^\s<>]+|"[^<>]+")\s+[^\s<>]+'
OPKG_CONFDIR = '/etc/opkg'
ATTR_MAP = {
'Architecture': 'arch',
'Homepage': 'url',
'Installed-Time': 'install_date_time_t',
'Maintainer': 'packager',
'Package': 'name',
'Section': 'group'
}
log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'pkg'
NILRT_RESTARTCHECK_STATE_PATH = '/var/lib/salt/restartcheck_state'
def _update_nilrt_restart_state():
'''
NILRT systems determine whether to reboot after various package operations
including but not limited to kernel module installs/removals by checking
specific file md5sums & timestamps. These files are touched/modified by
the post-install/post-remove functions of their respective packages.
The opkg module uses this function to store/update those file timestamps
and checksums to be used later by the restartcheck module.
'''
__salt__['cmd.shell']('stat -c %Y /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.timestamp'
.format(NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum /lib/modules/$(uname -r)/modules.dep >{0}/modules.dep.md5sum'
.format(NILRT_RESTARTCHECK_STATE_PATH))
# We can't assume nisysapi.ini always exists like modules.dep
nisysapi_path = '/usr/local/natinst/share/nisysapi.ini'
if os.path.exists(nisysapi_path):
__salt__['cmd.shell']('stat -c %Y {0} >{1}/nisysapi.ini.timestamp'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0} >{1}/nisysapi.ini.md5sum'
.format(nisysapi_path, NILRT_RESTARTCHECK_STATE_PATH))
# Expert plugin files get added to a conf.d dir, so keep track of the total
# no. of files, their timestamps and content hashes
nisysapi_conf_d_path = "/usr/lib/{0}/nisysapi/conf.d/experts/".format(
'arm-linux-gnueabi' if 'arm' in __grains__.get('cpuarch') else 'x86_64-linux-gnu'
)
if os.path.exists(nisysapi_conf_d_path):
with salt.utils.files.fopen('{0}/sysapi.conf.d.count'.format(
NILRT_RESTARTCHECK_STATE_PATH), 'w') as fcount:
fcount.write(str(len(os.listdir(nisysapi_conf_d_path))))
for fexpert in os.listdir(nisysapi_conf_d_path):
__salt__['cmd.shell']('stat -c %Y {0}/{1} >{2}/{1}.timestamp'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
__salt__['cmd.shell']('md5sum {0}/{1} >{2}/{1}.md5sum'
.format(nisysapi_conf_d_path,
fexpert,
NILRT_RESTARTCHECK_STATE_PATH))
def _get_restartcheck_result(errors):
'''
Return restartcheck result and append errors (if any) to ``errors``
'''
rs_result = __salt__['restartcheck.restartcheck'](verbose=False)
if isinstance(rs_result, dict) and 'comment' in rs_result:
errors.append(rs_result['comment'])
return rs_result
def _process_restartcheck_result(rs_result, **kwargs):
'''
Check restartcheck output to see if system/service restarts were requested
and take appropriate action.
'''
if 'No packages seem to need to be restarted' in rs_result:
return
reboot_required = False
for rstr in rs_result:
if 'System restart required' in rstr:
_update_nilrt_restart_state()
__salt__['system.set_reboot_required_witnessed']()
reboot_required = True
if kwargs.get('always_restart_services', True) or not reboot_required:
for rstr in rs_result:
if 'System restart required' not in rstr:
service = os.path.join('/etc/init.d', rstr)
if os.path.exists(service):
__salt__['cmd.run']([service, 'restart'])
def __virtual__():
'''
Confirm this module is on a nilrt based system
'''
if __grains__.get('os_family') == 'NILinuxRT':
try:
os.makedirs(NILRT_RESTARTCHECK_STATE_PATH)
except OSError as exc:
if exc.errno != errno.EEXIST:
return False, 'Error creating {0} (-{1}): {2}'.format(
NILRT_RESTARTCHECK_STATE_PATH,
exc.errno,
exc.strerror)
# populate state dir if empty
if not os.listdir(NILRT_RESTARTCHECK_STATE_PATH):
_update_nilrt_restart_state()
return __virtualname__
if os.path.isdir(OPKG_CONFDIR):
return __virtualname__
return False, "Module opkg only works on OpenEmbedded based systems"
def latest_version(*names, **kwargs):
'''
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package1> <package2> <package3> ...
'''
refresh = salt.utils.data.is_true(kwargs.pop('refresh', True))
if not names:
return ''
ret = {}
for name in names:
ret[name] = ''
# Refresh before looking for the latest version available
if refresh:
refresh_db()
cmd = ['opkg', 'list-upgradable']
out = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
try:
name, _oldversion, newversion = line.split(' - ')
if name in names:
ret[name] = newversion
except ValueError:
pass
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = latest_version
def version(*names, **kwargs):
'''
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
'''
return __salt__['pkg_resource.version'](*names, **kwargs)
def refresh_db(failhard=False, **kwargs): # pylint: disable=unused-argument
'''
Updates the opkg database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
failhard
If False, return results of failed lines as ``False`` for the package
database that encountered the error.
If True, raise an error with a list of the package databases that
encountered errors.
.. versionadded:: 2018.3.0
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
'''
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
ret = {}
error_repos = []
cmd = ['opkg', 'update']
# opkg returns a non-zero retcode when there is a failure to refresh
# from one or more repos. Due to this, ignore the retcode.
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False,
ignore_retcode=True,
redirect_stderr=True)
out = call['stdout']
prev_line = ''
for line in salt.utils.itertools.split(out, '\n'):
if 'Inflating' in line:
key = line.strip().split()[1][:-1]
ret[key] = True
elif 'Updated source' in line:
# Use the previous line.
key = prev_line.strip().split()[1][:-1]
ret[key] = True
elif 'Failed to download' in line:
key = line.strip().split()[5].split(',')[0]
ret[key] = False
error_repos.append(key)
prev_line = line
if failhard and error_repos:
raise CommandExecutionError(
'Error getting repos: {0}'.format(', '.join(error_repos))
)
# On a non-zero exit code where no failed repos were found, raise an
# exception because this appears to be a different kind of error.
if call['retcode'] != 0 and not error_repos:
raise CommandExecutionError(out)
return ret
def _is_testmode(**kwargs):
'''
Returns whether a test mode (noaction) operation was requested.
'''
return bool(kwargs.get('test') or __opts__.get('test'))
def _append_noaction_if_testmode(cmd, **kwargs):
'''
Adds the --noaction flag to the command if it's running in the test mode.
'''
if _is_testmode(**kwargs):
cmd.append('--noaction')
def _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall):
'''
Builds a list of install commands to be executed in sequence in order to process
each of the to_install, to_downgrade, and to_reinstall lists.
'''
cmds = []
if to_install:
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(to_install)
cmds.append(cmd)
if to_downgrade:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-downgrade')
cmd.extend(to_downgrade)
cmds.append(cmd)
if to_reinstall:
cmd = copy.deepcopy(cmd_prefix)
cmd.append('--force-reinstall')
cmd.extend(to_reinstall)
cmds.append(cmd)
return cmds
def _parse_reported_packages_from_install_output(output):
'''
Parses the output of "opkg install" to determine what packages would have been
installed by an operation run with the --noaction flag.
We are looking for lines like:
Installing <package> (<version>) on <target>
or
Upgrading <package> from <oldVersion> to <version> on root
'''
reported_pkgs = {}
install_pattern = re.compile(r'Installing\s(?P<package>.*?)\s\((?P<version>.*?)\)\son\s(?P<target>.*?)')
upgrade_pattern = re.compile(r'Upgrading\s(?P<package>.*?)\sfrom\s(?P<oldVersion>.*?)\sto\s(?P<version>.*?)\son\s(?P<target>.*?)')
for line in salt.utils.itertools.split(output, '\n'):
match = install_pattern.match(line)
if match is None:
match = upgrade_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = match.group('version')
return reported_pkgs
def _execute_install_command(cmd, parse_output, errors, parsed_packages):
'''
Executes a command for the install operation.
If the command fails, its error output will be appended to the errors list.
If the command succeeds and parse_output is true, updated packages will be appended
to the parsed_packages dictionary.
'''
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors.append(out['stderr'])
else:
errors.append(out['stdout'])
elif parse_output:
parsed_packages.update(_parse_reported_packages_from_install_output(out['stdout']))
def install(name=None,
refresh=False,
pkgs=None,
sources=None,
reinstall=False,
**kwargs):
'''
Install the passed package, add refresh=True to update the opkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
version
Install a specific version of the package, e.g. 1.2.3~0ubuntu0. Ignored
if "pkgs" or "sources" is passed.
.. versionadded:: 2017.7.0
reinstall : False
Specifying reinstall=True will use ``opkg install --force-reinstall``
rather than simply ``opkg install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``opkg
install --force-reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2017.7.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "1.2.3-0ubuntu0"}]'
sources
A list of IPK packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
install_recommends
Whether to install the packages marked as recommended. Default is True.
only_upgrade
Only upgrade the packages (disallow downgrades), if they are already
installed. Default is False.
.. versionadded:: 2017.7.0
always_restart_services
Whether to restart services even if a reboot is required. Default is True.
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
'''
refreshdb = salt.utils.data.is_true(refresh)
try:
pkg_params, pkg_type = __salt__['pkg_resource.parse_targets'](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
cmd_prefix = ['opkg', 'install']
to_install = []
to_reinstall = []
to_downgrade = []
_append_noaction_if_testmode(cmd_prefix, **kwargs)
if not pkg_params:
return {}
elif pkg_type == 'file':
if reinstall:
cmd_prefix.append('--force-reinstall')
if not kwargs.get('only_upgrade', False):
cmd_prefix.append('--force-downgrade')
to_install.extend(pkg_params)
elif pkg_type == 'repository':
if not kwargs.get('install_recommends', True):
cmd_prefix.append('--no-install-recommends')
for pkgname, pkgversion in six.iteritems(pkg_params):
if (name and pkgs is None and kwargs.get('version') and
len(pkg_params) == 1):
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs['version']
else:
version_num = pkgversion
if version_num is None:
# Don't allow downgrades if the version
# number is not specified.
if reinstall and pkgname in old:
to_reinstall.append(pkgname)
else:
to_install.append(pkgname)
else:
pkgstr = '{0}={1}'.format(pkgname, version_num)
cver = old.get(pkgname, '')
if reinstall and cver and salt.utils.versions.compare(
ver1=version_num,
oper='==',
ver2=cver,
cmp_func=version_cmp):
to_reinstall.append(pkgstr)
elif not cver or salt.utils.versions.compare(
ver1=version_num,
oper='>=',
ver2=cver,
cmp_func=version_cmp):
to_install.append(pkgstr)
else:
if not kwargs.get('only_upgrade', False):
to_downgrade.append(pkgstr)
else:
# This should cause the command to fail.
to_install.append(pkgstr)
cmds = _build_install_command_list(cmd_prefix, to_install, to_downgrade, to_reinstall)
if not cmds:
return {}
if refreshdb:
refresh_db()
errors = []
is_testmode = _is_testmode(**kwargs)
test_packages = {}
for cmd in cmds:
_execute_install_command(cmd, is_testmode, errors, test_packages)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if is_testmode:
new = copy.deepcopy(new)
new.update(test_packages)
ret = salt.utils.data.compare_dicts(old, new)
if pkg_type == 'file' and reinstall:
# For file-based packages, prepare 'to_reinstall' to have a list
# of all the package names that may have been reinstalled.
# This way, we could include reinstalled packages in 'ret'.
for pkgfile in to_install:
# Convert from file name to package name.
cmd = ['opkg', 'info', pkgfile]
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] == 0:
# Just need the package name.
pkginfo_dict = _process_info_installed_output(
out['stdout'], []
)
if pkginfo_dict:
to_reinstall.append(list(pkginfo_dict.keys())[0])
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update({pkgname: {'old': old.get(pkgname, ''),
'new': new.get(pkgname, '')}})
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered installing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def _parse_reported_packages_from_remove_output(output):
'''
Parses the output of "opkg remove" to determine what packages would have been
removed by an operation run with the --noaction flag.
We are looking for lines like
Removing <package> (<version>) from <Target>...
'''
reported_pkgs = {}
remove_pattern = re.compile(r'Removing\s(?P<package>.*?)\s\((?P<version>.*?)\)\sfrom\s(?P<target>.*?)...')
for line in salt.utils.itertools.split(output, '\n'):
match = remove_pattern.match(line)
if match:
reported_pkgs[match.group('package')] = ''
return reported_pkgs
def remove(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Remove packages using ``opkg remove``.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
remove_dependencies
Remove package and all dependencies
.. versionadded:: 2019.2.0
auto_remove_deps
Remove packages that were installed automatically to satisfy dependencies
.. versionadded:: 2019.2.0
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.remove <package name>
salt '*' pkg.remove <package1>,<package2>,<package3>
salt '*' pkg.remove pkgs='["foo", "bar"]'
salt '*' pkg.remove pkgs='["foo", "bar"]' remove_dependencies=True auto_remove_deps=True
'''
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 {}
cmd = ['opkg', 'remove']
_append_noaction_if_testmode(cmd, **kwargs)
if kwargs.get('remove_dependencies', False):
cmd.append('--force-removal-of-dependent-packages')
if kwargs.get('auto_remove_deps', False):
cmd.append('--autoremove')
cmd.extend(targets)
out = __salt__['cmd.run_all'](
cmd,
output_loglevel='trace',
python_shell=False
)
if out['retcode'] != 0:
if out['stderr']:
errors = [out['stderr']]
else:
errors = [out['stdout']]
else:
errors = []
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
if _is_testmode(**kwargs):
reportedPkgs = _parse_reported_packages_from_remove_output(out['stdout'])
new = {k: v for k, v in new.items() if k not in reportedPkgs}
ret = salt.utils.data.compare_dicts(old, new)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered removing package(s)',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def purge(name=None, pkgs=None, **kwargs): # pylint: disable=unused-argument
'''
Package purges are not supported by opkg, this function is identical to
:mod:`pkg.remove <salt.modules.opkg.remove>`.
name
The name of the package to be deleted.
Multiple Package Options:
pkgs
A list of packages to delete. Must be passed as a python list. The
``name`` parameter will be ignored if this option is passed.
Returns a dict containing the changes.
CLI Example:
.. code-block:: bash
salt '*' pkg.purge <package name>
salt '*' pkg.purge <package1>,<package2>,<package3>
salt '*' pkg.purge pkgs='["foo", "bar"]'
'''
return remove(name=name, pkgs=pkgs)
def upgrade(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
Upgrades all packages via ``opkg upgrade``
Returns a dictionary containing the changes:
.. code-block:: python
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade
'''
ret = {'changes': {},
'result': True,
'comment': '',
}
errors = []
if salt.utils.data.is_true(refresh):
refresh_db()
old = list_pkgs()
cmd = ['opkg', 'upgrade']
result = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
__context__.pop('pkg.list_pkgs', None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
if result['retcode'] != 0:
errors.append(result)
rs_result = _get_restartcheck_result(errors)
if errors:
raise CommandExecutionError(
'Problem encountered upgrading packages',
info={'errors': errors, 'changes': ret}
)
_process_restartcheck_result(rs_result, **kwargs)
return ret
def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package in 'hold' state, meaning it will not be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.hold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.hold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} not currently held.'
.format(target))
elif state != 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret[target]['comment'] = ('Package {0} is set to be held.'
.format(target))
else:
result = _set_state(target, 'hold')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is now being held.'
.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set to be held.'
.format(target))
return ret
def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
'''
Set package current in 'hold' state to install state,
meaning it will be upgraded.
name
The name of the package, e.g., 'tmux'
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold <package name>
pkgs
A list of packages to hold. Must be passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.unhold pkgs='["foo", "bar"]'
'''
if not name and not pkgs and not sources:
raise SaltInvocationError(
'One of name, pkgs, or sources must be specified.'
)
if pkgs and sources:
raise SaltInvocationError(
'Only one of pkgs or sources can be specified.'
)
targets = []
if pkgs:
targets.extend(pkgs)
elif sources:
for source in sources:
targets.append(next(iter(source)))
else:
targets.append(name)
ret = {}
for target in targets:
if isinstance(target, dict):
target = next(iter(target))
ret[target] = {'name': target,
'changes': {},
'result': False,
'comment': ''}
state = _get_state(target)
if not state:
ret[target]['comment'] = ('Package {0} does not have a state.'
.format(target))
elif state == 'hold':
if 'test' in __opts__ and __opts__['test']:
ret[target].update(result=None)
ret['comment'] = ('Package {0} is set not to be held.'
.format(target))
else:
result = _set_state(target, 'ok')
ret[target].update(changes=result[target], result=True)
ret[target]['comment'] = ('Package {0} is no longer being '
'held.'.format(target))
else:
ret[target].update(result=True)
ret[target]['comment'] = ('Package {0} is already set not to be '
'held.'.format(target))
return ret
def _get_state(pkg):
'''
View package state from the opkg database
Return the state of pkg
'''
cmd = ['opkg', 'status']
cmd.append(pkg)
out = __salt__['cmd.run'](cmd, python_shell=False)
state_flag = ''
for line in salt.utils.itertools.split(out, '\n'):
if line.startswith('Status'):
_status, _state_want, state_flag, _state_status = line.split()
return state_flag
def _set_state(pkg, state):
'''
Change package state on the opkg database
The state can be any of:
- hold
- noprune
- user
- ok
- installed
- unpacked
This command is commonly used to mark a specific package to be held from
being upgraded, that is, to be kept at a certain version.
Returns a dict containing the package name, and the new and old
versions.
'''
ret = {}
valid_states = ('hold', 'noprune', 'user', 'ok', 'installed', 'unpacked')
if state not in valid_states:
raise SaltInvocationError('Invalid state: {0}'.format(state))
oldstate = _get_state(pkg)
cmd = ['opkg', 'flag']
cmd.append(state)
cmd.append(pkg)
_out = __salt__['cmd.run'](cmd, python_shell=False)
# Missing return value check due to opkg issue 160
ret[pkg] = {'old': oldstate,
'new': state}
return ret
def list_pkgs(versions_as_list=False, **kwargs):
'''
List the packages currently installed in a dict::
{'<package_name>': '<version>'}
CLI Example:
.. code-block:: bash
salt '*' pkg.list_pkgs
salt '*' pkg.list_pkgs versions_as_list=True
'''
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
cmd = ['opkg', 'list-installed']
ret = {}
out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
for line in salt.utils.itertools.split(out, '\n'):
# This is a continuation of package description
if not line or line[0] == ' ':
continue
# This contains package name, version, and description.
# Extract the first two.
pkg_name, pkg_version = line.split(' - ', 2)[:2]
__salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version)
__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 list_upgrades(refresh=True, **kwargs): # pylint: disable=unused-argument
'''
List all available package upgrades.
CLI Example:
.. code-block:: bash
salt '*' pkg.list_upgrades
'''
ret = {}
if salt.utils.data.is_true(refresh):
refresh_db()
cmd = ['opkg', 'list-upgradable']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if 'stderr' in call:
comment += call['stderr']
if 'stdout' in call:
comment += call['stdout']
raise CommandExecutionError(comment)
else:
out = call['stdout']
for line in out.splitlines():
name, _oldversion, newversion = line.split(' - ')
ret[name] = newversion
return ret
def _convert_to_standard_attr(attr):
'''
Helper function for _process_info_installed_output()
Converts an opkg attribute name to a standard attribute
name which is used across 'pkg' modules.
'''
ret_attr = ATTR_MAP.get(attr, None)
if ret_attr is None:
# All others convert to lowercase
return attr.lower()
return ret_attr
def _process_info_installed_output(out, filter_attrs):
'''
Helper function for info_installed()
Processes stdout output from a single invocation of
'opkg status'.
'''
ret = {}
name = None
attrs = {}
attr = None
for line in salt.utils.itertools.split(out, '\n'):
if line and line[0] == ' ':
# This is a continuation of the last attr
if filter_attrs is None or attr in filter_attrs:
line = line.strip()
if attrs[attr]:
# If attr is empty, don't add leading newline
attrs[attr] += '\n'
attrs[attr] += line
continue
line = line.strip()
if not line:
# Separator between different packages
if name:
ret[name] = attrs
name = None
attrs = {}
attr = None
continue
key, value = line.split(':', 1)
value = value.lstrip()
attr = _convert_to_standard_attr(key)
if attr == 'name':
name = value
elif filter_attrs is None or attr in filter_attrs:
attrs[attr] = value
if name:
ret[name] = attrs
return ret
def info_installed(*names, **kwargs):
'''
Return the information of the named package(s), installed on the system.
.. versionadded:: 2017.7.0
:param names:
Names of the packages to get information about. If none are specified,
will return information for all installed packages.
:param attr:
Comma-separated package attributes. If no 'attr' is specified, all available attributes returned.
Valid attributes are:
arch, conffiles, conflicts, depends, description, filename, group,
install_date_time_t, md5sum, packager, provides, recommends,
replaces, size, source, suggests, url, version
CLI example:
.. code-block:: bash
salt '*' pkg.info_installed
salt '*' pkg.info_installed attr=version,packager
salt '*' pkg.info_installed <package1>
salt '*' pkg.info_installed <package1> <package2> <package3> ...
salt '*' pkg.info_installed <package1> attr=version,packager
salt '*' pkg.info_installed <package1> <package2> <package3> ... attr=version,packager
'''
attr = kwargs.pop('attr', None)
if attr is None:
filter_attrs = None
elif isinstance(attr, six.string_types):
filter_attrs = set(attr.split(','))
else:
filter_attrs = set(attr)
ret = {}
if names:
# Specific list of names of installed packages
for name in names:
cmd = ['opkg', 'status', name]
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
else:
# All installed packages
cmd = ['opkg', 'status']
call = __salt__['cmd.run_all'](cmd,
output_loglevel='trace',
python_shell=False)
if call['retcode'] != 0:
comment = ''
if call['stderr']:
comment += call['stderr']
else:
comment += call['stdout']
raise CommandExecutionError(comment)
ret.update(_process_info_installed_output(call['stdout'], filter_attrs))
return ret
def upgrade_available(name, **kwargs): # pylint: disable=unused-argument
'''
Check whether or not an upgrade is available for a given package
CLI Example:
.. code-block:: bash
salt '*' pkg.upgrade_available <package name>
'''
return latest_version(name) != ''
def version_cmp(pkg1, pkg2, ignore_epoch=False, **kwargs): # pylint: disable=unused-argument
'''
Do a cmp-style comparison on two packages. Return -1 if pkg1 < pkg2, 0 if
pkg1 == pkg2, and 1 if pkg1 > pkg2. Return None if there was a problem
making the comparison.
ignore_epoch : False
Set to ``True`` to ignore the epoch when comparing versions
.. versionadded:: 2016.3.4
CLI Example:
.. code-block:: bash
salt '*' pkg.version_cmp '0.2.4-0' '0.2.4.1-0'
'''
normalize = lambda x: six.text_type(x).split(':', 1)[-1] if ignore_epoch else six.text_type(x)
pkg1 = normalize(pkg1)
pkg2 = normalize(pkg2)
output = __salt__['cmd.run_stdout'](['opkg', '--version'],
output_loglevel='trace',
python_shell=False)
opkg_version = output.split(' ')[2].strip()
if salt.utils.versions.LooseVersion(opkg_version) >= \
salt.utils.versions.LooseVersion('0.3.4'):
cmd_compare = ['opkg', 'compare-versions']
elif salt.utils.path.which('opkg-compare-versions'):
cmd_compare = ['opkg-compare-versions']
else:
log.warning('Unable to find a compare-versions utility installed. Either upgrade opkg to '
'version > 0.3.4 (preferred) or install the older opkg-compare-versions script.')
return None
for oper, ret in (("<<", -1), ("=", 0), (">>", 1)):
cmd = cmd_compare[:]
cmd.append(_cmd_quote(pkg1))
cmd.append(oper)
cmd.append(_cmd_quote(pkg2))
retcode = __salt__['cmd.retcode'](cmd,
output_loglevel='trace',
ignore_retcode=True,
python_shell=False)
if retcode == 0:
return ret
return None
def _set_repo_option(repo, option):
'''
Set the option to repo
'''
if not option:
return
opt = option.split('=')
if len(opt) != 2:
return
if opt[0] == 'trusted':
repo['trusted'] = opt[1] == 'yes'
else:
repo[opt[0]] = opt[1]
def _set_repo_options(repo, options):
'''
Set the options to the repo.
'''
delimiters = "[", "]"
pattern = '|'.join(map(re.escape, delimiters))
for option in options:
splitted = re.split(pattern, option)
for opt in splitted:
_set_repo_option(repo, opt)
def _create_repo(line, filename):
'''
Create repo
'''
repo = {}
if line.startswith('#'):
repo['enabled'] = False
line = line[1:]
else:
repo['enabled'] = True
cols = salt.utils.args.shlex_split(line.strip())
repo['compressed'] = not cols[0] in 'src'
repo['name'] = cols[1]
repo['uri'] = cols[2]
repo['file'] = os.path.join(OPKG_CONFDIR, filename)
if len(cols) > 3:
_set_repo_options(repo, cols[3:])
return repo
def _read_repos(conf_file, repos, filename, regex):
'''
Read repos from configuration file
'''
for line in conf_file:
line = salt.utils.stringutils.to_unicode(line)
if not regex.search(line):
continue
repo = _create_repo(line, filename)
# do not store duplicated uri's
if repo['uri'] not in repos:
repos[repo['uri']] = [repo]
def list_repos(**kwargs): # pylint: disable=unused-argument
'''
Lists all repos on ``/etc/opkg/*.conf``
CLI Example:
.. code-block:: bash
salt '*' pkg.list_repos
'''
repos = {}
regex = re.compile(REPO_REGEXP)
for filename in os.listdir(OPKG_CONFDIR):
if not filename.endswith(".conf"):
continue
with salt.utils.files.fopen(os.path.join(OPKG_CONFDIR, filename)) as conf_file:
_read_repos(conf_file, repos, filename, regex)
return repos
def get_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Display a repo from the ``/etc/opkg/*.conf``
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo repo
'''
repos = list_repos()
if repos:
for source in six.itervalues(repos):
for sub in source:
if sub['name'] == repo:
return sub
return {}
def _del_repo_from_file(repo, filepath):
'''
Remove a repo from filepath
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
regex = re.compile(REPO_REGEXP)
for line in fhandle:
line = salt.utils.stringutils.to_unicode(line)
if regex.search(line):
if line.startswith('#'):
line = line[1:]
cols = salt.utils.args.shlex_split(line.strip())
if repo != cols[1]:
output.append(salt.utils.stringutils.to_str(line))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def _set_trusted_option_if_needed(repostr, trusted):
'''
Set trusted option to repo if needed
'''
if trusted is True:
repostr += ' [trusted=yes]'
elif trusted is False:
repostr += ' [trusted=no]'
return repostr
def _add_new_repo(repo, properties):
'''
Add a new repo entry
'''
repostr = '# ' if not properties.get('enabled') else ''
repostr += 'src/gz ' if properties.get('compressed') else 'src '
if ' ' in repo:
repostr += '"' + repo + '" '
else:
repostr += repo + ' '
repostr += properties.get('uri')
repostr = _set_trusted_option_if_needed(repostr, properties.get('trusted'))
repostr += '\n'
conffile = os.path.join(OPKG_CONFDIR, repo + '.conf')
with salt.utils.files.fopen(conffile, 'a') as fhandle:
fhandle.write(salt.utils.stringutils.to_str(repostr))
def _mod_repo_in_file(repo, repostr, filepath):
'''
Replace a repo entry in filepath with repostr
'''
with salt.utils.files.fopen(filepath) as fhandle:
output = []
for line in fhandle:
cols = salt.utils.args.shlex_split(
salt.utils.stringutils.to_unicode(line).strip()
)
if repo not in cols:
output.append(line)
else:
output.append(salt.utils.stringutils.to_str(repostr + '\n'))
with salt.utils.files.fopen(filepath, 'w') as fhandle:
fhandle.writelines(output)
def del_repo(repo, **kwargs): # pylint: disable=unused-argument
'''
Delete a repo from ``/etc/opkg/*.conf``
If the file does not contain any other repo configuration, the file itself
will be deleted.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo repo
'''
refresh = salt.utils.data.is_true(kwargs.get('refresh', True))
repos = list_repos()
if repos:
deleted_from = dict()
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
deleted_from[source['file']] = 0
_del_repo_from_file(repo, source['file'])
if deleted_from:
ret = ''
for repository in repos:
source = repos[repository][0]
if source['file'] in deleted_from:
deleted_from[source['file']] += 1
for repo_file, count in six.iteritems(deleted_from):
msg = 'Repo \'{0}\' has been removed from {1}.\n'
if count == 1 and os.path.isfile(repo_file):
msg = ('File {1} containing repo \'{0}\' has been '
'removed.\n')
try:
os.remove(repo_file)
except OSError:
pass
ret += msg.format(repo, repo_file)
if refresh:
refresh_db()
return ret
return "Repo {0} doesn't exist in the opkg repo lists".format(repo)
def mod_repo(repo, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as uri is defined.
The following options are available to modify a repo definition:
repo
alias by which opkg refers to the repo.
uri
the URI to the repo.
compressed
defines (True or False) if the index file is compressed
enabled
enable or disable (True or False) repository
but do not remove if disabled.
refresh
enable or disable (True or False) auto-refresh of the repositories
CLI Examples:
.. code-block:: bash
salt '*' pkg.mod_repo repo uri=http://new/uri
salt '*' pkg.mod_repo repo enabled=False
'''
repos = list_repos()
found = False
uri = ''
if 'uri' in kwargs:
uri = kwargs['uri']
for repository in repos:
source = repos[repository][0]
if source['name'] == repo:
found = True
repostr = ''
if 'enabled' in kwargs and not kwargs['enabled']:
repostr += '# '
if 'compressed' in kwargs:
repostr += 'src/gz ' if kwargs['compressed'] else 'src'
else:
repostr += 'src/gz' if source['compressed'] else 'src'
repo_alias = kwargs['alias'] if 'alias' in kwargs else repo
if ' ' in repo_alias:
repostr += ' "{0}"'.format(repo_alias)
else:
repostr += ' {0}'.format(repo_alias)
repostr += ' {0}'.format(kwargs['uri'] if 'uri' in kwargs else source['uri'])
trusted = kwargs.get('trusted')
repostr = _set_trusted_option_if_needed(repostr, trusted) if trusted is not None else \
_set_trusted_option_if_needed(repostr, source.get('trusted'))
_mod_repo_in_file(repo, repostr, source['file'])
elif uri and source['uri'] == uri:
raise CommandExecutionError(
'Repository \'{0}\' already exists as \'{1}\'.'.format(uri, source['name']))
if not found:
# Need to add a new repo
if 'uri' not in kwargs:
raise CommandExecutionError(
'Repository \'{0}\' not found and no URI passed to create one.'.format(repo))
properties = {'uri': kwargs['uri']}
# If compressed is not defined, assume True
properties['compressed'] = kwargs['compressed'] if 'compressed' in kwargs else True
# If enabled is not defined, assume True
properties['enabled'] = kwargs['enabled'] if 'enabled' in kwargs else True
properties['trusted'] = kwargs.get('trusted')
_add_new_repo(repo, properties)
if 'refresh' in kwargs:
refresh_db()
def file_list(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg.file_list httpd
salt '*' pkg.file_list httpd postfix
salt '*' pkg.file_list
'''
output = file_dict(*packages)
files = []
for package in list(output['packages'].values()):
files.extend(package)
return {'errors': output['errors'], 'files': files}
def owner(*paths, **kwargs): # pylint: disable=unused-argument
'''
Return the name of the package that owns the file. Multiple file paths can
be passed. Like :mod:`pkg.version <salt.modules.opkg.version`, if a single
path is passed, a string will be returned, and if multiple paths are passed,
a dictionary of file/package name pairs will be returned.
If the file is not owned by a package, or is not present on the minion,
then an empty string will be returned for that path.
CLI Example:
salt '*' pkg.owner /usr/bin/apachectl
salt '*' pkg.owner /usr/bin/apachectl /usr/bin/basename
'''
if not paths:
return ''
ret = {}
cmd_search = ['opkg', 'search']
for path in paths:
cmd = cmd_search[:]
cmd.append(path)
output = __salt__['cmd.run_stdout'](cmd,
output_loglevel='trace',
python_shell=False)
if output:
ret[path] = output.split(' - ')[0].strip()
else:
ret[path] = ''
if len(ret) == 1:
return next(six.itervalues(ret))
return ret
def version_clean(version):
'''
Clean the version string removing extra data.
There's nothing do to here for nipkg.py, therefore it will always
return the given version.
'''
return version
def check_extra_requirements(pkgname, pkgver):
'''
Check if the installed package already has the given requirements.
There's nothing do to here for nipkg.py, therefore it will always
return True.
'''
return True
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.