Esempio n. 1
0
    def GetTargetPodsWhenTargetPodsENVNotSet(self, podAffPerc, nonChaosPods,
                                             chaosDetails, clients):

        filteredPods = []
        realPods = []
        for pod in nonChaosPods.items:

            parentName, err = annotation.GetParentName(clients, pod,
                                                       chaosDetails)

            if err != None:
                return client.V1PodList, err

            if chaosDetails.AppDetail.AnnotationCheck:
                isParentAnnotated, err = annotation.IsParentAnnotated(
                    clients, parentName, chaosDetails)

                if err != None:
                    return client.V1PodList, err

                if isParentAnnotated:
                    filteredPods.append(pod)
                    logging.info(
                        "[Info]: chaos candidate of kind: %s, name: %s, namespace: %s",
                        chaosDetails.AppDetail.Kind, parentName,
                        chaosDetails.AppDetail.Namespace)
            else:
                for pod in nonChaosPods.items:
                    filteredPods.append(pod)
                logging.info(
                    "[Info]: chaos candidate of kind: %s, name: %s, namespace: %s",
                    chaosDetails.AppDetail.Kind, parentName,
                    chaosDetails.AppDetail.Namespace)

        if len(filteredPods) == 0:
            return client.V1PodList(
                items=filteredPods), ValueError("No target pod found")

        newPodListLength = max(1,
                               maths.Adjustment(podAffPerc, len(filteredPods)))

        # it will generate the random podlist
        # it starts from the random index and choose requirement no of pods next to that index in a circular way.
        index = random.randint(0, len(filteredPods) - 1)
        for i in range(int(newPodListLength)):
            realPods.append(filteredPods[index])
            index = (index + 1) % len(filteredPods)

        return client.V1PodList(items=realPods), None
Esempio n. 2
0
 def _mock_list_namespaced_pods(list_pods_call_responses: List[List[client.V1Pod]]):
     calls = []
     for list_pods_call_response in list_pods_call_responses:
         pods = client.V1PodList(items=list_pods_call_response)
         calls.append(pods)
     get_k8s().v1api.list_namespaced_pod = unittest.mock.Mock(side_effect=calls)
     return calls
Esempio n. 3
0
    def _mock_create_namespaced_pod(self):
        def _generate_pod(namespace, pod):
            terminated_container_state = client.V1ContainerStateTerminated(
                finished_at=datetime.now(timezone.utc), exit_code=0)
            container_state = client.V1ContainerState(
                terminated=terminated_container_state)
            container_status = client.V1ContainerStatus(
                state=container_state,
                image=self.image_name,
                image_id="must-provide-image-id",
                name=self.name,
                ready=True,
                restart_count=0,
            )
            status = client.V1PodStatus(phase=PodPhases.succeeded,
                                        container_statuses=[container_status])
            response_pod = deepcopy(pod)
            response_pod.status = status
            response_pod.metadata.name = "test-pod"
            response_pod.metadata.namespace = namespace
            return response_pod

        get_k8s().v1api.create_namespaced_pod = unittest.mock.Mock(
            side_effect=_generate_pod)

        # Our purpose is not to test the client watching on logs, mock empty list (used in get_logger_pods)
        get_k8s().v1api.list_namespaced_pod = unittest.mock.Mock(
            return_value=client.V1PodList(items=[]))
def test_all_pods_in_all_ns_are_ok_completed(node_client, client, has_conf):
    node_name = 'node1'
    has_conf.return_value = False
    v1 = MagicMock()

    pod1 = create_pod_object("fakepod1", node_name=node_name)
    pod2 = create_pod_object("fakepod2",
                             state="terminated",
                             node_name=node_name)
    pod2.status.container_statuses[0].state.terminated.reason = 'Completed'

    node = MagicMock()
    node.metadata.name = node_name
    v1.list_node_with_http_info.return_value = k8sClient.V1NodeList(
        items=[node])

    response = k8sClient.V1PodList(items=[pod1, pod2])
    v1.list_pod_for_all_namespaces.return_value = response
    client.CoreV1Api.return_value = v1
    node_client.CoreV1Api.return_value = v1
    node_client.V1NodeList.return_value = k8sClient.V1NodeList(items=[])

    resp = all_pods_in_all_ns_are_ok(configuration={"ns-ignore-list": []})
    v1.list_pod_for_all_namespaces.assert_called_with(watch=False)
    assert resp is True
def test_all_pods_in_all_ns_are_ok_failure(nodes_client, client, has_conf):
    node_name = 'node1'
    has_conf.return_value = False
    v1 = MagicMock()

    pod1 = create_pod_object("fakepod1", node_name=node_name)
    pod2 = create_pod_object("fakepod2",
                             state='terminated',
                             node_name=node_name)
    pod2.status.container_statuses[0].running = None
    pod2.spec.node_name = node_name

    response = k8sClient.V1PodList(items=[pod1, pod2])
    v1.list_pod_for_all_namespaces.return_value = response

    node = MagicMock()
    node.metadata.name = "node1"
    v1.list_node_with_http_info.return_value = k8sClient.V1NodeList(
        items=[node])

    nodes_client.CoreV1Api.return_value = v1
    nodes_client.V1NodeList.return_value = k8sClient.V1NodeList(items=[])
    client.CoreV1Api.return_value = v1

    resp = all_pods_in_all_ns_are_ok(
        configuration={"ns-ignore-list": ["db-catalog"]})
    v1.list_pod_for_all_namespaces.assert_called_with(watch=False)
    assert resp is False
Esempio n. 6
0
 def test_filterIpedWorkers(self):
     status = client.V1PodStatus(host_ip="1.2.3.4", pod_ip='6.7.8.9')
     metadata = client.V1ObjectMeta(name='notipedworker-myname')
     spec = client.V1PodSpec(node_name='sardcloudXX', containers=[])
     pods = [client.V1Pod(status=status, metadata=metadata, spec=spec)]
     podList = client.V1PodList(items=pods)
     workers: List[IPEDWorker] = _listWorkers(podList)
     self.assertEqual(len(workers), 0)
Esempio n. 7
0
def test_get_pod_finds_no_pod(mocker: MockFixture, k8s_api_client_mock: K8SAPIClient):
    fake_pods = []
    fake_pods_list = k8s_models.V1PodList(items=fake_pods)

    mocker.patch.object(k8s_api_client_mock.v1_api_client, 'list_namespaced_pod').return_value = fake_pods_list

    found_pod = k8s_api_client_mock.get_pod(namespace=MY_FAKE_NAMESPACE, label_selector=FAKE_LABEL_SELECTOR)

    assert found_pod is None
Esempio n. 8
0
 def FilterNonChaosPods(self, podList, chaosDetails, clients):
     if chaosDetails.AppDetail.Label == "":
         nonChaosPods = []
         # ignore chaos pods
         for pod in podList.items:
             if pod.metadata.labels.get(
                     "chaosUID") == "" and pod.metadata.labels.get(
                         "name") != "chaos-operator":
                 nonChaosPods.append(pod)
         return client.V1PodList(items=nonChaosPods)
     return podList
Esempio n. 9
0
 def list_namespaced_pod(self, namespace, label_selector):
     print(namespace)
     if label_selector not in MockCoreV1ApiForTTL.pod_map.keys():
         return client.V1PodList(items=[])
     else:
         pods = client.V1PodList(
             items=MockCoreV1ApiForTTL.pod_map[label_selector].copy())
         if pods.items:
             pods.items[0].status.container_statuses = [
                 client.V1ContainerStatus(
                     state=client.V1ContainerStateTerminated(exit_code=0),
                     image='aaa',
                     image_id='aaa',
                     name='name',
                     container_id='id',
                     ready=True,
                     restart_count=0)
             ]
         print("Sending {} pods".format(len(pods.items)))
         return pods
Esempio n. 10
0
def test_get_pod_finds_many_pods(mocker: MockFixture, k8s_api_client_mock: K8SAPIClient):
    fake_pod = k8s_models.V1Pod(metadata=k8s_models.V1ObjectMeta(name=FAKE_OBJECT_NAME))
    fake_second_pod = k8s_models.V1Pod(metadata=k8s_models.V1ObjectMeta(name=FAKE_OBJECT_NAME+'-2'))
    fake_pods = [fake_pod, fake_second_pod]
    fake_pods_list = k8s_models.V1PodList(items=fake_pods)

    mocker.patch.object(k8s_api_client_mock.v1_api_client, 'list_namespaced_pod').return_value = fake_pods_list

    found_pod = k8s_api_client_mock.get_pod(namespace=MY_FAKE_NAMESPACE, label_selector=FAKE_LABEL_SELECTOR)

    assert found_pod in (fake_pod, fake_second_pod)
def test_all_pods_in_all_ns_are_ok(cl, client, has_conf):
    has_conf.return_value = False
    v1 = MagicMock()

    pod1 = create_pod_object("fakepod1")
    pod2 = create_pod_object("fakepod2")

    response = k8sClient.V1PodList(items=[pod1, pod2])
    v1.list_pod_for_all_namespaces.return_value = response
    client.CoreV1Api.return_value = v1

    resp = all_pods_in_all_ns_are_ok(
        configuration={"ns-ignore-list": ["db-catalog"]})
    v1.list_pod_for_all_namespaces.assert_called_with(watch=False)
    assert resp is True
Esempio n. 12
0
    def GetTargetPodsWhenTargetPodsENVSet(self, targetPods, chaosDetails,
                                          clients):
        try:
            podList = clients.clientCoreV1.list_namespaced_pod(
                chaosDetails.AppDetail.Namespace,
                label_selector=chaosDetails.AppDetail.Label)
        except Exception as exp:
            return client.V1PodList, exp

        if len(podList.items) == 0:
            return client.V1PodList, ValueError(
                "Failed to find the pods with matching labels in {} namespace".
                format(chaosDetails.AppDetail.Namespace))

        targetPodsList = targetPods.split(",")
        realPodList = []
        for pod in podList.items:
            for podTarget in targetPodsList:
                parentName, err = annotation.GetParentName(
                    clients, pod, chaosDetails)
                if err != None:
                    return client.V1PodList, err
                if podTarget == pod.metadata.name:
                    if chaosDetails.AppDetail.AnnotationCheck:
                        isPodAnnotated, err = annotation.IsParentAnnotated(
                            clients, parentName, chaosDetails)
                        if err != None:
                            return client.V1PodList, err

                        if not isPodAnnotated:
                            return client.V1PodList, ValueError(
                                "{} target pods are not annotated".format(
                                    targetPods))

                    realPodList.append(pod)
                    logging.info(
                        "[Info]: chaos candidate of kind: %s, name: %s, namespace: %s",
                        chaosDetails.AppDetail.Kind, parentName,
                        chaosDetails.AppDetail.Namespace)

        return client.V1PodList(items=realPodList), None
Esempio n. 13
0
 def test_list1IpedWorker(self):
     state = client.V1ContainerState(running=None)
     containerStatus = client.V1ContainerStatus(image='image',
                                                image_id='1',
                                                name='2',
                                                ready=True,
                                                restart_count=0,
                                                state=state)
     status = client.V1PodStatus(host_ip="1.2.3.4",
                                 pod_ip='6.7.8.9',
                                 container_statuses=[containerStatus])
     metadata = client.V1ObjectMeta(name='ipedworker-myname')
     spec = client.V1PodSpec(node_name='sardcloudXX', containers=[])
     pods = [client.V1Pod(status=status, metadata=metadata, spec=spec)]
     podList = client.V1PodList(items=pods)
     workers: List[IPEDWorker] = _listWorkers(podList)
     self.assertEqual(len(workers), 1)
     w0: IPEDWorker = workers[0]
     self.assertEqual(w0.name, "ipedworker-myname")
     self.assertEqual(w0.host_ip, "1.2.3.4")
     self.assertEqual(w0.pod_ip, "6.7.8.9")
     self.assertEqual(w0.node_name, "sardcloudXX")
     self.assertEqual(w0.ready, True)
     self.assertEqual(w0.image, 'image')
Esempio n. 14
0
 def test_listEmptyIpedWorkers(self):
     pods = []
     podList = client.V1PodList(items=pods)
     workers: List[IPEDWorker] = _listWorkers(podList)
     self.assertListEqual(workers, [])