Python docker.Client() Examples
The following are 30
code examples of docker.Client().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
docker
, or try the search function
.
Example #1
Source File: image.py From hummer with Apache License 2.0 | 6 votes |
def _tag_image_with_new_name(self, base_url, old_image_name, old_image_version, image_name, image_version): """ Docker tag old_image_name:old_image_version image_name:image_version. """ client = Client(base_url=base_url) old_image = "{}:{}".format(old_image_name, old_image_version) try: response = client.tag(image=old_image, repository=image_name, tag=image_version) except Exception as e: logger.debug(e) response = False if not response: logger.info("Tag image {} to {}:{} failed.".format(old_image, image_name, image_version)) return None image_token = self._get_image_token_on_docker_host(base_url, image_name, image_version) self._delete_image_on_docker_host(base_url, old_image_name, old_image_version) return image_token
Example #2
Source File: test_functional_cos_emitter.py From agentless-system-crawler with Apache License 2.0 | 6 votes |
def setUp(self): self.docker = docker.Client( base_url='unix://var/run/docker.sock', version='auto') os.mkdir('/etc/cos-secrets', 0755 ) f=open("/etc/cos-secrets/access_key", "w+") f.write("test") f.close() f=open("/etc/cos-secrets/secret_key", "w+") f.write("testforall") f.close() f=open("/etc/cos-secrets/location", "w+") f.write("test") f.close() self.start_minio_container() self.start_crawled_container()
Example #3
Source File: test_functional_plugins.py From agentless-system-crawler with Apache License 2.0 | 6 votes |
def setUp(self): self.docker = docker.Client( base_url='unix://var/run/docker.sock', version='auto') try: if len(self.docker.containers()) != 0: raise Exception( "Sorry, this test requires a machine with no docker" "containers running.") except requests.exceptions.ConnectionError: print ("Error connecting to docker daemon, are you in the docker" "group? You need to be in the docker group.") self.docker.pull(repository='alpine', tag='latest') self.container = self.docker.create_container( image=self.image_name, command='/bin/sleep 60') self.tempd = tempfile.mkdtemp(prefix='crawlertest.') self.docker.start(container=self.container['Id'])
Example #4
Source File: cmp.py From aioes with Apache License 2.0 | 6 votes |
def find_endpoint(): if os.environ.get("NO_DOCKER"): yield ('localhost', 9200) else: es_tag = os.environ.get("ES_VERSION", '2.4') cl = docker.Client(version='auto') cl.pull('elasticsearch:{}'.format(es_tag)) container = cl.create_container( image='elasticsearch:{}'.format(es_tag), name='aioes-test-server', ports=[9200], detach=True) cid = container['Id'] cl.start(container=cid) ins = cl.inspect_container(cid) try: yield (ins['NetworkSettings']['IPAddress'], 9200) finally: cl.kill(container=cid) cl.remove_container(cid)
Example #5
Source File: test_functional_dockerutils.py From agentless-system-crawler with Apache License 2.0 | 6 votes |
def setUp(self): self.docker = docker.Client( base_url='unix://var/run/docker.sock', version='auto') try: if len(self.docker.containers()) != 0: raise Exception( "Sorry, this test requires a machine with no docker" "containers running.") except requests.exceptions.ConnectionError: print ("Error connecting to docker daemon, are you in the docker" "group? You need to be in the docker group.") self.docker.pull(repository='alpine', tag='latest') self.container = self.docker.create_container( image=self.image_name, command='/bin/sleep 60') self.tempd = tempfile.mkdtemp(prefix='crawlertest.') self.docker.start(container=self.container['Id'])
Example #6
Source File: docker_backend.py From sen with MIT License | 6 votes |
def __init__(self): self._containers = None self._images = None # displayed images self._all_images = None # docker images -a self._df = None kwargs = {"version": "auto"} kwargs.update(docker.utils.kwargs_from_env(assert_hostname=False)) try: APIClientClass = docker.Client # 1.x except AttributeError: APIClientClass = docker.APIClient # 2.x try: self.client = APIClientClass(**kwargs) except docker.errors.DockerException as ex: raise TerminateApplication("can't establish connection to docker daemon: {0}".format(str(ex))) self.scratch_image = RootImage(self) # backend queries
Example #7
Source File: test_functional_nodepackage_plugin.py From agentless-system-crawler with Apache License 2.0 | 6 votes |
def setUp(self): self.docker = docker.Client( base_url='unix://var/run/docker.sock', version='auto') try: if len(self.docker.containers()) != 0: raise Exception( "Sorry, this test requires a machine with no docker" "containers running.") except requests.exceptions.ConnectionError: print ("Error connecting to docker daemon, are you in the docker" "group? You need to be in the docker group.") self.docker.pull(repository='node', tag='11.0') self.container = self.docker.create_container( image=self.image_name, command='sleep 60') self.docker.start(container=self.container['Id'])
Example #8
Source File: dockerutils.py From agentless-system-crawler with Apache License 2.0 | 6 votes |
def exec_dockerps(): """ Returns a list of docker inspect jsons, one for each container. This call executes the `docker inspect` command every time it is invoked. """ try: client = docker.Client( base_url='unix://var/run/docker.sock', version='auto') containers = client.containers() inspect_arr = [] for container in containers: inspect = exec_dockerinspect(container['Id']) inspect_arr.append(inspect) except docker.errors.DockerException as e: logger.warning(str(e)) raise DockerutilsException('Failed to exec dockerps') return inspect_arr
Example #9
Source File: test_functional_apk_package_crawler.py From agentless-system-crawler with Apache License 2.0 | 6 votes |
def setUp(self): root = logging.getLogger() root.setLevel(logging.INFO) ch = logging.StreamHandler(sys.stdout) ch.setLevel(logging.INFO) formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') ch.setFormatter(formatter) root.addHandler(ch) self.docker = docker.Client(base_url='unix://var/run/docker.sock', version='auto') try: if len(self.docker.containers()) != 0: raise Exception( "Sorry, this test requires a machine with no docker" "containers running.") except requests.exceptions.ConnectionError: print ("Error connecting to docker daemon, are you in the docker" "group? You need to be in the docker group.") self.start_crawled_container()
Example #10
Source File: calico_kubernetes.py From k8s-exec-plugin with Apache License 2.0 | 6 votes |
def __init__(self, config): self.pod_name = None self.namespace = None self.docker_id = None self.policy_parser = None # Get configuration from the given dictionary. logger.debug("Plugin running with config: %s", config) self.auth_token = config[KUBE_AUTH_TOKEN_VAR] self.api_root = config[KUBE_API_ROOT_VAR] self.client_certificate = config[KUBE_CLIENT_CERTIFICATE_VAR] self.client_certificate_key = config[KUBE_CLIENT_CERTIFICATE_KEY_VAR] self.ca_certificate = config[KUBE_CA_CERTIFICATE_VAR] self.calico_ipam = config[CALICO_IPAM_VAR].lower() self.default_policy = config[DEFAULT_POLICY_VAR].lower() self._datastore_client = IPAMClient() self._docker_client = Client( version=DOCKER_VERSION, base_url=os.getenv("DOCKER_HOST", "unix://var/run/docker.sock"))
Example #11
Source File: image.py From hummer with Apache License 2.0 | 6 votes |
def _push_image_to_registry(self, base_url, image_name, image_version, image_token): """ Push image from docker host to private registry. Returns the sha256 digest of the image. """ image_complete_name = '%s:%s' %(image_name, image_version) client = Client(base_url=base_url) try: response = [res for res in client.push(image_complete_name, stream=True)] except Exception: logger.error('Push image %s to registry failed.' % image_complete_name) return None try: digest = fetch_digest_from_response(response[-1]) except Exception: logger.error('Parse the digest response error.') return None return digest
Example #12
Source File: image.py From hummer with Apache License 2.0 | 6 votes |
def _delete_image_on_docker_host(self, base_url, image_name, image_version): """ Delete image from docker host if exists image called image_name:image_version. """ image_complete_name = '%s:%s' %(image_name, image_version) client = Client(base_url=base_url) try: client.remove_image(image=image_complete_name, force=True) except Exception: logger.info('There is no image called %s on docker host %s' % (image_complete_name, base_url)) return None logger.info('Image %s on docker host %s has been deleted.' % (image_complete_name, base_url))
Example #13
Source File: image.py From hummer with Apache License 2.0 | 6 votes |
def _delete_image_on_docker_host(self, base_url, image_name, image_version): """ Delete image from docker host if exists image called image_name:image_version. """ image_complete_name = '%s:%s' %(image_name, image_version) client = Client(base_url=base_url) try: client.remove_image(image=image_complete_name, force=True) except Exception: logger.info('There is no image called %s on docker host %s' % (image_complete_name, base_url)) return None logger.info('Image %s on docker host %s has been deleted.' % (image_complete_name, base_url))
Example #14
Source File: dockerplugin.py From docker-collectd-plugin with GNU General Public License v2.0 | 6 votes |
def init_callback(self): self.client = docker.Client( base_url=self.docker_url, version=DockerPlugin.MIN_DOCKER_API_VERSION) self.client.timeout = self.timeout # Check API version for stats endpoint support. try: version = self.client.version()['ApiVersion'] if StrictVersion(version) < \ StrictVersion(DockerPlugin.MIN_DOCKER_API_VERSION): raise Exception except: collectd.warning(('Docker daemon at {url} does not ' 'support container statistics!') .format(url=self.docker_url)) return False collectd.register_read(self.read_callback) collectd.info(('Collecting stats about Docker containers from {url} ' '(API version {version}; timeout: {timeout}s).') .format(url=self.docker_url, version=version, timeout=self.timeout)) return True
Example #15
Source File: pty.py From deepWordBug with Apache License 2.0 | 6 votes |
def __init__(self, client, container, interactive=True, stdout=None, stderr=None, stdin=None, logs=None): """ Initialize the PTY using the docker.Client instance and container dict. """ if logs is None: warnings.warn("The default behaviour of dockerpty is changing. Please add logs=1 to your dockerpty.start call to maintain existing behaviour. See https://github.com/d11wtq/dockerpty/issues/51 for details.", DeprecationWarning) logs = 1 self.client = client self.container = container self.raw = None self.interactive = interactive self.stdout = stdout or sys.stdout self.stderr = stderr or sys.stderr self.stdin = stdin or sys.stdin self.logs = logs
Example #16
Source File: test_tasker.py From atomic-reactor with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_timeout(timeout, expected_timeout): if not hasattr(docker, 'APIClient'): setattr(docker, 'APIClient', docker.Client) expected_kwargs = { 'timeout': expected_timeout } if hasattr(docker, 'AutoVersionClient'): expected_kwargs['version'] = 'auto' (flexmock(docker.APIClient) .should_receive('__init__') .with_args(**expected_kwargs) .once()) kwargs = {} if timeout is not None: kwargs['timeout'] = timeout DockerTasker(**kwargs)
Example #17
Source File: image.py From hummer with Apache License 2.0 | 6 votes |
def _delete_image_on_docker_host(self, base_url, image_name, image_version): """ Delete image from docker host if exists image called image_name:image_version. """ image_complete_name = '%s:%s' %(image_name, image_version) client = Client(base_url=base_url) try: client.remove_image(image=image_complete_name, force=True) except Exception: logger.info('There is no image called %s on docker host %s' % (image_complete_name, base_url)) return None logger.info('Image %s on docker host %s has been deleted.' % (image_complete_name, base_url))
Example #18
Source File: test_tasker.py From atomic-reactor with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_docker2(): class MockClient(object): def __init__(self, **kwargs): pass def version(self): return {} for client in ['APIClient', 'Client']: if not hasattr(docker, client): setattr(docker, client, MockClient) (flexmock(docker) .should_receive('APIClient') .once() .and_raise(AttributeError)) (flexmock(docker) .should_receive('Client') .once()) DockerTasker()
Example #19
Source File: calico_kubernetes.py From k8s-exec-plugin with Apache License 2.0 | 5 votes |
def create(self, namespace, pod_name, docker_id): """"Create a pod.""" self.pod_name = pod_name self.docker_id = docker_id self.namespace = namespace self.policy_parser = PolicyParser(self.namespace) logger.info('Configuring pod %s/%s (container_id %s)', self.namespace, self.pod_name, self.docker_id) # Obtain information from Docker Client and validate container state. # If validation fails, the plugin will exit. self._validate_container_state(self.docker_id) try: endpoint = self._configure_interface() logger.info("Created Calico endpoint: %s", endpoint.endpoint_id) self._configure_profile(endpoint) except BaseException: # Check to see if an endpoint has been created. If so, # we need to tear down any state we may have created. logger.exception("Error networking pod - cleaning up") try: self.delete(namespace, pod_name, docker_id) except BaseException: # Catch all errors tearing down the pod - this # is best-effort. logger.exception("Error cleaning up pod") # We've torn down, exit. logger.info("Done cleaning up") sys.exit(1) else: logger.info("Successfully configured networking for pod %s/%s", self.namespace, self.pod_name)
Example #20
Source File: dockerclient.py From cargo with Apache License 2.0 | 5 votes |
def __init__(self, dockerURL): self.dclient = Client(base_url=dockerURL)
Example #21
Source File: test_cmds_local_run.py From paasta with Apache License 2.0 | 5 votes |
def test_run_healthcheck_cmd_success(mock_sleep, mock_perform_cmd_healthcheck): mock_docker_client = mock.MagicMock(spec_set=docker.Client) fake_container_id = "fake_container_id" fake_mode = "cmd" fake_cmd = "/bin/true" fake_timeout = 10 mock_perform_cmd_healthcheck.return_value = True assert run_healthcheck_on_container( mock_docker_client, fake_container_id, fake_mode, fake_cmd, fake_timeout ) assert mock_perform_cmd_healthcheck.call_count == 1 mock_perform_cmd_healthcheck.assert_called_once_with( mock_docker_client, fake_container_id, fake_cmd, fake_timeout )
Example #22
Source File: test_cmds_local_run.py From paasta with Apache License 2.0 | 5 votes |
def test_get_container_id(): mock_docker_client = mock.MagicMock(spec_set=docker.Client) fake_containers = [ {"Names": ["/paasta_local_run_1"], "Id": "11111"}, {"Names": ["/paasta_local_run_2"], "Id": "22222"}, ] mock_docker_client.containers = mock.MagicMock( spec_set=docker.Client, return_value=fake_containers ) container_name = "paasta_local_run_2" expected = "22222" actual = get_container_id(mock_docker_client, container_name) assert actual == expected
Example #23
Source File: test_cmds_local_run.py From paasta with Apache License 2.0 | 5 votes |
def test_run_healthcheck_cmd_fails(mock_sleep, mock_perform_cmd_healthcheck): mock_docker_client = mock.MagicMock(spec_set=docker.Client) fake_container_id = "fake_container_id" fake_mode = "cmd" fake_cmd = "/bin/true" fake_timeout = 10 mock_perform_cmd_healthcheck.return_value = False assert not run_healthcheck_on_container( mock_docker_client, fake_container_id, fake_mode, fake_cmd, fake_timeout ) assert mock_perform_cmd_healthcheck.call_count == 1 mock_perform_cmd_healthcheck.assert_called_once_with( mock_docker_client, fake_container_id, fake_cmd, fake_timeout )
Example #24
Source File: conftest.py From aioes with Apache License 2.0 | 5 votes |
def docker(request): if request.config.getoption('--no-docker'): return None return DockerClient(version='auto')
Example #25
Source File: real.py From sen with MIT License | 5 votes |
def mock(): try: client_class = docker.Client # 1.x except AttributeError: client_class = docker.APIClient # 2.x flexmock(client_class, images=images_response) flexmock(client_class, containers=containers_response) flexmock(client_class, version=lambda *args, **kwargs: version_data) flexmock(client_class, top=lambda *args, **kwargs: top_data) flexmock(client_class, stats=stats_response_1_13) flexmock(client_class, inspect_image=lambda *args, **kwargs: inspect_image_data)
Example #26
Source File: docker_inspect.py From lain with MIT License | 5 votes |
def main(): module = AnsibleModule( argument_spec=dict( name=dict(required=True), type=dict(default='container', choices=['container', 'image']), ), ) name = module.params['name'] type = module.params['type'] client = docker.Client() if type == 'container': inspect_method = client.inspect_container elif type == 'image': inspect_method = client.inspect_image else: # should not reach here raise Exception("unknown type") try: result = inspect_method(name) except APIError as e: if e.response.status_code == 404: module.fail_json(msg="%s does not exists" % name) raise result['changed'] = False module.exit_json(**result)
Example #27
Source File: utdocker.py From pykit with MIT License | 5 votes |
def get_client(): dcli = docker.Client(base_url='unix://var/run/docker.sock') return dcli
Example #28
Source File: client.py From flocker with Apache License 2.0 | 5 votes |
def __init__(self, image): # Getting Docker to work correctly on any client platform can # be tricky. See # http://doc-dev.clusterhq.com/gettinginvolved/client-testing.html # for details. params = docker.utils.kwargs_from_env(assert_hostname=False) self.docker = docker.Client(version='1.16', **params) self.image = image
Example #29
Source File: pty.py From deepWordBug with Apache License 2.0 | 5 votes |
def __init__(self, client, operation): """ Initialize the PTY using the docker.Client instance and container dict. """ self.client = client self.operation = operation
Example #30
Source File: image.py From hummer with Apache License 2.0 | 5 votes |
def _load_image_on_docker_host(self, base_url, build_file, image_name, image_version='latest'): """ Import container snapshot on the selected docker host. 'base_url': the url of docker host. 'build_file': the name of the build file in absolute path. 'image_name': the name of the image, containing registry address, user name and image name. 'image_version': the version of the image. Returns: 'token': the image token """ self._delete_image_on_docker_host(base_url, self.old_image_name, self.old_image_version) self._delete_image_on_docker_host(base_url, image_name, image_version) client = Client(base_url=base_url) try: with open(build_file, 'rb') as fileobj: client.load_image(fileobj) except Exception: logger.error('load image file on docker host %s failed.' % base_url) return None return self._tag_image_with_new_name(base_url, self.old_image_name, self.old_image_version, image_name, image_version)