当前位置: 首页>>代码示例>>Python>>正文


Python DockerUtil.extract_container_tags方法代码示例

本文整理汇总了Python中utils.dockerutil.DockerUtil.extract_container_tags方法的典型用法代码示例。如果您正苦于以下问题:Python DockerUtil.extract_container_tags方法的具体用法?Python DockerUtil.extract_container_tags怎么用?Python DockerUtil.extract_container_tags使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在utils.dockerutil.DockerUtil的用法示例。


在下文中一共展示了DockerUtil.extract_container_tags方法的2个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: SDDockerBackend

# 需要导入模块: from utils.dockerutil import DockerUtil [as 别名]
# 或者: from utils.dockerutil.DockerUtil import extract_container_tags [as 别名]

#.........这里部分代码省略.........
            if Platform.is_k8s():
                spec = state.get_kube_container_spec(c_id)
                if spec:
                    ports = [str(x.get('containerPort')) for x in spec.get('ports', [])]
            else:
                ports = [p.split('/')[0] for p in container_inspect['Config'].get('ExposedPorts', {}).keys()]

        ports = sorted(ports, key=int)
        return self._extract_port_from_list(ports, tpl_var)

    def _extract_port_from_list(self, ports, tpl_var):
        if not ports:
            return None

        tpl_parts = tpl_var.split('_', 1)

        if len(tpl_parts) == 1:
            log.debug("No index was passed for template variable %s. "
                      "Trying with the last element." % tpl_var)
            return ports[-1]

        try:
            idx = tpl_parts[-1]
            return ports[int(idx)]
        except ValueError:
            log.error("Port index is not an integer. Using the last element instead.")
        except IndexError:
            log.error("Port index is out of range. Using the last element instead.")
        return ports[-1]

    def get_tags(self, state, c_id):
        """Extract useful tags from docker or platform APIs. These are collected by default."""
        c_inspect = state.inspect_container(c_id)
        tags = self.dockerutil.extract_container_tags(c_inspect, self.docker_labels_as_tags)

        if Platform.is_k8s():
            if not self.kubeutil.init_success:
                log.warning("kubelet client not initialized, kubernetes tags will be missing.")
                return tags

            pod_metadata = state.get_kube_config(c_id, 'metadata')

            if pod_metadata is None:
                log.warning("Failed to fetch pod metadata for container %s."
                            " Kubernetes tags will be missing." % c_id[:12])
                return tags

            # get pod labels
            kube_labels = pod_metadata.get('labels', {})
            for label, value in kube_labels.iteritems():
                tags.append('%s:%s' % (label, value))

            # get kubernetes namespace
            namespace = pod_metadata.get('namespace')
            tags.append('kube_namespace:%s' % namespace)

            # get kubernetes container name
            kube_container_name = state.get_kube_container_name(c_id)
            if kube_container_name:
                tags.append('kube_container_name:%s' % kube_container_name)

            if not self.kubeutil:
                log.warning("The agent can't connect to kubelet, creator and "
                            "service tags will be missing for container %s." % c_id[:12])
            else:
                # add creator tags
开发者ID:serverdensity,项目名称:sd-agent,代码行数:70,代码来源:sd_docker_backend.py

示例2: test_extract_container_tags

# 需要导入模块: from utils.dockerutil import DockerUtil [as 别名]
# 或者: from utils.dockerutil.DockerUtil import extract_container_tags [as 别名]
    def test_extract_container_tags(self):
        #mocks
        du = DockerUtil()
        with mock.patch.dict(du._image_sha_to_name_mapping,
          {'gcr.io/google_containers/[email protected]:7653dfb091e9524ecb1c2c472ec27e9d2e0ff9addc199d91b5c532a2cdba5b9e': 'gcr.io/google_containers/hyperkube:latest',
          'myregistry.local:5000/testing/[email protected]:5bef08742407efd622d243692b79ba0055383bbce12900324f75e56f589aedb0': 'myregistry.local:5000/testing/test-image:version'}):
            no_label_test_data = [
                # Nominal case
                [{'Image': 'redis:3.2'}, ['docker_image:redis:3.2', 'image_name:redis', 'image_tag:3.2']],
                # No tag
                [{'Image': 'redis'}, ['docker_image:redis', 'image_name:redis']],
                # No image
                [{}, []],
                # Image containing 'sha256', swarm fashion
                [{'Image': 'datadog/docker-dd-agent:[email protected]:769418c18c3e9e0b6ab2c18147c3599d6e27f40fb3dee56418bf897147ff84d0'},
                    ['docker_image:datadog/docker-dd-agent:latest', 'image_name:datadog/docker-dd-agent', 'image_tag:latest']],
                # Image containing 'sha256', kubernetes fashion
                [{'Image': 'gcr.io/google_containers/[email protected]:7653dfb091e9524ecb1c2c472ec27e9d2e0ff9addc199d91b5c532a2cdba5b9e'},
                    ['docker_image:gcr.io/google_containers/hyperkube:latest', 'image_name:gcr.io/google_containers/hyperkube', 'image_tag:latest']],
                # Images with several ':'
                [{'Image': 'myregistry.local:5000/testing/test-image:version'},
                    ['docker_image:myregistry.local:5000/testing/test-image:version', 'image_name:myregistry.local:5000/testing/test-image', 'image_tag:version']],
                [{'Image': 'myregistry.local:5000/testing/[email protected]:5bef08742407efd622d243692b79ba0055383bbce12900324f75e56f589aedb0'},
                    ['docker_image:myregistry.local:5000/testing/test-image:version', 'image_name:myregistry.local:5000/testing/test-image', 'image_tag:version']],
                # Here, since the tag is present, we should not try to resolve it in the sha256, and so returning 'latest'
                [{'Image': 'myregistry.local:5000/testing/test-image:[email protected]:5bef08742407efd622d243692b79ba0055383bbce12900324f75e56f589aedb0'},
                    ['docker_image:myregistry.local:5000/testing/test-image:latest', 'image_name:myregistry.local:5000/testing/test-image', 'image_tag:latest']]
            ]
            labeled_test_data = [
                # No labels
                (
                    # ctr inspect
                    {
                        'Image': 'redis:3.2',
                        'Config': {
                            'Labels': {}
                        }
                    },
                    # labels as tags
                    [],
                    # expected result
                    ['docker_image:redis:3.2', 'image_name:redis', 'image_tag:3.2']
                ),
                # Un-monitored labels
                (
                    {
                        'Image': 'redis:3.2',
                        'Config': {
                            'Labels': {
                                'foo': 'bar'
                            }
                        }
                    },
                    [],
                    ['docker_image:redis:3.2', 'image_name:redis', 'image_tag:3.2']
                ),
                # no labels, with labels_as_tags list
                (
                    {
                        'Image': 'redis:3.2',
                        'Config': {
                            'Labels': {}
                        }
                    },
                    ['foo'],
                    ['docker_image:redis:3.2', 'image_name:redis', 'image_tag:3.2']
                ),
                # labels and labels_as_tags list
                (
                    {
                        'Image': 'redis:3.2',
                        'Config': {
                            'Labels': {'foo': 'bar', 'f00': 'b4r'}
                        }
                    },
                    ['foo'],
                    ['docker_image:redis:3.2', 'image_name:redis', 'image_tag:3.2', 'foo:bar']
                ),

            ]
            for test in no_label_test_data:
                self.assertEqual(test[1], du.extract_container_tags(test[0], []))

            for test in labeled_test_data:
                self.assertEqual(test[2], du.extract_container_tags(test[0], test[1]))
开发者ID:tschellhorn,项目名称:dd-agent,代码行数:87,代码来源:test_dockerutil.py


注:本文中的utils.dockerutil.DockerUtil.extract_container_tags方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。