我们从Python开源项目中,提取了以下13个代码示例,用于说明如何使用docker.errors()。
def build_apb(project, dockerfile=None, tag=None): if dockerfile is None: dockerfile = "Dockerfile" spec = get_spec(project) if 'version' not in spec: print("APB spec does not have a listed version. Please update apb.yml") exit(1) if not tag: tag = spec['name'] update_dockerfile(project, dockerfile) print("Building APB using tag: [%s]" % tag) try: client = docker.DockerClient(base_url='unix://var/run/docker.sock', version='auto') client.images.build(path=project, tag=tag, dockerfile=dockerfile) except docker.errors.DockerException: print("Error accessing the docker API. Is the daemon running?") raise print("Successfully built APB image: %s" % tag) return tag
def docker_logs(self, container_id, show_stdout, show_stderr, follow): try: return (self.cli.logs(container=container_id, stdout=show_stdout, stderr=show_stderr, follow=follow))\ .decode('utf-8') except docker.errors.APIError as ex: if "configured logging reader does not support reading" in str(ex): message = "Docker logging driver is not set to be 'json-file' or 'journald'" DagdaLogger.get_logger().error(message) raise DagdaError(message) else: message = "Unexpected exception of type {0} occured: {1!r}" \ .format(type(ex).__name__, str(ex)) DagdaLogger.get_logger().error(message) raise ex # Creates container and return the container id
def docker_is_running(client): """Return true if Docker server is responsive. Parameters ---------- client : docker.client.DockerClient The Docker client. E.g., `client = docker.from_env()`. Returns ------- running : bool True if Docker server is responsive. """ try: client.ping() return True except (requests.exceptions.ConnectionError, docker.errors.APIError): return False
def _get_image(build_logger_obj): """Helper to check for build errors and return image. This method is in the DockerImage class so that errors are raised in the main thread. This method borrows from the higher-level API of docker-py. See https://github.com/docker/docker-py/pull/1581. """ import re from docker.errors import BuildError if isinstance(build_logger_obj.generator, str): return client.images.get(build_logger_obj.generator) if not build_logger_obj.logs: return BuildError('Unknown') for event in build_logger_obj.logs: if 'stream' in event: match = re.search(r'(Successfully built |sha256:)([0-9a-f]+)', event.get('stream', '')) if match: image_id = match.group(2) return client.images.get(image_id) last_event = build_logger_obj.logs[-1] raise BuildError(last_event.get('error') or last_event)
def start_host(self, image_name, hostname): if hostname in self.hosts: raise Exception("host with name '%s' already exists") try: self.hosts[hostname] = DockerHost(self.cli, image_name, hostname) except docker.errors.DockerException: self.clean() raise
def clean(self): self.cli.stop(container=self.container_id) self.cli.remove_container(container=self.container_id) # by default delete generated docker images if int(os.environ.get('JUMPSSH_DOCKER_IMAGES_CLEANUP', '1')) != 0: try: self.cli.remove_image(image='jumpssh/%s' % self.image_name) except docker.errors.APIError as ex: # image can be used by several containers, in that case, it should be removed after removal # of the last container using that image if ex.response.status_code != 409: raise
def get_tar_content(self, container, path): # http://docker-py.readthedocs.io/en/1.5.0/api/#get_archive try: # content, stats = self.client.api.get_archive( content, _ = self.client.api.get_archive( container=container.attrs, path=path, ) except docker.errors.NotFound: log.exit("Path %s not found in container %s" % (path, container)) return content
def main(): try: arguments = cli.parser.parse_args() except cli.parser.ParseError as e: print_exception(e) return 1 setup_logger(arguments.verbosity) try: docker_client = docker.from_env() except docker.errors.DockerException as e: print_exception(e) return 1 pydev_container = container.PyDevContainer(docker_client) dispatcher = CommandDispatcher(pydev_container) try: dispatcher.dispatch(arguments.command, arguments.container_options) except DispatcherError as e: print_exception(e) return 1 except container.ContainerError as e: print_exception(e) return 1
def docker_exec(self, container_id, cmd, show_stdout, show_stderr): dict = self.cli.exec_create(container=container_id, cmd=cmd, stdout=show_stdout, stderr=show_stderr) return (self.cli.exec_start(exec_id=dict.get('Id'))).decode("utf-8", errors="ignore") # Gets logs from docker container
def cleanup(self, remove=True, force=False): """Stop the container, and optionally remove. Parameters ---------- remove : bool If true, remove container after stopping. force : bool If true, force remove container. """ if remove and force: self.container.remove(force=force) return # If user only wants to stop, attempt to stop the container twice. try: self.container.stop() except (docker.errors.APIError, requests.exceptions.ReadTimeout): self.container.stop() filters = {'status': 'running'} if self.container in client.containers.list(filters=filters): raise docker.errors.APIError("Container not stopped properly.") # If user wants to stop and remove, but not forcefully. if remove: self.container.remove()
def container_create(container_params): #~ container_params = json.loads(container_params) print "\ncreate container %s" % container_params try: print docker_client.create_container(**container_params) except docker.errors.APIError as e: print e sys.exit(1) #~ self.tmp_list() #~ self.state_change('start') print 'finished' return 'finished'
def docker_run(command, image='ubuntu:trusty', network_mode='host', privileged=True, client=None, stream=False): """ # copied from blockade with minor enhancements Runs the command on the docker container with provided image and returns logs Args: command: non blocking command to be run image: Docker image to create container with network_mode: network mode for container privileged: True/False client: docker client stream: True/False stream docker logs from container Returns: """ docker_client = DockerClient() if not client else client host_config = docker_client.create_host_config( network_mode=network_mode, privileged=privileged) try: container = docker_client.create_container(image=image, command=command, host_config=host_config) except docker.errors.NotFound: docker_client.pull(image) container = docker_client.create_container(image=image, command=command, host_config=host_config) docker_client.start_container(container) stdout = docker_client.get_logs(container, stdout=True, stream=stream) if stream: output = b'' for item in stdout: output += item output = output.decode('utf-8') if stream else stdout.decode('utf-8') status_code = docker_client.wait_till_stopped(container) docker_client.remove_container(container, force=True) if status_code == 2 and 'No such file or directory' in output: # docker_client.remove_container(container, force=True) return elif status_code != 0: err_msg = "Problem running command '%s' - %s" % (command, output) log.debug(err_msg) raise DockerClientException(err_msg) # if isinstance(docker_client, docker.Client): # docker_client.remove_container(container=container.get('Id'), # force=True) # else: # docker_client.remove_container(cid=container, force=True) log.debug("Succesfully ran command - %s" % command) return output
def cmdrun_push(**kwargs): project = kwargs['base_path'] spec = get_spec(project, 'string') dict_spec = get_spec(project, 'dict') blob = base64.b64encode(spec) broker = kwargs["broker"] if broker is None: broker = get_asb_route() data_spec = {'apbSpec': blob} print(spec) if kwargs['openshift']: namespace = kwargs['reg_namespace'] service = kwargs['reg_svc_name'] # Assume we are using internal registry, no need to push to broker registry = get_registry_service_ip(namespace, service) if registry is None: print("Failed to find registry service IP address.") raise Exception("Unable to get registry IP from namespace %s" % namespace) tag = registry + "/" + kwargs['namespace'] + "/" + dict_spec['name'] print("Building image with the tag: " + tag) try: client = docker.DockerClient(base_url='unix://var/run/docker.sock', version='auto') client.images.build(path=project, tag=tag, dockerfile=kwargs['dockerfile']) openshift_config.load_kube_config() token = openshift_client.configuration.api_key['authorization'].split(" ")[1] client.login(username="unused", password=token, registry=registry, reauth=True) client.images.push(tag) print("Successfully pushed image: " + tag) bootstrap(broker, kwargs.get("basic_auth_username"), kwargs.get("basic_auth_password"), kwargs["verify"]) except docker.errors.DockerException: print("Error accessing the docker API. Is the daemon running?") raise except docker.errors.APIError: print("Failed to login to the docker API.") raise else: response = broker_request(kwargs["broker"], "/apb/spec", "post", data=data_spec, verify=kwargs["verify"], basic_auth_username=kwargs.get("basic_auth_username"), basic_auth_password=kwargs.get("basic_auth_password")) if response.status_code != 200: print("Error: Attempt to add APB to the Broker returned status: %d" % response.status_code) print("Unable to add APB to Ansible Service Broker.") exit(1) print("Successfully added APB to Ansible Service Broker") if not kwargs['no_relist']: relist_service_broker(kwargs)