class DockerVolumeManager(object): def __init__(self, client): self.client = client self.parameters = TaskParameters(client) self.check_mode = self.client.check_mode self.results = {u'changed': False, u'actions': []} self.diff = self.client.module._diff self.diff_tracker = DifferenceTracker() self.diff_result = dict() self.existing_volume = self.get_existing_volume() state = self.parameters.state if state == 'present': self.present() elif state == 'absent': self.absent() if self.diff or self.check_mode or self.parameters.debug: if self.diff: self.diff_result['before'], self.diff_result[ 'after'] = self.diff_tracker.get_before_after() self.results['diff'] = self.diff_result def get_existing_volume(self): try: volumes = self.client.volumes() except APIError as e: self.client.fail(text_type(e)) if volumes[u'Volumes'] is None: return None for volume in volumes[u'Volumes']: if volume['Name'] == self.parameters.volume_name: return volume return None def has_different_config(self): """ Return the list of differences between the current parameters and the existing volume. :return: list of options that differ """ differences = DifferenceTracker() if self.parameters.driver and self.parameters.driver != self.existing_volume[ 'Driver']: differences.add('driver', parameter=self.parameters.driver, active=self.existing_volume['Driver']) if self.parameters.driver_options: if not self.existing_volume.get('Options'): differences.add('driver_options', parameter=self.parameters.driver_options, active=self.existing_volume.get('Options')) else: for key, value in iteritems(self.parameters.driver_options): if (not self.existing_volume['Options'].get(key) or value != self.existing_volume['Options'][key]): differences.add( 'driver_options.%s' % key, parameter=value, active=self.existing_volume['Options'].get(key)) if self.parameters.labels: existing_labels = self.existing_volume.get('Labels', {}) for label in self.parameters.labels: if existing_labels.get(label) != self.parameters.labels.get( label): differences.add( 'labels.%s' % label, parameter=self.parameters.labels.get(label), active=existing_labels.get(label)) return differences def create_volume(self): if not self.existing_volume: if not self.check_mode: try: params = dict( driver=self.parameters.driver, driver_opts=self.parameters.driver_options, ) if self.parameters.labels is not None: params['labels'] = self.parameters.labels resp = self.client.create_volume( self.parameters.volume_name, **params) self.existing_volume = self.client.inspect_volume( resp['Name']) except APIError as e: self.client.fail(text_type(e)) self.results['actions'].append( "Created volume %s with driver %s" % (self.parameters.volume_name, self.parameters.driver)) self.results['changed'] = True def remove_volume(self): if self.existing_volume: if not self.check_mode: try: self.client.remove_volume(self.parameters.volume_name) except APIError as e: self.client.fail(text_type(e)) self.results['actions'].append("Removed volume %s" % self.parameters.volume_name) self.results['changed'] = True def present(self): differences = DifferenceTracker() if self.existing_volume: differences = self.has_different_config() self.diff_tracker.add('exists', parameter=True, active=self.existing_volume is not None) if (not differences.empty and self.parameters.recreate == 'options-changed') or self.parameters.recreate == 'always': self.remove_volume() self.existing_volume = None self.create_volume() if self.diff or self.check_mode or self.parameters.debug: self.diff_result[ 'differences'] = differences.get_legacy_docker_diffs() self.diff_tracker.merge(differences) if not self.check_mode and not self.parameters.debug: self.results.pop('actions') volume_facts = self.get_existing_volume() self.results['ansible_facts'] = {u'docker_volume': volume_facts} self.results['volume'] = volume_facts def absent(self): self.diff_tracker.add('exists', parameter=False, active=self.existing_volume is not None) self.remove_volume()
class DockerNetworkManager(object): def __init__(self, client): self.client = client self.parameters = TaskParameters(client) self.check_mode = self.client.check_mode self.results = {u'changed': False, u'actions': []} self.diff = self.client.module._diff self.diff_tracker = DifferenceTracker() self.diff_result = dict() self.existing_network = self.get_existing_network() if not self.parameters.connected and self.existing_network: self.parameters.connected = container_names_in_network( self.existing_network) if (self.parameters.ipam_options['subnet'] or self.parameters.ipam_options['iprange'] or self.parameters.ipam_options['gateway'] or self.parameters.ipam_options['aux_addresses']): self.parameters.ipam_config = [self.parameters.ipam_options] if self.parameters.ipam_config: try: for ipam_config in self.parameters.ipam_config: validate_cidr(ipam_config['subnet']) except ValueError as e: self.client.fail(str(e)) if self.parameters.driver_options: self.parameters.driver_options = clean_dict_booleans_for_docker_api( self.parameters.driver_options) state = self.parameters.state if state == 'present': self.present() elif state == 'absent': self.absent() if self.diff or self.check_mode or self.parameters.debug: if self.diff: self.diff_result['before'], self.diff_result[ 'after'] = self.diff_tracker.get_before_after() self.results['diff'] = self.diff_result def get_existing_network(self): return self.client.get_network(name=self.parameters.name) def has_different_config(self, net): ''' Evaluates an existing network and returns a tuple containing a boolean indicating if the configuration is different and a list of differences. :param net: the inspection output for an existing network :return: (bool, list) ''' differences = DifferenceTracker() if self.parameters.driver and self.parameters.driver != net['Driver']: differences.add('driver', parameter=self.parameters.driver, active=net['Driver']) if self.parameters.driver_options: if not net.get('Options'): differences.add('driver_options', parameter=self.parameters.driver_options, active=net.get('Options')) else: for key, value in self.parameters.driver_options.items(): if not (key in net['Options']) or value != net['Options'][key]: differences.add('driver_options.%s' % key, parameter=value, active=net['Options'].get(key)) if self.parameters.ipam_driver: if not net.get('IPAM') or net['IPAM'][ 'Driver'] != self.parameters.ipam_driver: differences.add('ipam_driver', parameter=self.parameters.ipam_driver, active=net.get('IPAM')) if self.parameters.ipam_driver_options is not None: ipam_driver_options = net['IPAM'].get('Options') or {} if ipam_driver_options != self.parameters.ipam_driver_options: differences.add('ipam_driver_options', parameter=self.parameters.ipam_driver_options, active=ipam_driver_options) if self.parameters.ipam_config is not None and self.parameters.ipam_config: if not net.get('IPAM') or not net['IPAM']['Config']: differences.add('ipam_config', parameter=self.parameters.ipam_config, active=net.get('IPAM', {}).get('Config')) else: # Put network's IPAM config into the same format as module's IPAM config net_ipam_configs = [] for net_ipam_config in net['IPAM']['Config']: config = dict() for k, v in net_ipam_config.items(): config[normalize_ipam_config_key(k)] = v net_ipam_configs.append(config) # Compare lists of dicts as sets of dicts for idx, ipam_config in enumerate(self.parameters.ipam_config): net_config = dict() for net_ipam_config in net_ipam_configs: if dicts_are_essentially_equal(ipam_config, net_ipam_config): net_config = net_ipam_config break for key, value in ipam_config.items(): if value is None: # due to recursive argument_spec, all keys are always present # (but have default value None if not specified) continue if value != net_config.get(key): differences.add('ipam_config[%s].%s' % (idx, key), parameter=value, active=net_config.get(key)) if self.parameters.enable_ipv6 is not None and self.parameters.enable_ipv6 != net.get( 'EnableIPv6', False): differences.add('enable_ipv6', parameter=self.parameters.enable_ipv6, active=net.get('EnableIPv6', False)) if self.parameters.internal is not None and self.parameters.internal != net.get( 'Internal', False): differences.add('internal', parameter=self.parameters.internal, active=net.get('Internal')) if self.parameters.scope is not None and self.parameters.scope != net.get( 'Scope'): differences.add('scope', parameter=self.parameters.scope, active=net.get('Scope')) if self.parameters.attachable is not None and self.parameters.attachable != net.get( 'Attachable', False): differences.add('attachable', parameter=self.parameters.attachable, active=net.get('Attachable')) if self.parameters.labels: if not net.get('Labels'): differences.add('labels', parameter=self.parameters.labels, active=net.get('Labels')) else: for key, value in self.parameters.labels.items(): if not (key in net['Labels']) or value != net['Labels'][key]: differences.add('labels.%s' % key, parameter=value, active=net['Labels'].get(key)) return not differences.empty, differences def create_network(self): if not self.existing_network: params = dict( driver=self.parameters.driver, options=self.parameters.driver_options, ) ipam_pools = [] if self.parameters.ipam_config: for ipam_pool in self.parameters.ipam_config: if LooseVersion(docker_version) >= LooseVersion('2.0.0'): ipam_pools.append(IPAMPool(**ipam_pool)) else: ipam_pools.append(utils.create_ipam_pool(**ipam_pool)) if self.parameters.ipam_driver or self.parameters.ipam_driver_options or ipam_pools: # Only add ipam parameter if a driver was specified or if IPAM parameters # were specified. Leaving this parameter away can significantly speed up # creation; on my machine creation with this option needs ~15 seconds, # and without just a few seconds. if LooseVersion(docker_version) >= LooseVersion('2.0.0'): params['ipam'] = IPAMConfig( driver=self.parameters.ipam_driver, pool_configs=ipam_pools, options=self.parameters.ipam_driver_options) else: params['ipam'] = utils.create_ipam_config( driver=self.parameters.ipam_driver, pool_configs=ipam_pools) if self.parameters.enable_ipv6 is not None: params['enable_ipv6'] = self.parameters.enable_ipv6 if self.parameters.internal is not None: params['internal'] = self.parameters.internal if self.parameters.scope is not None: params['scope'] = self.parameters.scope if self.parameters.attachable is not None: params['attachable'] = self.parameters.attachable if self.parameters.labels: params['labels'] = self.parameters.labels if not self.check_mode: resp = self.client.create_network(self.parameters.name, **params) self.client.report_warnings(resp, ['Warning']) self.existing_network = self.client.get_network( network_id=resp['Id']) self.results['actions'].append( "Created network %s with driver %s" % (self.parameters.name, self.parameters.driver)) self.results['changed'] = True def remove_network(self): if self.existing_network: self.disconnect_all_containers() if not self.check_mode: self.client.remove_network(self.parameters.name) self.results['actions'].append("Removed network %s" % (self.parameters.name, )) self.results['changed'] = True def is_container_connected(self, container_name): if not self.existing_network: return False return container_name in container_names_in_network( self.existing_network) def connect_containers(self): for name in self.parameters.connected: if not self.is_container_connected(name): if not self.check_mode: self.client.connect_container_to_network( name, self.parameters.name) self.results['actions'].append("Connected container %s" % (name, )) self.results['changed'] = True self.diff_tracker.add('connected.{0}'.format(name), parameter=True, active=False) def disconnect_missing(self): if not self.existing_network: return containers = self.existing_network['Containers'] if not containers: return for c in containers.values(): name = c['Name'] if name not in self.parameters.connected: self.disconnect_container(name) def disconnect_all_containers(self): containers = self.client.get_network( name=self.parameters.name)['Containers'] if not containers: return for cont in containers.values(): self.disconnect_container(cont['Name']) def disconnect_container(self, container_name): if not self.check_mode: self.client.disconnect_container_from_network( container_name, self.parameters.name) self.results['actions'].append("Disconnected container %s" % (container_name, )) self.results['changed'] = True self.diff_tracker.add('connected.{0}'.format(container_name), parameter=False, active=True) def present(self): different = False differences = DifferenceTracker() if self.existing_network: different, differences = self.has_different_config( self.existing_network) self.diff_tracker.add('exists', parameter=True, active=self.existing_network is not None) if self.parameters.force or different: self.remove_network() self.existing_network = None self.create_network() self.connect_containers() if not self.parameters.appends: self.disconnect_missing() if self.diff or self.check_mode or self.parameters.debug: self.diff_result[ 'differences'] = differences.get_legacy_docker_diffs() self.diff_tracker.merge(differences) if not self.check_mode and not self.parameters.debug: self.results.pop('actions') network_facts = self.get_existing_network() self.results['ansible_facts'] = {u'docker_network': network_facts} self.results['network'] = network_facts def absent(self): self.diff_tracker.add('exists', parameter=False, active=self.existing_network is not None) self.remove_network()
class DockerPluginManager(object): def __init__(self, client): self.client = client self.dclient = DockerClient(**self.client._connect_params) self.dclient.api = client self.parameters = TaskParameters(client) self.check_mode = self.client.check_mode self.results = {u'changed': False, u'actions': []} self.diff = self.client.module._diff self.diff_tracker = DifferenceTracker() self.diff_result = dict() self.existing_plugin = self.get_existing_plugin() state = self.parameters.state if state == 'present': self.present() elif state == 'absent': self.absent() elif state == 'enabled': self.enable() elif state == 'disabled': self.disable() if self.diff or self.check_mode or self.parameters.debug: if self.diff: self.diff_result['before'], self.diff_result[ 'after'] = self.diff_tracker.get_before_after() self.results['diff'] = self.diff_result def get_existing_plugin(self): """Return an existing plugin or None.""" alias = self.parameters.alias try: plugin = self.dclient.plugins.get(alias) except NotFound: return None except APIError as error: msg = wrap_error("Failed to query existing plugins", error) self.client.fail(msg) else: return plugin return None def has_different_config(self): """ Return the list of differences between the current parameters and the existing plugin. :return: list of options that differ """ differences = DifferenceTracker() if self.parameters.plugin_options: existing_options = parse_options( self.existing_plugin.settings['Env']) if not existing_options: differences.add('plugin_options', parameter=self.parameters.plugin_options, active=existing_options) else: for key, value in self.parameters.plugin_options.items(): active_value = existing_options.get(key) if active_value != value: differences.add('plugin_options.%s' % key, parameter=value, active=active_value) return differences def install_plugin(self): # Perform action only when plugin is not already installed if not self.existing_plugin: if not self.check_mode: try: self.existing_plugin = self.dclient.plugins.install( self.parameters.name, self.parameters.alias) except APIError as error: msg = wrap_error( prefix= "Failed to install local docker logging plugin %s from %s" % (self.parameters.alias, self.parameters.name), error=error) self.client.fail(msg) # Set results self.results['actions'].append( "Installed local docker logging plugin %s from %s." % (self.parameters.alias, self.parameters.name)) self.results['changed'] = True def remove_plugin(self): # Perform action only when plugin is installed if self.existing_plugin: if not self.check_mode: try: self.existing_plugin.remove() except APIError as error: msg = wrap_error( prefix="Failed to remove local docker logging plugin %s" % self.parameters.alias, error=error) self.client.fail(msg) # Set results self.results['actions'].append( "Removed local docker logging plugin %s." % self.parameters.alias) self.results['changed'] = True def enable_plugin(self, main_action=True): # We want to know if the plugin is installed self.existing_plugin = self.get_existing_plugin() if not self.existing_plugin.enabled: if not self.check_mode: try: self.existing_plugin.enable(1) except APIError as error: msg = wrap_error(prefix=( "Failed to enable local docker logging plugin %s. " % self.parameters.alias, ), error=error) self.client.fail(msg) # Set results optionnaly if main_action: self.results['actions'].append( "Enabled local docker logging plugin %s." % self.parameters.alias) self.results['changed'] = True def disable_plugin(self, main_action=True): if self.existing_plugin: if self.existing_plugin.enabled: if not self.check_mode: try: self.existing_plugin.disable() except APIError as error: msg = wrap_error(prefix=( "Failed to disable local docker logging plugin %s. " % self.parameters.alias, ), error=error) self.client.fail(msg) # Set results optionnaly if main_action: self.results['actions'].append( "Disabled local docker logging plugin %s." % self.parameters.alias) self.results['changed'] = True def update_plugin(self, differences): if not self.check_mode: must_enable = self.parameters.state == "enabled" # Plugin must be disabled to be updated if self.existing_plugin.enabled: self.disable_plugin(main_action=False) if self.parameters.state in ["present", "enabled"]: need_enable = True # Update the configuration try: self.existing_plugin.configure( prepare_options(self.parameters.plugin_options)) except APIError as error: msg = wrap_error( prefix=("Failed to update local docker logging plugin %s" % self.parameters.alias, ), error=error) self.client.fail(msg) # Enable the plugin when needed if must_enable: self.enable_plugin(main_action=False) # Set results self.results['actions'].append( "Updated local docker logging plugin %s settings." % self.parameters.alias) self.results['changed'] = True def present(self): differences = DifferenceTracker() if self.existing_plugin: differences = self.has_different_config() self.diff_tracker.add('exists', parameter=True, active=self.existing_plugin is not None) if not differences.empty: # Plugin already exists self.update_plugin(differences) else: # Let's install plugin self.install_plugin() if self.diff or self.check_mode or self.parameters.debug: self.results['diff'] = differences.get_legacy_docker_diffs() self.diff_tracker.merge(differences) if not self.check_mode and not self.parameters.debug: self.results.pop('actions') def absent(self): self.remove_plugin() def enable(self): differences = DifferenceTracker() if self.existing_plugin: differences = self.has_different_config() self.diff_tracker.add('exists', parameter=True, active=self.existing_plugin is not None) # Plugin already exists if not differences.empty: # Let's update plugin self.update_plugin(differences) else: # Or install and enable plugin self.install_plugin() self.enable_plugin() if self.diff or self.check_mode or self.parameters.debug: self.results['diff'] = differences.get_legacy_docker_diffs() self.diff_tracker.merge(differences) if not self.check_mode and not self.parameters.debug: self.results.pop('actions') def disable(self): self.disable_plugin()