コード例 #1
0
def test_extract_env_var():
    container = {
        "random": {"random": "random"},
        "environment": [
            {"name": "PROMETHEUS_PORT", "value": "80"},
            {"name": "SOMETINGELSE", "value": "fefefwe"},
        ],
    }

    assert "80" == toolbox.extract_env_var(container, "PROMETHEUS_PORT")
    assert None is toolbox.extract_env_var(container, "does not exist")
コード例 #2
0
def _is_marked_as_target(
    container_definition: dict,
    marker_type: str = s.MARKER_TYPE,
    marker: str = s.MARKER,
) -> bool:
    """Determines if the given container is a target.

    Args:
        container_definition (`dict`): Container definition matching the API.

        marker_type (`str`, optional): Where is the marker located? Defaults to
            `s.MARKER_TYPE`, can be set through settings.

        marker (`str`, optional): The key name to look up. Must be `true`
            string to count as marked. Defaults to `s.MARKER`, can be set
            through settings.

    Returns:
        `bool`: Self explanatory.
    """

    if (marker_type == "environment" and toolbox.extract_env_var(
            container_definition, marker) == "true"):
        return True
    elif (marker_type == "dockerLabels" and container_definition.get(
            "dockerLabels", {}).get(marker, None) == "true"):
        return True
    else:
        return False
コード例 #3
0
def test_extract_env_var_no_env():
    container = {
        "random": {
            "random": "random"
        },
    }

    assert None is toolbox.extract_env_var(container, "PROMETHEUS_PORT")
コード例 #4
0
    def _build_target(self, container: dict,
                      data: Type[TaskInfo]) -> Type[Target] or None:
        """Builds target if conditions are met.

        :param container: Container from task. Not the continer definition.
        :param data: Holds all information required.
        :return: Either the `Target` or `None`.
        """

        container_name = container["name"]
        task_definition_arn = data.task["taskDefinitionArn"]
        task_arn = data.task["taskArn"]

        _logger = logger.bind(
            container=container_name,
            task_definition=task_definition_arn,
            task=task_arn,
        )

        for defi in data.task_definition["containerDefinitions"]:
            if container_name == defi["name"]:
                container_definition = defi

        if _is_marked_as_target(container_definition):
            self.targets_marked_counter += 1
            _logger.debug("Prometheus marker true. Build target.")
        else:
            _logger.debug("Prometheus marker not found / not 'true'. Reject.")
            return

        metrics_path = toolbox.extract_env_var(container_definition,
                                               "PROMETHEUS_ENDPOINT")
        prom_port = toolbox.extract_env_var(container_definition,
                                            "PROMETHEUS_PORT")

        network_bindings = container.get("networkBindings", [])
        network_interfaces = container.get("networkInterfaces", [])
        network_mode = data.task_definition.get("networkMode", "bridge")
        port_mappings = container_definition.get("portMappings", [])

        if not _has_proper_network(
                network_bindings,
                network_interfaces,
                network_mode,
                prom_port,
                port_mappings,
                _logger,
        ):
            self.fetcher.task_cache.current.pop(task_arn, None)
            self.fetcher.task_cache.next.pop(task_arn, None)
            self.targets_marked_rejected_counter += 1
            return

        port = _extract_port(
            network_mode,
            prom_port,
            toolbox.extract_env_var(container_definition,
                                    "PROMETHEUS_CONTAINER_PORT"),
            port_mappings,
            network_bindings,
        )
        if port is None:
            _logger.warning(
                "Does not expose port matching PROMETHEUS_CONTAINER_PORT.")
            self.targets_marked_rejected_counter += 1
            return

        ip = _extract_ip(network_mode, network_interfaces, data.ec2_instance)

        custom_labels = _extract_custom_labels(
            env=container_definition.get("environment", []))

        custom_labels.update(
            _extract_custom_labels_from_dockerlabels(
                container_definition.get("dockerLabels", {})))

        task_name = data.task["taskDefinitionArn"].split(":")[5].split("/")[-1]

        if toolbox.extract_env_var(container_definition,
                                   "PROMETHEUS_NOLABELS"):
            _logger.debug(
                "Build target successfully from discovered task info.")

            return Target(
                ip=ip,
                port=port,
                metrics_path=metrics_path,
                p_instance=task_name,
                task_name=task_name,
                custom_labels=custom_labels,
            )

        if "FARGATE" in data.task_definition.get("requiresCompatibilities",
                                                 ""):
            instance_id = container_id = None
        else:
            instance_id = data.container_instance["ec2InstanceId"]
            container_id = container["containerArn"].split(":")[5].split(
                "/")[-1]

        _logger.debug("Build target successfully from discovered task info.")

        return Target(
            ip=ip,
            port=port,
            metrics_path=metrics_path,
            cluster_name=data.task["clusterArn"].split(":")[5].split("/")[-1],
            task_name=data.task["taskDefinitionArn"].split(":")[5].split("/")
            [-1],
            task_version=data.task["taskDefinitionArn"].split(":")[6],
            task_id=data.task["taskArn"].split(":")[5].split("/")[-1],
            p_instance=f"{ip}:{port}",
            instance_id=instance_id,
            container_id=container_id,
            custom_labels=custom_labels,
        )
コード例 #5
0
def test_extract_env_var_no_environment():
    container = {"random": {"random": "random"}}

    assert None is toolbox.extract_env_var(container, "does not exist")