def __call__(self, *args, **kwargs): cli = self.swarm.client if cli is not None: rm_flag = kwargs.pop('rm') logs = kwargs.pop('logs') try: ret = cli.create_container(*args, **kwargs) if ret.get('Warnings') is not None: print('[Warning] {message}'.format(message=ret['Warnings'])) # try to start created container if ret.get('Id') is not None: if kwargs['stdin_open'] and kwargs['tty']: dockerpty.start(cli, ret['Id'], logs=logs) else: cli.start(ret['Id']) print(ret['Id']) if rm_flag: cli.remove_container(ret['Id']) except (errors.NotFound, errors.APIError, errors.DockerException) as e: pyprint(e.explanation) # volumes_from and dns arguments raise TypeError exception # if they are used against v1.10 and above of the Docker remote API except TypeError as e: pyprint(e) finally: cli.close()
def client(self): base_url = self._get_base_url() if base_url is not None: try: tls = False _tlsconfig = self._get_tlsconfig() if _tlsconfig is not None: client_cert = (_tlsconfig.get('tlscert'), _tlsconfig.get('tlskey')) ca_cert = _tlsconfig.get('tlscacert') verify = True if _tlsconfig.get( 'tlsverify') == '1' else False tls = TLSConfig(client_cert=client_cert, ca_cert=ca_cert, verify=verify) cli = Client(base_url, version=self.version, timeout=3, tls=tls) # Hits the /_ping endpoint of the remote API and returns the result. # An exception will be raised if the endpoint isn't responding. if cli.ping() == 'OK': cli.close() return Client(base_url, version=self.version, timeout=600, tls=tls) return except errors.DockerException as e: pyprint(e) return print('No available swarm api') return
def _get_tlsconfig(self): try: with open(self._config, 'r') as fp: data = json.load(fp) current = data['current'] tlsconfig = data.get('tlsconfig', {}).get(current, {}) return tlsconfig if tlsconfig else None except IOError as e: pyprint(e) return except OSError: raise
def _get_containers(self, show_all=False, filters={}, limit=None, latest=None, since=None): """ :param show_all(bool): Show all containers. Only running containers are shown by default :param filters(dict): Filters to be processed on the image list :parma limit(tuple or list): Filter containers by node name or node pattern :param latest(bool): Show only the latest created container, include non-running ones :param since(str): Show only containers created since Id or Name, include non-running containers """ cli = self.swarm.client if cli is not None: try: ret = cli.containers(all=show_all, filters=filters, latest=latest, since=since) except (errors.NotFound, errors.APIError, errors.DockerException) as e: pyprint(e.explanation) return finally: cli.close() if ret: for container in ret: # if limit is provide, then get containers against it node = container['Names'][0].split('/', 2)[1] if limit is not None: if not node in limit: continue # 'Names' includes self container name as well as names of linked containers # Filter name by checking '/' for names in container['Names']: if names.count('/') == 2: name = names.split('/')[2] break # convert created timestamp to human-readable string created_delta = datetime.now() - datetime.fromtimestamp(container['Created']) if created_delta.days > 1: created = '{day} days ago'.format(day=created_delta.days) else: created = timeformat(created_delta.seconds + created_delta.days * 86400) # get the longest node/created/status field length for pretty print self.node_length = len(node) if len(node) > self.node_length else self.node_length self.image_length = len(container['Image']) if len(container['Image']) > self.image_length\ else self.image_length if len(container['Command']) < self.command_length: command = container['Command'] else: command = container['Command'] if len(container['Command']) < self.max_command_length\ else container['Command'][:self.max_command_length] self.command_length = len(container['Command']) if len(container['Command']) < self.max_command_length\ else self.max_command_length self.created_length = len(created) if len(created) > self.created_length else self.created_length self.status_length = len(container['Status']) if len(container['Status']) > self.status_length else self.status_length # (Id, Node, Image, Command, Created, Status, Names) data = (container['Id'], node, container['Image'], command, created, container['Status'], name) self.containers.setdefault(node, []).append(data)
def _get_images(self, name=None, show_all=False, filters={}, image_list=None): """ :param name(str): Only show images belonging to the repository name :param show_all(bool): Show all images (by default filter out the intermediate image layers) :parma filters(dict): Filters to be applied on the image list :param image_list(list): List of image id or name """ cli = self.swarm.client if cli is not None: try: ret = cli.images(name=name, all=show_all, filters=filters) except (errors.NotFound, errors.APIError, errors.DockerException) as e: pyprint(e.explanation) return finally: cli.close() if ret: for image in ret: # if image_list provide, then get images against it if image_list is not None: if not image['Id'].startswith(image_list)\ and not image['RepoTags'].startswith(image_list): continue image_id = image['Id'][:12] # convert created timestamp to human-readable string created_delta = datetime.now() - datetime.fromtimestamp( image['Created']) if created_delta.days > 1: created = '{day} days ago'.format( day=created_delta.days) else: created = timeformat(created_delta.seconds + created_delta.days * 86400) # convert virtual size to human-readable string virtual_size = byteformat(image['VirtualSize'], base=1000) # get the longest created field length for pretty print self.created_length = len(created) if len(created) > self.created_length\ else self.created_length for repotag in image['RepoTags']: repo, tag = repotag.split(':') data = (repo, tag, image_id, created, virtual_size) self.images.add(data) # get the longest repo/tag field length for pretty print self.repo_length = len(repo) if len( repo) > self.repo_length else self.repo_length self.tag_length = len(tag) if len( tag) > self.tag_length else self.tag_length
def __call__(self, container, name): """ :param container(str): ID of the container to rename :param name(str): New name for the container """ cli = self.swarm.client if cli is not None: try: cli.rename(container, name) except (errors.NotFound, errors.APIError, errors.DockerException) as e: pyprint(e.explanation) finally: cli.close()
def __call__(self, container, ps_args): """ :param container(str): The container to inspect :param ps_args(str): An optional arguments passed to ps (e.g., aux) """ cli = self.swarm.client if cli is not None: try: self.ret = cli.top(container, ps_args) except (errors.NotFound, errors.APIError, errors.DockerException) as e: pyprint(e.explanation) finally: cli.close() self._pretty_print()
def _get_version(self): try: with open(self._config, 'r') as fp: data = json.load(fp) try: if data['version']: return data['version'] return except KeyError: return except IOError as e: pyprint(e) return except OSError: raise
def __call__(self, **kwargs): cli = self.swarm.client if cli is not None: try: for line in cli.build(**kwargs): if line.get('stream') is not None: print(line['stream']), elif line.get('error') is not None: print(line['error']) stdout.flush() except (errors.NotFound, errors.APIError, errors.DockerException) as e: pyprint(e.explanation) except TypeError as e: pyprint(e) finally: cli.close()
def __call__(self, *args, **kwargs): """ :param repo(str): The repository to push to :param tag(str): An optional tag to push :param insecure_registry(bool): Use http:// to connect to the registry """ cli = self.swarm.client if cli is not None: kwargs['stream'] = True kwargs['decode'] = True try: self._display_JSONMessages(cli.push(*args, **kwargs)) except (errors.NotFound, errors.APIError, errors.DockerException) as e: pyprint(e.explanation) finally: cli.close()
def __call__(self, image_list): """ :param image_list(list): List of image id or name """ cli = self.swarm.client if cli is not None: images_err = set() for image in image_list: try: cli.remove_image(image) except (errors.NotFound, errors.APIError, errors.DockerException) as e: pyprint(e.explanation) images_err.add(image) cli.close() # exclude images in image_error images_removed = tuple( (image for image in image_list if not image in images_err)) if images_removed: print('Succeed to remove image {images}'.format( images=', '.join(images_removed)))
def __call__(self, container, **kwargs): """ :param container(str): The container to get logs from :param timestamps(bool): Show timestamps :param tail(str or int): Output specified number of lines at the end of logs: "all" or number :param since(int): Show logs since a given datetime or integer epoch (in seconds) :param follow(bool): Follow log output """ cli = self.swarm.client if cli is not None: kwargs['stdout'] = kwargs['stderr'] = True kwargs['stream'] = True try: for line in cli.logs(container, **kwargs): if six.PY3: line = line.decode('utf8') print(line, end='') except (errors.NotFound, errors.APIError, errors.DockerException) as e: pyprint(e.explanation) finally: cli.close()
def _handle_containers(self, command, container, **kwargs): """ :param command(str): must be one of ['start', 'stop', 'restart', 'remove', 'kill'] :param container_list(list): list containes container ids or names :param kwargs: optional keyword arguments """ cli = self.swarm.client if cli is not None: handlers = { 'start': cli.start, 'stop': cli.stop, 'restart': cli.restart, 'remove': cli.remove_container, 'kill': cli.kill } try: handlers[command](container, **kwargs) except (errors.NotFound, errors.APIError, errors.DockerException) as e: pyprint(e.explanation) finally: cli.close()
def __call__(self, term, **kwargs): cli = self.swarm.client if cli is not None: try: response = cli.search(term) for image in response: if kwargs.get('automated', False): if not image['is_automated']: continue if kwargs.get('stars', 0) > 0: if image['star_count'] < kwargs['stars']: continue if not kwargs.get('no_trunc', False): if image['description'] >= 45: image['description'] = image[ 'description'][:42] + '...' self.images_filter.append(image) self._pretty_print() except (errors.NotFound, errors.APIError, errors.DockerException) as e: pyprint(e.explanation) finally: cli.close()
def __call__(self, *args, **kwargs): """ :param repo(str): The repository to pull :param tag(str): The tag to pull :param insecure_registry(bool): Use an insecure registry :param auth_config(dict): Override the credentials that Client.login has set for this request \ auth_config should contain the username and password keys to be valid """ cli = self.swarm.client if cli is not None: try: kwargs['stream'] = True kwargs['decode'] = True for line in cli.pull(*args, **kwargs): if line.get('id') is not None: print('[{id}] {status}'.format(id=line['id'], status=line['status'])) elif line.get('error') is not None: print(line['error']) except (errors.NotFound, errors.APIError, errors.DockerException) as e: pyprint(e.explanation) finally: cli.close()
def __call__(self, container, command, detach, stdin, tty, user): """ :param container(str): Target container where exec instance will be created :param command(str or list): Command to be executed :param detach(bool): If true, detach from the exec command :param stdin(bool): Keep stdin open even if not attached :param tty(bool): Allocate a pseudo-TTY :param user(str): User to execute command as """ cli = self.swarm.client if cli is not None: try: if stdin and tty: ret = cli.exec_create(container, command, stdin=True, stdout=True, stderr=True, tty=True, user=user) dockerpty.start_exec(cli, ret['Id']) else: ret = cli.exec_create(container, command, user=user) for line in cli.exec_start(ret['Id'], detach=detach, stream=True): print(line.strip()) except (errors.NotFound, errors.APIError, errors.DockerException) as e: pyprint(e.explanation) finally: cli.close()
def __call__(self, *args, **kwargs): """ :param image(str): The image to tag :param repo(str): The repository to set for the tag :param tag(str): The tag name :param force(bool): Force """ cli = self.swarm.client if cli is not None: ret = None try: ret = cli.tag(*args, **kwargs) except (errors.NotFound, errors.APIError, errors.DockerException) as e: pyprint(e.explanation) finally: cli.close() if ret is not None: status = 'Succeed' if ret else 'Fail' image, repo = args tag = kwargs['tag'] if kwargs.get( 'tag') is not None else 'latest' print('{status} to tag {image} into {repo}:{tag}'.format( status=status, image=image, repo=repo, tag=tag))