desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Test that calling scale on a service that has a custom container name results in warning output.'
@mock.patch(u'compose.service.log') def test_scale_with_custom_container_name_outputs_warning(self, mock_log):
service = self.create_service(u'app', container_name=u'custom-container') self.assertEqual(service.custom_container_name, u'custom-container') with pytest.raises(OperationFailedError): service.scale(3) captured_output = mock_log.warn.call_args[0][0] self.assertEqual(len(service.containers())...
'Return the name of the container that caused the cascade_stop'
def test_item_is_stop_with_cascade_stop(self):
queue = Queue() for item in (QueueItem.stop(u'foobar-1'), QueueItem.new(u'a'), QueueItem.new(u'b')): queue.put(item) generator = consume_queue(queue, True) assert (next(generator) is u'foobar-1')
'When you set a \'memswap_limit\' it is invalid config unless you also set a mem_limit'
def test_validation_fails_with_just_memswap_limit(self):
with pytest.raises(ConfigurationError) as excinfo: config.load(build_config_details({u'foo': {u'image': u'busybox', u'memswap_limit': 2000000}}, u'tests/fixtures/extends', u'filename.yml')) assert (u"foo.memswap_limit is invalid: when defining 'memswap_limit' you must set 'mem...
'We specify a \'file\' key that is the filename we\'re already in.'
def test_self_referencing_file(self):
service_dicts = load_from_filename(u'tests/fixtures/extends/specify-file-as-self.yml') self.assertEqual(service_sort(service_dicts), service_sort([{u'environment': {u'YEP': u'1', u'BAR': u'1', u'BAZ': u'3'}, u'image': u'busybox', u'name': u'myweb'}, {u'environment': {u'YEP': u'1'}, u'image': u'busybox', u'name'...
'Test not specifying a file in our extends options that the config is valid and correctly extends from itself.'
def test_extends_file_defaults_to_self(self):
service_dicts = load_from_filename(u'tests/fixtures/extends/no-file-specified.yml') self.assertEqual(service_sort(service_dicts), service_sort([{u'name': u'myweb', u'image': u'busybox', u'environment': {u'BAR': u'1', u'BAZ': u'3'}}, {u'name': u'web', u'image': u'busybox', u'environment': {u'BAZ': u'3'}}]))
'Test with files placed in the subdir'
def test_get_config_path_default_file_in_parent_dir(self):
def get_config_in_subdir(files): return get_config_filename_for_files(files, subdir=True) for (index, filename) in enumerate(self.files): self.assertEqual(filename, get_config_in_subdir(self.files[index:])) with self.assertRaises(config.ComposeFileNotFound): get_config_in_subdir([])
'Build or rebuild services. Services are built once and then tagged as `project_service`, e.g. `composetest_db`. If you change a service\'s `Dockerfile` or the contents of its build directory, you can run `docker-compose build` to rebuild it. Usage: build [options] [--build-arg key=val...] [SERVICE...] Options: --force...
def build(self, options):
service_names = options[u'SERVICE'] build_args = options.get(u'--build-arg', None) if build_args: environment = Environment.from_env_file(self.project_dir) build_args = resolve_build_args(build_args, environment) if ((not service_names) and build_args): raise UserError(u'Need ...
'Generate a Distributed Application Bundle (DAB) from the Compose file. Images must have digests stored, which requires interaction with a Docker registry. If digests aren\'t stored for all images, you can fetch them with `docker-compose pull` or `docker-compose push`. To push images automatically when bundling, pass `...
def bundle(self, config_options, options):
self.project = project_from_options(u'.', config_options) compose_config = get_config_from_options(self.project_dir, config_options) output = options[u'--output'] if (not output): output = u'{}.dab'.format(self.project.name) image_digests = image_digests_for_project(self.project, options[u'-...
'Validate and view the Compose file. Usage: config [options] Options: --resolve-image-digests Pin image tags to digests. -q, --quiet Only validate the configuration, don\'t print anything. --services Print the service names, one per line. --volumes Print the volume names, one ...
def config(self, config_options, options):
compose_config = get_config_from_options(self.project_dir, config_options) image_digests = None if options[u'--resolve-image-digests']: self.project = project_from_options(u'.', config_options) image_digests = image_digests_for_project(self.project) if options[u'--quiet']: return...
'Creates containers for a service. Usage: create [options] [SERVICE...] Options: --force-recreate Recreate containers even if their configuration and image haven\'t changed. Incompatible with --no-recreate. --no-recreate If containers already exist, don\'t recreate them. Incompatible with --force-recreat...
def create(self, options):
service_names = options[u'SERVICE'] self.project.create(service_names=service_names, strategy=convergence_strategy_from_opts(options), do_build=build_action_from_opts(options))
'Stops containers and removes containers, networks, volumes, and images created by `up`. By default, the only things removed are: - Containers for services defined in the Compose file - Networks defined in the `networks` section of the Compose file - The default network, if one is used Networks and volumes defined as `...
def down(self, options):
image_type = image_type_from_opt(u'--rmi', options[u'--rmi']) self.project.down(image_type, options[u'--volumes'], options[u'--remove-orphans'])
'Receive real time events from containers. Usage: events [options] [SERVICE...] Options: --json Output events as a stream of json objects'
def events(self, options):
def format_event(event): attributes = [(u'%s=%s' % item) for item in event[u'attributes'].items()] return u'{time} {type} {action} {id} ({attrs})'.format(attrs=u', '.join(sorted(attributes)), **event) def json_format_event(event): event[u'time'] = event[u'time'].isoformat(...
'Execute a command in a running container Usage: exec [options] SERVICE COMMAND [ARGS...] Options: -d Detached mode: Run command in the background. --privileged Give extended privileges to the process. -u, --user USER Run the command as this user. -T Disable pseudo-tty allocation. B...
def exec_command(self, options):
index = int(options.get(u'--index')) service = self.project.get_service(options[u'SERVICE']) detach = options[u'-d'] try: container = service.get_container(number=index) except ValueError as e: raise UserError(str(e)) command = ([options[u'COMMAND']] + options[u'ARGS']) tty =...
'Get help on a command. Usage: help [COMMAND]'
@classmethod def help(cls, options):
if options[u'COMMAND']: subject = get_handler(cls, options[u'COMMAND']) else: subject = cls print(getdoc(subject))
'List images used by the created containers. Usage: images [options] [SERVICE...] Options: -q Only display IDs'
def images(self, options):
containers = sorted((self.project.containers(service_names=options[u'SERVICE'], stopped=True) + self.project.containers(service_names=options[u'SERVICE'], one_off=OneOffFilter.only)), key=attrgetter(u'name')) if options[u'-q']: for image in set((c.image for c in containers)): print(image.spl...
'Force stop service containers. Usage: kill [options] [SERVICE...] Options: -s SIGNAL SIGNAL to send to the container. Default signal is SIGKILL.'
def kill(self, options):
signal = options.get(u'-s', u'SIGKILL') self.project.kill(service_names=options[u'SERVICE'], signal=signal)
'View output from containers. Usage: logs [options] [SERVICE...] Options: --no-color Produce monochrome output. -f, --follow Follow log output. -t, --timestamps Show timestamps. --tail="all" Number of lines to show from the end of the logs for each container.'
def logs(self, options):
containers = self.project.containers(service_names=options[u'SERVICE'], stopped=True) tail = options[u'--tail'] if (tail is not None): if tail.isdigit(): tail = int(tail) elif (tail != u'all'): raise UserError(u'tail flag must be all or a number')...
'Pause services. Usage: pause [SERVICE...]'
def pause(self, options):
containers = self.project.pause(service_names=options[u'SERVICE']) exit_if((not containers), u'No containers to pause', 1)
'Print the public port for a port binding. Usage: port [options] SERVICE PRIVATE_PORT Options: --protocol=proto tcp or udp [default: tcp] --index=index index of the container if there are multiple instances of a service [default: 1]'
def port(self, options):
index = int(options.get(u'--index')) service = self.project.get_service(options[u'SERVICE']) try: container = service.get_container(number=index) except ValueError as e: raise UserError(str(e)) print((container.get_local_port(options[u'PRIVATE_PORT'], protocol=(options.get(u'--protoc...
'List containers. Usage: ps [options] [SERVICE...] Options: -q Only display IDs'
def ps(self, options):
containers = sorted((self.project.containers(service_names=options[u'SERVICE'], stopped=True) + self.project.containers(service_names=options[u'SERVICE'], one_off=OneOffFilter.only)), key=attrgetter(u'name')) if options[u'-q']: for container in containers: print(container.id) else: ...
'Pulls images for services defined in a Compose file, but does not start the containers. Usage: pull [options] [SERVICE...] Options: --ignore-pull-failures Pull what it can and ignores images with pull failures. --parallel Pull multiple images in parallel. --quiet Pull without printing pro...
def pull(self, options):
self.project.pull(service_names=options[u'SERVICE'], ignore_pull_failures=options.get(u'--ignore-pull-failures'), parallel_pull=options.get(u'--parallel'), silent=options.get(u'--quiet'))
'Pushes images for services. Usage: push [options] [SERVICE...] Options: --ignore-push-failures Push what it can and ignores images with push failures.'
def push(self, options):
self.project.push(service_names=options[u'SERVICE'], ignore_push_failures=options.get(u'--ignore-push-failures'))
'Removes stopped service containers. By default, anonymous volumes attached to containers will not be removed. You can override this with `-v`. To list all volumes, use `docker volume ls`. Any data which is not in a volume will be lost. Usage: rm [options] [SERVICE...] Options: -f, --force Don\'t ask to confirm remov...
def rm(self, options):
if options.get(u'--all'): log.warn(u'--all flag is obsolete. This is now the default behavior of `docker-compose rm`') one_off = OneOffFilter.include if options.get(u'--stop'): self.project.stop(service_names=options[u'SERVICE'], one_off=one_off) all_c...
'Run a one-off command on a service. For example: $ docker-compose run web python manage.py shell By default, linked services will be started, unless they are already running. If you do not want to start linked services, use `docker-compose run --no-deps SERVICE COMMAND [ARGS...]`. Usage: run [options] [-v VOLUME...] [...
def run(self, options):
service = self.project.get_service(options[u'SERVICE']) detach = options[u'-d'] if (options[u'--publish'] and options[u'--service-ports']): raise UserError(u'Service port mapping and manual port mapping can not be used together') if (options[u'COMMAND'] is not No...
'Set number of containers to run for a service. Numbers are specified in the form `service=num` as arguments. For example: $ docker-compose scale web=2 worker=3 This command is deprecated. Use the up command with the `--scale` flag instead. Usage: scale [options] [SERVICE=NUM...] Options: -t, --timeout TIMEOUT Spe...
def scale(self, options):
timeout = timeout_from_opts(options) if (self.project.config_version == V2_2): raise UserError(u'The scale command is incompatible with the v2.2 format. Use the up command with the --scale flag instead.') else: log.warn(u'The scale com...
'Start existing containers. Usage: start [SERVICE...]'
def start(self, options):
containers = self.project.start(service_names=options[u'SERVICE']) exit_if((not containers), u'No containers to start', 1)
'Stop running containers without removing them. They can be started again with `docker-compose start`. Usage: stop [options] [SERVICE...] Options: -t, --timeout TIMEOUT Specify a shutdown timeout in seconds. (default: 10)'
def stop(self, options):
timeout = timeout_from_opts(options) self.project.stop(service_names=options[u'SERVICE'], timeout=timeout)
'Restart running containers. Usage: restart [options] [SERVICE...] Options: -t, --timeout TIMEOUT Specify a shutdown timeout in seconds. (default: 10)'
def restart(self, options):
timeout = timeout_from_opts(options) containers = self.project.restart(service_names=options[u'SERVICE'], timeout=timeout) exit_if((not containers), u'No containers to restart', 1)
'Display the running processes Usage: top [SERVICE...]'
def top(self, options):
containers = sorted((self.project.containers(service_names=options[u'SERVICE'], stopped=False) + self.project.containers(service_names=options[u'SERVICE'], one_off=OneOffFilter.only)), key=attrgetter(u'name')) for (idx, container) in enumerate(containers): if (idx > 0): print() top_d...
'Unpause services. Usage: unpause [SERVICE...]'
def unpause(self, options):
containers = self.project.unpause(service_names=options[u'SERVICE']) exit_if((not containers), u'No containers to unpause', 1)
'Builds, (re)creates, starts, and attaches to containers for a service. Unless they are already running, this command also starts any linked services. The `docker-compose up` command aggregates the output of each container. When the command exits, all containers are stopped. Running `docker-compose up -d` starts the co...
def up(self, options):
start_deps = (not options[u'--no-deps']) exit_value_from = exitval_from_opts(options, self.project) cascade_stop = options[u'--abort-on-container-exit'] service_names = options[u'SERVICE'] timeout = timeout_from_opts(options) remove_orphans = options[u'--remove-orphans'] detached = options.g...
'Show version informations Usage: version [--short] Options: --short Shows only Compose\'s version number.'
@classmethod def version(cls, options):
if options[u'--short']: print(__version__) else: print(get_version_info(u'full'))
'Construct a Project from a config.Config object.'
@classmethod def from_config(cls, name, config_data, client):
use_networking = (config_data.version and (config_data.version != V1)) networks = build_networks(name, config_data, client) project_networks = ProjectNetworks.from_services(config_data.services, networks, use_networking) volumes = ProjectVolumes.from_config(name, config_data, client) project = cls(n...
'Retrieve a service by name. Raises NoSuchService if the named service does not exist.'
def get_service(self, name):
for service in self.services: if (service.name == name): return service raise NoSuchService(name)
'Validate that the given list of service names only contains valid services. Raises NoSuchService if one of the names is invalid.'
def validate_service_names(self, service_names):
valid_names = self.service_names for name in service_names: if (name not in valid_names): raise NoSuchService(name)
'Returns a list of this project\'s services filtered by the provided list of names, or all services if service_names is None or []. If include_deps is specified, returns a list including the dependencies for service_names, in order of dependency. Preserves the original order of self.services where possible, reordering ...
def get_services(self, service_names=None, include_deps=False):
if ((service_names is None) or (len(service_names) == 0)): service_names = self.service_names unsorted = [self.get_service(name) for name in service_names] services = [s for s in self.services if (s in unsorted)] if include_deps: services = reduce(self._inject_deps, services, []) uni...
'Return a :class:`compose.container.Container` for this service. The container must be active, and match `number`.'
def get_container(self, number=1):
labels = (self.labels() + [u'{0}={1}'.format(LABEL_CONTAINER_NUMBER, number)]) for container in self.client.containers(filters={u'label': labels}): return Container.from_ps(self.client, container) raise ValueError((u'No container found for %s_%s' % (self.name, number)))
'Adjusts the number of containers to the specified number and ensures they are running. - creates containers until there are at least `desired_num` - stops containers until there are at most `desired_num` running - starts containers until there are at least `desired_num` running - removes all stopped containers'
def scale(self, desired_num, timeout=None):
self.show_scale_warnings(desired_num) running_containers = self.containers(stopped=False) num_running = len(running_containers) if (desired_num == num_running): log.info(u'Desired container number already achieved') return if (desired_num > num_running): all_conta...
'Create a container for this service. If the image doesn\'t exist, attempt to pull it.'
def create_container(self, one_off=False, previous_container=None, number=None, quiet=False, **override_options):
self.ensure_image_exists() container_options = self._get_container_create_options(override_options, (number or self._next_container_number(one_off=one_off)), one_off=one_off, previous_container=previous_container) if ((u'name' in container_options) and (not quiet)): log.info((u'Creating %s' % con...
'Recreate a container. The original container is renamed to a temporary name so that data volumes can be copied to the new container, before the original container is removed.'
def recreate_container(self, container, timeout=None, attach_logs=False, start_new_container=True):
log.info((u'Recreating %s' % container.name)) container.stop(timeout=self.stop_timeout(timeout)) container.rename_to_tmp_name() new_container = self.create_container(previous_container=container, number=container.labels.get(LABEL_CONTAINER_NUMBER), quiet=True) if attach_logs: new_containe...
'Check that all containers for this service report healthy. Returns false if at least one healthcheck is pending. If an unhealthy container is detected, raise a HealthCheckFailed exception.'
def is_healthy(self):
result = True for ctnr in self.containers(): ctnr.inspect() status = ctnr.get(u'State.Health.Status') if (status is None): raise NoHealthCheckConfigured(self.name) elif (status == u'starting'): result = False elif (status == u'unhealthy'): ...
'Service we are extending either has a value for \'file\' set, which we need to obtain a full path too or we are extending from a service defined in our own file.'
def get_extended_config_path(self, extends_options):
filename = self.service_config.filename validate_extends_file_path(self.service_config.name, extends_options, filename) if (u'file' in extends_options): return expand_path(self.working_dir, extends_options[u'file']) return filename
'Parse a volume_config path and split it into external:internal[:mode] parts to be returned as a valid VolumeSpec.'
@classmethod def parse(cls, volume_config, normalize=False):
if IS_WINDOWS_PLATFORM: return cls._parse_win32(volume_config, normalize) else: return cls._parse_unix(volume_config)
'Construct a container object from the output of GET /containers/json.'
@classmethod def from_ps(cls, client, dictionary, **kwargs):
name = get_container_name(dictionary) if (name is None): return None new_dictionary = {u'Id': dictionary[u'Id'], u'Image': dictionary[u'Image'], u'Name': (u'/' + name)} return cls(client, new_dictionary, **kwargs)
'A log stream can only be attached if the container uses a json-file log driver.'
def attach_log_stream(self):
if self.has_api_logs: self.log_stream = self.attach(stdout=True, stderr=True, stream=True)
'Return a value from the container or None if the value is not set. :param key: a string using dotted notation for nested dictionary lookups'
def get(self, key):
self.inspect_if_not_inspected() def get_value(dictionary, key): return (dictionary or {}).get(key) return reduce(get_value, key.split(u'.'), self.dictionary)
'Rename the container to a hopefully unique temporary container name by prepending the short id.'
def rename_to_tmp_name(self):
self.client.rename(self.id, (u'%s_%s' % (self.short_id, self.name)))
'Return a representation that allows this object to be sorted correctly with the default comparator.'
@property def order(self):
rc = ((0, self.rc) if self.rc else (1,)) return ((int(self.major), int(self.minor), int(self.patch)) + rc)
'Init internal variables.'
def __init__(self):
PlugIn.__init__(self) self.DBG_LINE = 'roster' self._data = {} self.set = None self._exported_methods = [self.getRoster]
'Register presence and subscription trackers in the owner\'s dispatcher. Also request roster from server if the \'request\' argument is set. Used internally.'
def plugin(self, owner, request=1):
self._owner.RegisterHandler('iq', self.RosterIqHandler, 'result', NS_ROSTER) self._owner.RegisterHandler('iq', self.RosterIqHandler, 'set', NS_ROSTER) self._owner.RegisterHandler('presence', self.PresenceHandler) if request: self.Request()
'Request roster from server if it were not yet requested (or if the \'force\' argument is set).'
def Request(self, force=0):
if (self.set is None): self.set = 0 elif (not force): return self._owner.send(Iq('get', NS_ROSTER)) self.DEBUG('Roster requested from server', 'start')
'Requests roster from server if neccessary and returns self.'
def getRoster(self):
if (not self.set): self.Request() while (not self.set): self._owner.Process(10) return self
'Subscription tracker. Used internally for setting items state in internal roster representation.'
def RosterIqHandler(self, dis, stanza):
for item in stanza.getTag('query').getTags('item'): jid = item.getAttr('jid') if (item.getAttr('subscription') == 'remove'): if self._data.has_key(jid): del self._data[jid] raise NodeProcessed self.DEBUG(('Setting roster item %s...' % jid), 'o...
'Presence tracker. Used internally for setting items\' resources state in internal roster representation.'
def PresenceHandler(self, dis, pres):
jid = JID(pres.getFrom()) if (not self._data.has_key(jid.getStripped())): self._data[jid.getStripped()] = {'name': None, 'ask': None, 'subscription': 'none', 'groups': ['Not in roster'], 'resources': {}} item = self._data[jid.getStripped()] typ = pres.getType() if (not typ): se...
'Return specific jid\'s representation in internal format. Used internally.'
def _getItemData(self, jid, dataname):
jid = jid[:(jid + '/').find('/')] return self._data[jid][dataname]
'Return specific jid\'s resource representation in internal format. Used internally.'
def _getResourceData(self, jid, dataname):
if (jid.find('/') + 1): (jid, resource) = jid.split('/', 1) if self._data[jid]['resources'].has_key(resource): return self._data[jid]['resources'][resource][dataname] elif self._data[jid]['resources'].keys(): lastpri = (-129) for r in self._data[jid]['resources'].keys...
'Delete contact \'jid\' from roster.'
def delItem(self, jid):
self._owner.send(Iq('set', NS_ROSTER, payload=[Node('item', {'jid': jid, 'subscription': 'remove'})]))
'Returns \'ask\' value of contact \'jid\'.'
def getAsk(self, jid):
return self._getItemData(jid, 'ask')
'Returns groups list that contact \'jid\' belongs to.'
def getGroups(self, jid):
return self._getItemData(jid, 'groups')
'Returns name of contact \'jid\'.'
def getName(self, jid):
return self._getItemData(jid, 'name')
'Returns priority of contact \'jid\'. \'jid\' should be a full (not bare) JID.'
def getPriority(self, jid):
return self._getResourceData(jid, 'priority')
'Returns roster representation in internal format.'
def getRawRoster(self):
return self._data
'Returns roster item \'jid\' representation in internal format.'
def getRawItem(self, jid):
return self._data[jid[:(jid + '/').find('/')]]
'Returns \'show\' value of contact \'jid\'. \'jid\' should be a full (not bare) JID.'
def getShow(self, jid):
return self._getResourceData(jid, 'show')
'Returns \'status\' value of contact \'jid\'. \'jid\' should be a full (not bare) JID.'
def getStatus(self, jid):
return self._getResourceData(jid, 'status')
'Returns \'subscription\' value of contact \'jid\'.'
def getSubscription(self, jid):
return self._getItemData(jid, 'subscription')
'Returns list of connected resources of contact \'jid\'.'
def getResources(self, jid):
return self._data[jid[:(jid + '/').find('/')]]['resources'].keys()
'Creates/renames contact \'jid\' and sets the groups list that it now belongs to.'
def setItem(self, jid, name=None, groups=[]):
iq = Iq('set', NS_ROSTER) query = iq.getTag('query') attrs = {'jid': jid} if name: attrs['name'] = name item = query.setTag('item', attrs) for group in groups: item.addChild(node=Node('group', payload=[group])) self._owner.send(iq)
'Return list of all [bare] JIDs that the roster is currently tracks.'
def getItems(self):
return self._data.keys()
'Same as getItems. Provided for the sake of dictionary interface.'
def keys(self):
return self._data.keys()
'Get the contact in the internal format. Raises KeyError if JID \'item\' is not in roster.'
def __getitem__(self, item):
return self._data[item]
'Get the contact in the internal format (or None if JID \'item\' is not in roster).'
def getItem(self, item):
if self._data.has_key(item): return self._data[item]
'Send subscription request to JID \'jid\'.'
def Subscribe(self, jid):
self._owner.send(Presence(jid, 'subscribe'))
'Ask for removing our subscription for JID \'jid\'.'
def Unsubscribe(self, jid):
self._owner.send(Presence(jid, 'unsubscribe'))
'Authorise JID \'jid\'. Works only if these JID requested auth previously.'
def Authorize(self, jid):
self._owner.send(Presence(jid, 'subscribed'))
'Unauthorise JID \'jid\'. Use for declining authorisation request or for removing existing authorization.'
def Unauthorize(self, jid):
self._owner.send(Presence(jid, 'unsubscribed'))
'Return set of user-registered callbacks in it\'s internal format. Used within the library to carry user handlers set over Dispatcher replugins.'
def dumpHandlers(self):
return self.handlers
'Restores user-registered callbacks structure from dump previously obtained via dumpHandlers. Used within the library to carry user handlers set over Dispatcher replugins.'
def restoreHandlers(self, handlers):
self.handlers = handlers
'Registers default namespaces/protocols/handlers. Used internally.'
def _init(self):
self.RegisterNamespace('unknown') self.RegisterNamespace(NS_STREAMS) self.RegisterNamespace(self._owner.defaultNamespace) self.RegisterProtocol('iq', Iq) self.RegisterProtocol('presence', Presence) self.RegisterProtocol('message', Message) self.RegisterDefaultHandler(self.returnStanzaHandler...
'Plug the Dispatcher instance into Client class instance and send initial stream header. Used internally.'
def plugin(self, owner):
self._init() for method in self._old_owners_methods: if (method.__name__ == 'send'): self._owner_send = method break self._owner.lastErrNode = None self._owner.lastErr = None self._owner.lastErrCode = None self.StreamInit()
'Prepares instance to be destructed.'
def plugout(self):
self.Stream.dispatch = None self.Stream.DEBUG = None self.Stream.features = None self.Stream.destroy()
'Send an initial stream header.'
def StreamInit(self):
self.Stream = simplexml.NodeBuilder() self.Stream._dispatch_depth = 2 self.Stream.dispatch = self.dispatch self.Stream.stream_header_received = self._check_stream_start self._owner.debug_flags.append(simplexml.DBG_NODEBUILDER) self.Stream.DEBUG = self._owner.DEBUG self.Stream.features = None...
'Check incoming stream for data waiting. If "timeout" is positive - block for as max. this time. Returns: 1) length of processed data if some data were processed; 2) \'0\' string if no data were processed but link is alive; 3) 0 (zero) if underlying connection is closed. Take note that in case of disconnection detect d...
def Process(self, timeout=0):
for handler in self._cycleHandlers: handler(self) if (len(self._pendingExceptions) > 0): _pendingException = self._pendingExceptions.pop() raise _pendingException[0], _pendingException[1], _pendingException[2] if self._owner.Connection.pending_data(timeout): try: ...
'Creates internal structures for newly registered namespace. You can register handlers for this namespace afterwards. By default one namespace already registered (jabber:client or jabber:component:accept depending on context.'
def RegisterNamespace(self, xmlns, order='info'):
self.DEBUG(('Registering namespace "%s"' % xmlns), order) self.handlers[xmlns] = {} self.RegisterProtocol('unknown', Protocol, xmlns=xmlns) self.RegisterProtocol('default', Protocol, xmlns=xmlns)
'Used to declare some top-level stanza name to dispatcher. Needed to start registering handlers for such stanzas. Iq, message and presence protocols are registered by default.'
def RegisterProtocol(self, tag_name, Proto, xmlns=None, order='info'):
if (not xmlns): xmlns = self._owner.defaultNamespace self.DEBUG(('Registering protocol "%s" as %s(%s)' % (tag_name, Proto, xmlns)), order) self.handlers[xmlns][tag_name] = {type: Proto, 'default': []}
'Register handler for processing all stanzas for specified namespace.'
def RegisterNamespaceHandler(self, xmlns, handler, typ='', ns='', makefirst=0, system=0):
self.RegisterHandler('default', handler, typ, ns, xmlns, makefirst, system)
'Register user callback as stanzas handler of declared type. Callback must take (if chained, see later) arguments: dispatcher instance (for replying), incomed return of previous handlers. The callback must raise xmpp.NodeProcessed just before return if it want preven callbacks to be called with the same stanza as argum...
def RegisterHandler(self, name, handler, typ='', ns='', xmlns=None, makefirst=0, system=0):
if (not xmlns): xmlns = self._owner.defaultNamespace self.DEBUG(('Registering handler %s for "%s" type->%s ns->%s(%s)' % (handler, name, typ, ns, xmlns)), 'info') if ((not typ) and (not ns)): typ = 'default' if (not self.handlers.has_key(xmlns)): self.RegisterNa...
'Unregister handler after first call (not implemented yet).'
def RegisterHandlerOnce(self, name, handler, typ='', ns='', xmlns=None, makefirst=0, system=0):
if (not xmlns): xmlns = self._owner.defaultNamespace self.RegisterHandler(name, handler, typ, ns, xmlns, makefirst, system)
'Unregister handler. "typ" and "ns" must be specified exactly the same as with registering.'
def UnregisterHandler(self, name, handler, typ='', ns='', xmlns=None):
if (not xmlns): xmlns = self._owner.defaultNamespace if (not self.handlers.has_key(xmlns)): return if ((not typ) and (not ns)): typ = 'default' for pack in self.handlers[xmlns][name][(typ + ns)]: if (handler == pack['func']): break else: pack = Non...
'Specify the handler that will be used if no NodeProcessed exception were raised. This is returnStanzaHandler by default.'
def RegisterDefaultHandler(self, handler):
self._defaultHandler = handler
'Register handler that will process events. F.e. "FILERECEIVED" event.'
def RegisterEventHandler(self, handler):
self._eventHandler = handler
'Return stanza back to the sender with <feature-not-implemennted/> error set.'
def returnStanzaHandler(self, conn, stanza):
if (stanza.getType() in ['get', 'set']): conn.send(Error(stanza, ERR_FEATURE_NOT_IMPLEMENTED))
'Register handler that will be called on every Dispatcher.Process() call.'
def RegisterCycleHandler(self, handler):
if (handler not in self._cycleHandlers): self._cycleHandlers.append(handler)
'Unregister handler that will is called on every Dispatcher.Process() call.'
def UnregisterCycleHandler(self, handler):
if (handler in self._cycleHandlers): self._cycleHandlers.remove(handler)
'Raise some event. Takes three arguments: 1) "realm" - scope of event. Usually a namespace. 2) "event" - the event itself. F.e. "SUCESSFULL SEND". 3) data that comes along with event. Depends on event.'
def Event(self, realm, event, data):
if self._eventHandler: self._eventHandler(realm, event, data)
'Main procedure that performs XMPP stanza recognition and calling apppropriate handlers for it. Called internally.'
def dispatch(self, stanza, session=None, direct=0):
if (not session): session = self session.Stream._mini_dom = None name = stanza.getName() if ((not direct) and self._owner._route): if (name == 'route'): if (stanza.getAttr('error') == None): if (len(stanza.getChildren()) == 1): stanza = sta...
'Block and wait until stanza with specific "id" attribute will come. If no such stanza is arrived within timeout, return None. If operation failed for some reason then owner\'s attributes lastErrNode, lastErr and lastErrCode are set accordingly.'
def WaitForResponse(self, ID, timeout=DefaultTimeout):
self._expected[ID] = None has_timed_out = 0 abort_time = (time.time() + timeout) self.DEBUG(('Waiting for ID:%s with timeout %s...' % (ID, timeout)), 'wait') while (not self._expected[ID]): if (not self.Process(0.04)): self._owner.lastErr = 'Disconnect' ...
'Put stanza on the wire and wait for recipient\'s response to it.'
def SendAndWaitForResponse(self, stanza, timeout=DefaultTimeout):
return self.WaitForResponse(self.send(stanza), timeout)
'Put stanza on the wire and call back when recipient replies. Additional callback arguments can be specified in args.'
def SendAndCallForResponse(self, stanza, func, args={}):
self._expected[self.send(stanza)] = (func, args)
'Serialise stanza and put it on the wire. Assign an unique ID to it before send. Returns assigned ID.'
def send(self, stanza):
if (type(stanza) in [type(''), type(u'')]): return self._owner_send(stanza) if (not isinstance(stanza, Protocol)): _ID = None elif (not stanza.getID()): global ID ID += 1 _ID = `ID` stanza.setID(_ID) else: _ID = stanza.getID() if (self._owner._...