File manager - Edit - /home/newsbmcs.com/public_html/static/img/logo/service.py.tar
Back
usr/local/CyberCP/lib/python3.10/site-packages/docker/api/service.py 0000644 00000045417 15027775571 0021134 0 ustar 00 from .. import auth, errors, utils from ..types import ServiceMode def _check_api_features(version, task_template, update_config, endpoint_spec, rollback_config): def raise_version_error(param, min_version): raise errors.InvalidVersion( f'{param} is not supported in API version < {min_version}' ) if update_config is not None: if utils.version_lt(version, '1.25'): if 'MaxFailureRatio' in update_config: raise_version_error('UpdateConfig.max_failure_ratio', '1.25') if 'Monitor' in update_config: raise_version_error('UpdateConfig.monitor', '1.25') if utils.version_lt(version, '1.28'): if update_config.get('FailureAction') == 'rollback': raise_version_error( 'UpdateConfig.failure_action rollback', '1.28' ) if utils.version_lt(version, '1.29'): if 'Order' in update_config: raise_version_error('UpdateConfig.order', '1.29') if rollback_config is not None: if utils.version_lt(version, '1.28'): raise_version_error('rollback_config', '1.28') if utils.version_lt(version, '1.29'): if 'Order' in update_config: raise_version_error('RollbackConfig.order', '1.29') if endpoint_spec is not None: if utils.version_lt(version, '1.32') and 'Ports' in endpoint_spec: if any(p.get('PublishMode') for p in endpoint_spec['Ports']): raise_version_error('EndpointSpec.Ports[].mode', '1.32') if task_template is not None: if 'ForceUpdate' in task_template and utils.version_lt( version, '1.25'): raise_version_error('force_update', '1.25') if task_template.get('Placement'): if utils.version_lt(version, '1.30'): if task_template['Placement'].get('Platforms'): raise_version_error('Placement.platforms', '1.30') if utils.version_lt(version, '1.27'): if task_template['Placement'].get('Preferences'): raise_version_error('Placement.preferences', '1.27') if task_template.get('ContainerSpec'): container_spec = task_template.get('ContainerSpec') if utils.version_lt(version, '1.25'): if container_spec.get('TTY'): raise_version_error('ContainerSpec.tty', '1.25') if container_spec.get('Hostname') is not None: raise_version_error('ContainerSpec.hostname', '1.25') if container_spec.get('Hosts') is not None: raise_version_error('ContainerSpec.hosts', '1.25') if container_spec.get('Groups') is not None: raise_version_error('ContainerSpec.groups', '1.25') if container_spec.get('DNSConfig') is not None: raise_version_error('ContainerSpec.dns_config', '1.25') if container_spec.get('Healthcheck') is not None: raise_version_error('ContainerSpec.healthcheck', '1.25') if utils.version_lt(version, '1.28'): if container_spec.get('ReadOnly') is not None: raise_version_error('ContainerSpec.dns_config', '1.28') if container_spec.get('StopSignal') is not None: raise_version_error('ContainerSpec.stop_signal', '1.28') if utils.version_lt(version, '1.30'): if container_spec.get('Configs') is not None: raise_version_error('ContainerSpec.configs', '1.30') if container_spec.get('Privileges') is not None: raise_version_error('ContainerSpec.privileges', '1.30') if utils.version_lt(version, '1.35'): if container_spec.get('Isolation') is not None: raise_version_error('ContainerSpec.isolation', '1.35') if utils.version_lt(version, '1.38'): if container_spec.get('Init') is not None: raise_version_error('ContainerSpec.init', '1.38') if task_template.get('Resources'): if utils.version_lt(version, '1.32'): if task_template['Resources'].get('GenericResources'): raise_version_error('Resources.generic_resources', '1.32') def _merge_task_template(current, override): merged = current.copy() if override is not None: for ts_key, ts_value in override.items(): if ts_key == 'ContainerSpec': if 'ContainerSpec' not in merged: merged['ContainerSpec'] = {} for cs_key, cs_value in override['ContainerSpec'].items(): if cs_value is not None: merged['ContainerSpec'][cs_key] = cs_value elif ts_value is not None: merged[ts_key] = ts_value return merged class ServiceApiMixin: @utils.minimum_version('1.24') def create_service( self, task_template, name=None, labels=None, mode=None, update_config=None, networks=None, endpoint_config=None, endpoint_spec=None, rollback_config=None ): """ Create a service. Args: task_template (TaskTemplate): Specification of the task to start as part of the new service. name (string): User-defined name for the service. Optional. labels (dict): A map of labels to associate with the service. Optional. mode (ServiceMode): Scheduling mode for the service (replicated or global). Defaults to replicated. update_config (UpdateConfig): Specification for the update strategy of the service. Default: ``None`` rollback_config (RollbackConfig): Specification for the rollback strategy of the service. Default: ``None`` networks (:py:class:`list`): List of network names or IDs or :py:class:`~docker.types.NetworkAttachmentConfig` to attach the service to. Default: ``None``. endpoint_spec (EndpointSpec): Properties that can be configured to access and load balance a service. Default: ``None``. Returns: A dictionary containing an ``ID`` key for the newly created service. Raises: :py:class:`docker.errors.APIError` If the server returns an error. """ _check_api_features( self._version, task_template, update_config, endpoint_spec, rollback_config ) url = self._url('/services/create') headers = {} image = task_template.get('ContainerSpec', {}).get('Image', None) if image is None: raise errors.DockerException( 'Missing mandatory Image key in ContainerSpec' ) if mode and not isinstance(mode, dict): mode = ServiceMode(mode) registry, repo_name = auth.resolve_repository_name(image) auth_header = auth.get_config_header(self, registry) if auth_header: headers['X-Registry-Auth'] = auth_header if utils.version_lt(self._version, '1.25'): networks = networks or task_template.pop('Networks', None) data = { 'Name': name, 'Labels': labels, 'TaskTemplate': task_template, 'Mode': mode, 'Networks': utils.convert_service_networks(networks), 'EndpointSpec': endpoint_spec } if update_config is not None: data['UpdateConfig'] = update_config if rollback_config is not None: data['RollbackConfig'] = rollback_config return self._result( self._post_json(url, data=data, headers=headers), True ) @utils.minimum_version('1.24') @utils.check_resource('service') def inspect_service(self, service, insert_defaults=None): """ Return information about a service. Args: service (str): Service name or ID. insert_defaults (boolean): If true, default values will be merged into the service inspect output. Returns: (dict): A dictionary of the server-side representation of the service, including all relevant properties. Raises: :py:class:`docker.errors.APIError` If the server returns an error. """ url = self._url('/services/{0}', service) params = {} if insert_defaults is not None: if utils.version_lt(self._version, '1.29'): raise errors.InvalidVersion( 'insert_defaults is not supported in API version < 1.29' ) params['insertDefaults'] = insert_defaults return self._result(self._get(url, params=params), True) @utils.minimum_version('1.24') @utils.check_resource('task') def inspect_task(self, task): """ Retrieve information about a task. Args: task (str): Task ID Returns: (dict): Information about the task. Raises: :py:class:`docker.errors.APIError` If the server returns an error. """ url = self._url('/tasks/{0}', task) return self._result(self._get(url), True) @utils.minimum_version('1.24') @utils.check_resource('service') def remove_service(self, service): """ Stop and remove a service. Args: service (str): Service name or ID Returns: ``True`` if successful. Raises: :py:class:`docker.errors.APIError` If the server returns an error. """ url = self._url('/services/{0}', service) resp = self._delete(url) self._raise_for_status(resp) return True @utils.minimum_version('1.24') def services(self, filters=None, status=None): """ List services. Args: filters (dict): Filters to process on the nodes list. Valid filters: ``id``, ``name`` , ``label`` and ``mode``. Default: ``None``. status (bool): Include the service task count of running and desired tasks. Default: ``None``. Returns: A list of dictionaries containing data about each service. Raises: :py:class:`docker.errors.APIError` If the server returns an error. """ params = { 'filters': utils.convert_filters(filters) if filters else None } if status is not None: if utils.version_lt(self._version, '1.41'): raise errors.InvalidVersion( 'status is not supported in API version < 1.41' ) params['status'] = status url = self._url('/services') return self._result(self._get(url, params=params), True) @utils.minimum_version('1.25') @utils.check_resource('service') def service_logs(self, service, details=False, follow=False, stdout=False, stderr=False, since=0, timestamps=False, tail='all', is_tty=None): """ Get log stream for a service. Note: This endpoint works only for services with the ``json-file`` or ``journald`` logging drivers. Args: service (str): ID or name of the service details (bool): Show extra details provided to logs. Default: ``False`` follow (bool): Keep connection open to read logs as they are sent by the Engine. Default: ``False`` stdout (bool): Return logs from ``stdout``. Default: ``False`` stderr (bool): Return logs from ``stderr``. Default: ``False`` since (int): UNIX timestamp for the logs staring point. Default: 0 timestamps (bool): Add timestamps to every log line. tail (string or int): Number of log lines to be returned, counting from the current end of the logs. Specify an integer or ``'all'`` to output all log lines. Default: ``all`` is_tty (bool): Whether the service's :py:class:`ContainerSpec` enables the TTY option. If omitted, the method will query the Engine for the information, causing an additional roundtrip. Returns (generator): Logs for the service. """ params = { 'details': details, 'follow': follow, 'stdout': stdout, 'stderr': stderr, 'since': since, 'timestamps': timestamps, 'tail': tail } url = self._url('/services/{0}/logs', service) res = self._get(url, params=params, stream=True) if is_tty is None: is_tty = self.inspect_service( service )['Spec']['TaskTemplate']['ContainerSpec'].get('TTY', False) return self._get_result_tty(True, res, is_tty) @utils.minimum_version('1.24') def tasks(self, filters=None): """ Retrieve a list of tasks. Args: filters (dict): A map of filters to process on the tasks list. Valid filters: ``id``, ``name``, ``service``, ``node``, ``label`` and ``desired-state``. Returns: (:py:class:`list`): List of task dictionaries. Raises: :py:class:`docker.errors.APIError` If the server returns an error. """ params = { 'filters': utils.convert_filters(filters) if filters else None } url = self._url('/tasks') return self._result(self._get(url, params=params), True) @utils.minimum_version('1.24') @utils.check_resource('service') def update_service(self, service, version, task_template=None, name=None, labels=None, mode=None, update_config=None, networks=None, endpoint_config=None, endpoint_spec=None, fetch_current_spec=False, rollback_config=None): """ Update a service. Args: service (string): A service identifier (either its name or service ID). version (int): The version number of the service object being updated. This is required to avoid conflicting writes. task_template (TaskTemplate): Specification of the updated task to start as part of the service. name (string): New name for the service. Optional. labels (dict): A map of labels to associate with the service. Optional. mode (ServiceMode): Scheduling mode for the service (replicated or global). Defaults to replicated. update_config (UpdateConfig): Specification for the update strategy of the service. Default: ``None``. rollback_config (RollbackConfig): Specification for the rollback strategy of the service. Default: ``None`` networks (:py:class:`list`): List of network names or IDs or :py:class:`~docker.types.NetworkAttachmentConfig` to attach the service to. Default: ``None``. endpoint_spec (EndpointSpec): Properties that can be configured to access and load balance a service. Default: ``None``. fetch_current_spec (boolean): Use the undefined settings from the current specification of the service. Default: ``False`` Returns: A dictionary containing a ``Warnings`` key. Raises: :py:class:`docker.errors.APIError` If the server returns an error. """ _check_api_features( self._version, task_template, update_config, endpoint_spec, rollback_config ) if fetch_current_spec: inspect_defaults = True if utils.version_lt(self._version, '1.29'): inspect_defaults = None current = self.inspect_service( service, insert_defaults=inspect_defaults )['Spec'] else: current = {} url = self._url('/services/{0}/update', service) data = {} headers = {} data['Name'] = current.get('Name') if name is None else name data['Labels'] = current.get('Labels') if labels is None else labels if mode is not None: if not isinstance(mode, dict): mode = ServiceMode(mode) data['Mode'] = mode else: data['Mode'] = current.get('Mode') data['TaskTemplate'] = _merge_task_template( current.get('TaskTemplate', {}), task_template ) container_spec = data['TaskTemplate'].get('ContainerSpec', {}) image = container_spec.get('Image', None) if image is not None: registry, repo_name = auth.resolve_repository_name(image) auth_header = auth.get_config_header(self, registry) if auth_header: headers['X-Registry-Auth'] = auth_header if update_config is not None: data['UpdateConfig'] = update_config else: data['UpdateConfig'] = current.get('UpdateConfig') if rollback_config is not None: data['RollbackConfig'] = rollback_config else: data['RollbackConfig'] = current.get('RollbackConfig') if networks is not None: converted_networks = utils.convert_service_networks(networks) if utils.version_lt(self._version, '1.25'): data['Networks'] = converted_networks else: data['TaskTemplate']['Networks'] = converted_networks elif utils.version_lt(self._version, '1.25'): data['Networks'] = current.get('Networks') elif data['TaskTemplate'].get('Networks') is None: current_task_template = current.get('TaskTemplate', {}) current_networks = current_task_template.get('Networks') if current_networks is None: current_networks = current.get('Networks') if current_networks is not None: data['TaskTemplate']['Networks'] = current_networks if endpoint_spec is not None: data['EndpointSpec'] = endpoint_spec else: data['EndpointSpec'] = current.get('EndpointSpec') resp = self._post_json( url, data=data, params={'version': version}, headers=headers ) return self._result(resp, json=True) usr/local/CyberPanel/lib/python3.10/site-packages/docker/api/service.py 0000644 00000045417 15030000032 0021630 0 ustar 00 from .. import auth, errors, utils from ..types import ServiceMode def _check_api_features(version, task_template, update_config, endpoint_spec, rollback_config): def raise_version_error(param, min_version): raise errors.InvalidVersion( f'{param} is not supported in API version < {min_version}' ) if update_config is not None: if utils.version_lt(version, '1.25'): if 'MaxFailureRatio' in update_config: raise_version_error('UpdateConfig.max_failure_ratio', '1.25') if 'Monitor' in update_config: raise_version_error('UpdateConfig.monitor', '1.25') if utils.version_lt(version, '1.28'): if update_config.get('FailureAction') == 'rollback': raise_version_error( 'UpdateConfig.failure_action rollback', '1.28' ) if utils.version_lt(version, '1.29'): if 'Order' in update_config: raise_version_error('UpdateConfig.order', '1.29') if rollback_config is not None: if utils.version_lt(version, '1.28'): raise_version_error('rollback_config', '1.28') if utils.version_lt(version, '1.29'): if 'Order' in update_config: raise_version_error('RollbackConfig.order', '1.29') if endpoint_spec is not None: if utils.version_lt(version, '1.32') and 'Ports' in endpoint_spec: if any(p.get('PublishMode') for p in endpoint_spec['Ports']): raise_version_error('EndpointSpec.Ports[].mode', '1.32') if task_template is not None: if 'ForceUpdate' in task_template and utils.version_lt( version, '1.25'): raise_version_error('force_update', '1.25') if task_template.get('Placement'): if utils.version_lt(version, '1.30'): if task_template['Placement'].get('Platforms'): raise_version_error('Placement.platforms', '1.30') if utils.version_lt(version, '1.27'): if task_template['Placement'].get('Preferences'): raise_version_error('Placement.preferences', '1.27') if task_template.get('ContainerSpec'): container_spec = task_template.get('ContainerSpec') if utils.version_lt(version, '1.25'): if container_spec.get('TTY'): raise_version_error('ContainerSpec.tty', '1.25') if container_spec.get('Hostname') is not None: raise_version_error('ContainerSpec.hostname', '1.25') if container_spec.get('Hosts') is not None: raise_version_error('ContainerSpec.hosts', '1.25') if container_spec.get('Groups') is not None: raise_version_error('ContainerSpec.groups', '1.25') if container_spec.get('DNSConfig') is not None: raise_version_error('ContainerSpec.dns_config', '1.25') if container_spec.get('Healthcheck') is not None: raise_version_error('ContainerSpec.healthcheck', '1.25') if utils.version_lt(version, '1.28'): if container_spec.get('ReadOnly') is not None: raise_version_error('ContainerSpec.dns_config', '1.28') if container_spec.get('StopSignal') is not None: raise_version_error('ContainerSpec.stop_signal', '1.28') if utils.version_lt(version, '1.30'): if container_spec.get('Configs') is not None: raise_version_error('ContainerSpec.configs', '1.30') if container_spec.get('Privileges') is not None: raise_version_error('ContainerSpec.privileges', '1.30') if utils.version_lt(version, '1.35'): if container_spec.get('Isolation') is not None: raise_version_error('ContainerSpec.isolation', '1.35') if utils.version_lt(version, '1.38'): if container_spec.get('Init') is not None: raise_version_error('ContainerSpec.init', '1.38') if task_template.get('Resources'): if utils.version_lt(version, '1.32'): if task_template['Resources'].get('GenericResources'): raise_version_error('Resources.generic_resources', '1.32') def _merge_task_template(current, override): merged = current.copy() if override is not None: for ts_key, ts_value in override.items(): if ts_key == 'ContainerSpec': if 'ContainerSpec' not in merged: merged['ContainerSpec'] = {} for cs_key, cs_value in override['ContainerSpec'].items(): if cs_value is not None: merged['ContainerSpec'][cs_key] = cs_value elif ts_value is not None: merged[ts_key] = ts_value return merged class ServiceApiMixin: @utils.minimum_version('1.24') def create_service( self, task_template, name=None, labels=None, mode=None, update_config=None, networks=None, endpoint_config=None, endpoint_spec=None, rollback_config=None ): """ Create a service. Args: task_template (TaskTemplate): Specification of the task to start as part of the new service. name (string): User-defined name for the service. Optional. labels (dict): A map of labels to associate with the service. Optional. mode (ServiceMode): Scheduling mode for the service (replicated or global). Defaults to replicated. update_config (UpdateConfig): Specification for the update strategy of the service. Default: ``None`` rollback_config (RollbackConfig): Specification for the rollback strategy of the service. Default: ``None`` networks (:py:class:`list`): List of network names or IDs or :py:class:`~docker.types.NetworkAttachmentConfig` to attach the service to. Default: ``None``. endpoint_spec (EndpointSpec): Properties that can be configured to access and load balance a service. Default: ``None``. Returns: A dictionary containing an ``ID`` key for the newly created service. Raises: :py:class:`docker.errors.APIError` If the server returns an error. """ _check_api_features( self._version, task_template, update_config, endpoint_spec, rollback_config ) url = self._url('/services/create') headers = {} image = task_template.get('ContainerSpec', {}).get('Image', None) if image is None: raise errors.DockerException( 'Missing mandatory Image key in ContainerSpec' ) if mode and not isinstance(mode, dict): mode = ServiceMode(mode) registry, repo_name = auth.resolve_repository_name(image) auth_header = auth.get_config_header(self, registry) if auth_header: headers['X-Registry-Auth'] = auth_header if utils.version_lt(self._version, '1.25'): networks = networks or task_template.pop('Networks', None) data = { 'Name': name, 'Labels': labels, 'TaskTemplate': task_template, 'Mode': mode, 'Networks': utils.convert_service_networks(networks), 'EndpointSpec': endpoint_spec } if update_config is not None: data['UpdateConfig'] = update_config if rollback_config is not None: data['RollbackConfig'] = rollback_config return self._result( self._post_json(url, data=data, headers=headers), True ) @utils.minimum_version('1.24') @utils.check_resource('service') def inspect_service(self, service, insert_defaults=None): """ Return information about a service. Args: service (str): Service name or ID. insert_defaults (boolean): If true, default values will be merged into the service inspect output. Returns: (dict): A dictionary of the server-side representation of the service, including all relevant properties. Raises: :py:class:`docker.errors.APIError` If the server returns an error. """ url = self._url('/services/{0}', service) params = {} if insert_defaults is not None: if utils.version_lt(self._version, '1.29'): raise errors.InvalidVersion( 'insert_defaults is not supported in API version < 1.29' ) params['insertDefaults'] = insert_defaults return self._result(self._get(url, params=params), True) @utils.minimum_version('1.24') @utils.check_resource('task') def inspect_task(self, task): """ Retrieve information about a task. Args: task (str): Task ID Returns: (dict): Information about the task. Raises: :py:class:`docker.errors.APIError` If the server returns an error. """ url = self._url('/tasks/{0}', task) return self._result(self._get(url), True) @utils.minimum_version('1.24') @utils.check_resource('service') def remove_service(self, service): """ Stop and remove a service. Args: service (str): Service name or ID Returns: ``True`` if successful. Raises: :py:class:`docker.errors.APIError` If the server returns an error. """ url = self._url('/services/{0}', service) resp = self._delete(url) self._raise_for_status(resp) return True @utils.minimum_version('1.24') def services(self, filters=None, status=None): """ List services. Args: filters (dict): Filters to process on the nodes list. Valid filters: ``id``, ``name`` , ``label`` and ``mode``. Default: ``None``. status (bool): Include the service task count of running and desired tasks. Default: ``None``. Returns: A list of dictionaries containing data about each service. Raises: :py:class:`docker.errors.APIError` If the server returns an error. """ params = { 'filters': utils.convert_filters(filters) if filters else None } if status is not None: if utils.version_lt(self._version, '1.41'): raise errors.InvalidVersion( 'status is not supported in API version < 1.41' ) params['status'] = status url = self._url('/services') return self._result(self._get(url, params=params), True) @utils.minimum_version('1.25') @utils.check_resource('service') def service_logs(self, service, details=False, follow=False, stdout=False, stderr=False, since=0, timestamps=False, tail='all', is_tty=None): """ Get log stream for a service. Note: This endpoint works only for services with the ``json-file`` or ``journald`` logging drivers. Args: service (str): ID or name of the service details (bool): Show extra details provided to logs. Default: ``False`` follow (bool): Keep connection open to read logs as they are sent by the Engine. Default: ``False`` stdout (bool): Return logs from ``stdout``. Default: ``False`` stderr (bool): Return logs from ``stderr``. Default: ``False`` since (int): UNIX timestamp for the logs staring point. Default: 0 timestamps (bool): Add timestamps to every log line. tail (string or int): Number of log lines to be returned, counting from the current end of the logs. Specify an integer or ``'all'`` to output all log lines. Default: ``all`` is_tty (bool): Whether the service's :py:class:`ContainerSpec` enables the TTY option. If omitted, the method will query the Engine for the information, causing an additional roundtrip. Returns (generator): Logs for the service. """ params = { 'details': details, 'follow': follow, 'stdout': stdout, 'stderr': stderr, 'since': since, 'timestamps': timestamps, 'tail': tail } url = self._url('/services/{0}/logs', service) res = self._get(url, params=params, stream=True) if is_tty is None: is_tty = self.inspect_service( service )['Spec']['TaskTemplate']['ContainerSpec'].get('TTY', False) return self._get_result_tty(True, res, is_tty) @utils.minimum_version('1.24') def tasks(self, filters=None): """ Retrieve a list of tasks. Args: filters (dict): A map of filters to process on the tasks list. Valid filters: ``id``, ``name``, ``service``, ``node``, ``label`` and ``desired-state``. Returns: (:py:class:`list`): List of task dictionaries. Raises: :py:class:`docker.errors.APIError` If the server returns an error. """ params = { 'filters': utils.convert_filters(filters) if filters else None } url = self._url('/tasks') return self._result(self._get(url, params=params), True) @utils.minimum_version('1.24') @utils.check_resource('service') def update_service(self, service, version, task_template=None, name=None, labels=None, mode=None, update_config=None, networks=None, endpoint_config=None, endpoint_spec=None, fetch_current_spec=False, rollback_config=None): """ Update a service. Args: service (string): A service identifier (either its name or service ID). version (int): The version number of the service object being updated. This is required to avoid conflicting writes. task_template (TaskTemplate): Specification of the updated task to start as part of the service. name (string): New name for the service. Optional. labels (dict): A map of labels to associate with the service. Optional. mode (ServiceMode): Scheduling mode for the service (replicated or global). Defaults to replicated. update_config (UpdateConfig): Specification for the update strategy of the service. Default: ``None``. rollback_config (RollbackConfig): Specification for the rollback strategy of the service. Default: ``None`` networks (:py:class:`list`): List of network names or IDs or :py:class:`~docker.types.NetworkAttachmentConfig` to attach the service to. Default: ``None``. endpoint_spec (EndpointSpec): Properties that can be configured to access and load balance a service. Default: ``None``. fetch_current_spec (boolean): Use the undefined settings from the current specification of the service. Default: ``False`` Returns: A dictionary containing a ``Warnings`` key. Raises: :py:class:`docker.errors.APIError` If the server returns an error. """ _check_api_features( self._version, task_template, update_config, endpoint_spec, rollback_config ) if fetch_current_spec: inspect_defaults = True if utils.version_lt(self._version, '1.29'): inspect_defaults = None current = self.inspect_service( service, insert_defaults=inspect_defaults )['Spec'] else: current = {} url = self._url('/services/{0}/update', service) data = {} headers = {} data['Name'] = current.get('Name') if name is None else name data['Labels'] = current.get('Labels') if labels is None else labels if mode is not None: if not isinstance(mode, dict): mode = ServiceMode(mode) data['Mode'] = mode else: data['Mode'] = current.get('Mode') data['TaskTemplate'] = _merge_task_template( current.get('TaskTemplate', {}), task_template ) container_spec = data['TaskTemplate'].get('ContainerSpec', {}) image = container_spec.get('Image', None) if image is not None: registry, repo_name = auth.resolve_repository_name(image) auth_header = auth.get_config_header(self, registry) if auth_header: headers['X-Registry-Auth'] = auth_header if update_config is not None: data['UpdateConfig'] = update_config else: data['UpdateConfig'] = current.get('UpdateConfig') if rollback_config is not None: data['RollbackConfig'] = rollback_config else: data['RollbackConfig'] = current.get('RollbackConfig') if networks is not None: converted_networks = utils.convert_service_networks(networks) if utils.version_lt(self._version, '1.25'): data['Networks'] = converted_networks else: data['TaskTemplate']['Networks'] = converted_networks elif utils.version_lt(self._version, '1.25'): data['Networks'] = current.get('Networks') elif data['TaskTemplate'].get('Networks') is None: current_task_template = current.get('TaskTemplate', {}) current_networks = current_task_template.get('Networks') if current_networks is None: current_networks = current.get('Networks') if current_networks is not None: data['TaskTemplate']['Networks'] = current_networks if endpoint_spec is not None: data['EndpointSpec'] = endpoint_spec else: data['EndpointSpec'] = current.get('EndpointSpec') resp = self._post_json( url, data=data, params={'version': version}, headers=headers ) return self._result(resp, json=True) usr/local/CyberCP/lib/python3.10/site-packages/botocore/docs/service.py 0000644 00000011576 15030001110 0021614 0 ustar 00 # Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file is # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF # ANY KIND, either express or implied. See the License for the specific # language governing permissions and limitations under the License. from botocore.docs.bcdoc.restdoc import DocumentStructure from botocore.docs.client import ( ClientContextParamsDocumenter, ClientDocumenter, ClientExceptionsDocumenter, ) from botocore.docs.paginator import PaginatorDocumenter from botocore.docs.waiter import WaiterDocumenter from botocore.exceptions import DataNotFoundError class ServiceDocumenter: def __init__(self, service_name, session, root_docs_path): self._session = session self._service_name = service_name self._root_docs_path = root_docs_path self._client = self._session.create_client( service_name, region_name='us-east-1', aws_access_key_id='foo', aws_secret_access_key='bar', ) self._event_emitter = self._client.meta.events self.sections = [ 'title', 'client-api', 'client-exceptions', 'paginator-api', 'waiter-api', 'client-context-params', ] def document_service(self): """Documents an entire service. :returns: The reStructured text of the documented service. """ doc_structure = DocumentStructure( self._service_name, section_names=self.sections, target='html' ) self.title(doc_structure.get_section('title')) self.client_api(doc_structure.get_section('client-api')) self.client_exceptions(doc_structure.get_section('client-exceptions')) self.paginator_api(doc_structure.get_section('paginator-api')) self.waiter_api(doc_structure.get_section('waiter-api')) context_params_section = doc_structure.get_section( 'client-context-params' ) self.client_context_params(context_params_section) return doc_structure.flush_structure() def title(self, section): section.style.h1(self._client.__class__.__name__) self._event_emitter.emit( f"docs.title.{self._service_name}", section=section ) def table_of_contents(self, section): section.style.table_of_contents(title='Table of Contents', depth=2) def client_api(self, section): examples = None try: examples = self.get_examples(self._service_name) except DataNotFoundError: pass ClientDocumenter( self._client, self._root_docs_path, examples ).document_client(section) def client_exceptions(self, section): ClientExceptionsDocumenter( self._client, self._root_docs_path ).document_exceptions(section) def paginator_api(self, section): try: service_paginator_model = self._session.get_paginator_model( self._service_name ) except DataNotFoundError: return if service_paginator_model._paginator_config: paginator_documenter = PaginatorDocumenter( self._client, service_paginator_model, self._root_docs_path ) paginator_documenter.document_paginators(section) def waiter_api(self, section): if self._client.waiter_names: service_waiter_model = self._session.get_waiter_model( self._service_name ) waiter_documenter = WaiterDocumenter( self._client, service_waiter_model, self._root_docs_path ) waiter_documenter.document_waiters(section) def get_examples(self, service_name, api_version=None): loader = self._session.get_component('data_loader') examples = loader.load_service_model( service_name, 'examples-1', api_version ) return examples['examples'] def client_context_params(self, section): omitted_params = ClientContextParamsDocumenter.OMITTED_CONTEXT_PARAMS params_to_omit = omitted_params.get(self._service_name, []) service_model = self._client.meta.service_model raw_context_params = service_model.client_context_parameters context_params = [ p for p in raw_context_params if p.name not in params_to_omit ] if context_params: context_param_documenter = ClientContextParamsDocumenter( self._service_name, context_params ) context_param_documenter.document_context_params(section) usr/lib/python3/dist-packages/firewall/core/io/service.py 0000644 00000027346 15030004352 0017430 0 ustar 00 # -*- coding: utf-8 -*- # # Copyright (C) 2011-2016 Red Hat, Inc. # # Authors: # Thomas Woerner <twoerner@redhat.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # __all__ = [ "Service", "service_reader", "service_writer" ] import xml.sax as sax import os import io import shutil from firewall import config from firewall.core.io.io_object import IO_Object, \ IO_Object_ContentHandler, IO_Object_XMLGenerator, check_port, \ check_tcpudp, check_protocol, check_address from firewall.core.logger import log from firewall import errors from firewall.errors import FirewallError class Service(IO_Object): IMPORT_EXPORT_STRUCTURE = ( ( "version", "" ), ( "short", "" ), ( "description", "" ), ( "ports", [ ( "", "" ), ], ), ( "modules", [ "", ], ), ( "destination", { "": "", }, ), ( "protocols", [ "", ], ), ( "source_ports", [ ( "", "" ), ], ), ( "includes", [ "" ], ), ( "helpers", [ "", ], ), ) ADDITIONAL_ALNUM_CHARS = [ "_", "-" ] PARSER_REQUIRED_ELEMENT_ATTRS = { "short": None, "description": None, "service": None, } PARSER_OPTIONAL_ELEMENT_ATTRS = { "service": [ "name", "version" ], "port": [ "port", "protocol" ], "protocol": [ "value" ], "module": [ "name" ], "destination": [ "ipv4", "ipv6" ], "source-port": [ "port", "protocol" ], "include": [ "service" ], "helper": [ "name" ], } def __init__(self): super(Service, self).__init__() self.version = "" self.short = "" self.description = "" self.ports = [ ] self.protocols = [ ] self.modules = [ ] self.destination = { } self.source_ports = [ ] self.includes = [ ] self.helpers = [ ] def cleanup(self): self.version = "" self.short = "" self.description = "" del self.ports[:] del self.protocols[:] del self.modules[:] self.destination.clear() del self.source_ports[:] del self.includes[:] del self.helpers[:] def _check_config(self, config, item, all_config, all_io_objects): if item == "ports": for port in config: if port[0] != "": check_port(port[0]) check_tcpudp(port[1]) else: # only protocol check_protocol(port[1]) elif item == "protocols": for proto in config: check_protocol(proto) elif item == "source_ports": for port in config: check_port(port[0]) check_tcpudp(port[1]) elif item == "destination": for destination in config: if destination not in [ "ipv4", "ipv6" ]: raise FirewallError(errors.INVALID_DESTINATION, "'%s' not in {'ipv4'|'ipv6'}" % \ destination) check_address(destination, config[destination]) elif item == "modules": for module in config: if module.startswith("nf_conntrack_"): module = module.replace("nf_conntrack_", "") if "_" in module: module = module.replace("_", "-") if len(module) < 2: raise FirewallError(errors.INVALID_MODULE, module) # PARSER class service_ContentHandler(IO_Object_ContentHandler): def startElement(self, name, attrs): IO_Object_ContentHandler.startElement(self, name, attrs) self.item.parser_check_element_attrs(name, attrs) if name == "service": if "name" in attrs: log.warning("Ignoring deprecated attribute name='%s'", attrs["name"]) if "version" in attrs: self.item.version = attrs["version"] elif name == "short": pass elif name == "description": pass elif name == "port": if attrs["port"] != "": check_port(attrs["port"]) check_tcpudp(attrs["protocol"]) entry = (attrs["port"], attrs["protocol"]) if entry not in self.item.ports: self.item.ports.append(entry) else: log.warning("Port '%s/%s' already set, ignoring.", attrs["port"], attrs["protocol"]) else: check_protocol(attrs["protocol"]) if attrs["protocol"] not in self.item.protocols: self.item.protocols.append(attrs["protocol"]) else: log.warning("Protocol '%s' already set, ignoring.", attrs["protocol"]) elif name == "protocol": check_protocol(attrs["value"]) if attrs["value"] not in self.item.protocols: self.item.protocols.append(attrs["value"]) else: log.warning("Protocol '%s' already set, ignoring.", attrs["value"]) elif name == "source-port": check_port(attrs["port"]) check_tcpudp(attrs["protocol"]) entry = (attrs["port"], attrs["protocol"]) if entry not in self.item.source_ports: self.item.source_ports.append(entry) else: log.warning("SourcePort '%s/%s' already set, ignoring.", attrs["port"], attrs["protocol"]) elif name == "destination": for x in [ "ipv4", "ipv6" ]: if x in attrs: check_address(x, attrs[x]) if x in self.item.destination: log.warning("Destination address for '%s' already set, ignoring", x) else: self.item.destination[x] = attrs[x] elif name == "module": module = attrs["name"] if module.startswith("nf_conntrack_"): module = module.replace("nf_conntrack_", "") if "_" in module: module = module.replace("_", "-") if module not in self.item.modules: self.item.modules.append(module) else: log.warning("Module '%s' already set, ignoring.", module) elif name == "include": if attrs["service"] not in self.item.includes: self.item.includes.append(attrs["service"]) else: log.warning("Include '%s' already set, ignoring.", attrs["service"]) elif name == "helper": if attrs["name"] not in self.item.helpers: self.item.helpers.append(attrs["name"]) else: log.warning("Helper '%s' already set, ignoring.", attrs["name"]) def service_reader(filename, path): service = Service() if not filename.endswith(".xml"): raise FirewallError(errors.INVALID_NAME, "'%s' is missing .xml suffix" % filename) service.name = filename[:-4] service.check_name(service.name) service.filename = filename service.path = path service.builtin = False if path.startswith(config.ETC_FIREWALLD) else True service.default = service.builtin handler = service_ContentHandler(service) parser = sax.make_parser() parser.setContentHandler(handler) name = "%s/%s" % (path, filename) with open(name, "rb") as f: source = sax.InputSource(None) source.setByteStream(f) try: parser.parse(source) except sax.SAXParseException as msg: raise FirewallError(errors.INVALID_SERVICE, "not a valid service file: %s" % \ msg.getException()) del handler del parser return service def service_writer(service, path=None): _path = path if path else service.path if service.filename: name = "%s/%s" % (_path, service.filename) else: name = "%s/%s.xml" % (_path, service.name) if os.path.exists(name): try: shutil.copy2(name, "%s.old" % name) except Exception as msg: log.error("Backup of file '%s' failed: %s", name, msg) dirpath = os.path.dirname(name) if dirpath.startswith(config.ETC_FIREWALLD) and not os.path.exists(dirpath): if not os.path.exists(config.ETC_FIREWALLD): os.mkdir(config.ETC_FIREWALLD, 0o750) os.mkdir(dirpath, 0o750) f = io.open(name, mode='wt', encoding='UTF-8') handler = IO_Object_XMLGenerator(f) handler.startDocument() # start service element attrs = {} if service.version and service.version != "": attrs["version"] = service.version handler.startElement("service", attrs) handler.ignorableWhitespace("\n") # short if service.short and service.short != "": handler.ignorableWhitespace(" ") handler.startElement("short", { }) handler.characters(service.short) handler.endElement("short") handler.ignorableWhitespace("\n") # description if service.description and service.description != "": handler.ignorableWhitespace(" ") handler.startElement("description", { }) handler.characters(service.description) handler.endElement("description") handler.ignorableWhitespace("\n") # ports for port in service.ports: handler.ignorableWhitespace(" ") handler.simpleElement("port", { "port": port[0], "protocol": port[1] }) handler.ignorableWhitespace("\n") # protocols for protocol in service.protocols: handler.ignorableWhitespace(" ") handler.simpleElement("protocol", { "value": protocol }) handler.ignorableWhitespace("\n") # source ports for port in service.source_ports: handler.ignorableWhitespace(" ") handler.simpleElement("source-port", { "port": port[0], "protocol": port[1] }) handler.ignorableWhitespace("\n") # modules for module in service.modules: handler.ignorableWhitespace(" ") handler.simpleElement("module", { "name": module }) handler.ignorableWhitespace("\n") # destination if len(service.destination) > 0: handler.ignorableWhitespace(" ") handler.simpleElement("destination", service.destination) handler.ignorableWhitespace("\n") # includes for include in service.includes: handler.ignorableWhitespace(" ") handler.simpleElement("include", { "service": include }) handler.ignorableWhitespace("\n") # helpers for helper in service.helpers: handler.ignorableWhitespace(" ") handler.simpleElement("helper", { "name": helper }) handler.ignorableWhitespace("\n") # end service element handler.endElement('service') handler.ignorableWhitespace("\n") handler.endDocument() f.close() del handler
| ver. 1.4 |
Github
|
.
| PHP 8.2.28 | Generation time: 0.02 |
proxy
|
phpinfo
|
Settings