Search in sources :

Example 1 with V1Pod

use of io.kubernetes.client.openapi.models.V1Pod in project pravega by pravega.

the class K8SequentialExecutor method startTestExecution.

@Override
public CompletableFuture<Void> startTestExecution(Method testMethod) {
    final String className = testMethod.getDeclaringClass().getName();
    final String methodName = testMethod.getName();
    // pod name is the combination of a test method name and random Alphanumeric. It cannot be more than 63 characters.
    final String podName = (methodName + "-" + randomAlphanumeric(5)).toLowerCase();
    log.info("Start execution of test {}#{} on the KUBERNETES Cluster", className, methodName);
    final K8sClient client = ClientFactory.INSTANCE.getK8sClient();
    Map<String, V1ContainerStatus> podStatusBeforeTest = getPravegaPodStatus(client);
    final V1Pod pod = getTestPod(className, methodName, podName.toLowerCase());
    final AtomicReference<CompletableFuture<Void>> logDownload = new AtomicReference<>(CompletableFuture.completedFuture(null));
    return // create service Account, ignore if already present.
    client.createServiceAccount(NAMESPACE, getServiceAccount()).thenCompose(// ensure test pod has cluster admin rights.
    v -> client.createClusterRoleBinding(getClusterRoleBinding())).thenCompose(// deploy test pod.
    v -> client.deployPod(NAMESPACE, pod)).thenCompose(v -> {
        // start download of logs.
        if (!Utils.isSkipLogDownloadEnabled()) {
            logDownload.set(client.downloadLogs(pod, "./build/test-results/" + podName));
        }
        return client.waitUntilPodCompletes(NAMESPACE, podName);
    }).handle((s, t) -> {
        Futures.getAndHandleExceptions(logDownload.get(), t1 -> {
            log.error("Failed to download logs for {}#{}", className, methodName, t1);
            return null;
        });
        if (t == null) {
            log.info("Test {}#{} execution completed with status {}", className, methodName, s);
            verifyPravegaPodRestart(podStatusBeforeTest, getPravegaPodStatus(client));
            if (s.getExitCode() != 0) {
                log.error("Test {}#{} failed. Details: {}", className, methodName, s);
                throw new AssertionError(methodName + " test failed due to " + s.getReason() + " with message " + s.getMessage());
            } else {
                return null;
            }
        } else {
            throw new CompletionException("Error while invoking the test " + podName, t);
        }
    });
}
Also used : TestExecutor(io.pravega.test.system.framework.TestExecutor) RandomStringUtils.randomAlphanumeric(org.apache.commons.lang.RandomStringUtils.randomAlphanumeric) CompletableFuture(java.util.concurrent.CompletableFuture) TestFrameworkException(io.pravega.test.system.framework.TestFrameworkException) AtomicReference(java.util.concurrent.atomic.AtomicReference) V1VolumeMountBuilder(io.kubernetes.client.openapi.models.V1VolumeMountBuilder) V1VolumeBuilder(io.kubernetes.client.openapi.models.V1VolumeBuilder) Map(java.util.Map) NotImplementedException(org.apache.commons.lang.NotImplementedException) V1beta1ClusterRoleBinding(io.kubernetes.client.openapi.models.V1beta1ClusterRoleBinding) V1ServiceAccount(io.kubernetes.client.openapi.models.V1ServiceAccount) V1ContainerStatus(io.kubernetes.client.openapi.models.V1ContainerStatus) V1SecretVolumeSourceBuilder(io.kubernetes.client.openapi.models.V1SecretVolumeSourceBuilder) Utils(io.pravega.test.system.framework.Utils) V1beta1RoleRefBuilder(io.kubernetes.client.openapi.models.V1beta1RoleRefBuilder) Method(java.lang.reflect.Method) ImmutableMap(com.google.common.collect.ImmutableMap) K8sClient(io.pravega.test.system.framework.kubernetes.K8sClient) V1ServiceAccountBuilder(io.kubernetes.client.openapi.models.V1ServiceAccountBuilder) CompletionException(java.util.concurrent.CompletionException) Collectors(java.util.stream.Collectors) ClientFactory(io.pravega.test.system.framework.kubernetes.ClientFactory) V1beta1ClusterRoleBindingBuilder(io.kubernetes.client.openapi.models.V1beta1ClusterRoleBindingBuilder) Slf4j(lombok.extern.slf4j.Slf4j) V1PersistentVolumeClaimVolumeSourceBuilder(io.kubernetes.client.openapi.models.V1PersistentVolumeClaimVolumeSourceBuilder) V1PodBuilder(io.kubernetes.client.openapi.models.V1PodBuilder) V1beta1SubjectBuilder(io.kubernetes.client.openapi.models.V1beta1SubjectBuilder) V1ObjectMetaBuilder(io.kubernetes.client.openapi.models.V1ObjectMetaBuilder) Futures(io.pravega.common.concurrent.Futures) V1Pod(io.kubernetes.client.openapi.models.V1Pod) CompletableFuture(java.util.concurrent.CompletableFuture) K8sClient(io.pravega.test.system.framework.kubernetes.K8sClient) V1ContainerStatus(io.kubernetes.client.openapi.models.V1ContainerStatus) CompletionException(java.util.concurrent.CompletionException) V1Pod(io.kubernetes.client.openapi.models.V1Pod) AtomicReference(java.util.concurrent.atomic.AtomicReference)

Example 2 with V1Pod

use of io.kubernetes.client.openapi.models.V1Pod in project pravega by pravega.

the class K8sClient method deployPod.

/**
 * Deploy a pod. This ignores exception when the pod has already been deployed.
 * @param namespace Namespace.
 * @param pod Pod details.
 * @return Future which is completed once the deployemnt has been triggered.
 */
@SneakyThrows(ApiException.class)
public CompletableFuture<V1Pod> deployPod(final String namespace, final V1Pod pod) {
    CoreV1Api api = new CoreV1Api();
    K8AsyncCallback<V1Pod> callback = new K8AsyncCallback<>("createPod-" + pod.getMetadata().getName());
    api.createNamespacedPodAsync(namespace, pod, PRETTY_PRINT, DRY_RUN, FIELD_MANAGER, callback);
    return exceptionallyExpecting(callback.getFuture(), isConflict, null);
}
Also used : V1Pod(io.kubernetes.client.openapi.models.V1Pod) CoreV1Api(io.kubernetes.client.openapi.apis.CoreV1Api) SneakyThrows(lombok.SneakyThrows)

Example 3 with V1Pod

use of io.kubernetes.client.openapi.models.V1Pod in project pravega by pravega.

the class K8sClient method getStatusOfPod.

/**
 * Method used to fetch the status of a Pod. V1PodStatus also helps to indicate the container status.
 * @param namespace Namespace.
 * @param podName Name of the pod.
 * @return A future representing the status of the pod.
 */
@SneakyThrows(ApiException.class)
public CompletableFuture<V1PodStatus> getStatusOfPod(final String namespace, final String podName) {
    CoreV1Api api = new CoreV1Api();
    K8AsyncCallback<V1PodList> callback = new K8AsyncCallback<>("listPods");
    api.listNamespacedPodAsync(namespace, PRETTY_PRINT, ALLOW_WATCH_BOOKMARKS, null, null, "POD_NAME=" + podName, null, null, null, false, callback);
    return callback.getFuture().thenApply(v1PodList -> {
        Optional<V1Pod> vpod = v1PodList.getItems().stream().filter(v1Pod -> v1Pod.getMetadata().getName().equals(podName) && v1Pod.getMetadata().getNamespace().equals(namespace)).findFirst();
        return vpod.map(V1Pod::getStatus).orElseThrow(() -> new RuntimeException("pod not found" + podName));
    });
}
Also used : V1PodList(io.kubernetes.client.openapi.models.V1PodList) PodLogs(io.kubernetes.client.PodLogs) TypeToken(com.google.gson.reflect.TypeToken) SneakyThrows(lombok.SneakyThrows) Retry(io.pravega.common.util.Retry) V1beta1CustomResourceDefinition(io.kubernetes.client.openapi.models.V1beta1CustomResourceDefinition) Cleanup(lombok.Cleanup) V1PodList(io.kubernetes.client.openapi.models.V1PodList) V1PodStatus(io.kubernetes.client.openapi.models.V1PodStatus) TestFrameworkException(io.pravega.test.system.framework.TestFrameworkException) ApiextensionsV1beta1Api(io.kubernetes.client.openapi.apis.ApiextensionsV1beta1Api) Futures.exceptionallyExpecting(io.pravega.common.concurrent.Futures.exceptionallyExpecting) V1beta1ClusterRole(io.kubernetes.client.openapi.models.V1beta1ClusterRole) V1Patch(io.kubernetes.client.custom.V1Patch) Configuration(io.kubernetes.client.openapi.Configuration) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Duration(java.time.Duration) Map(java.util.Map) V1beta1ClusterRoleBinding(io.kubernetes.client.openapi.models.V1beta1ClusterRoleBinding) V1ServiceAccount(io.kubernetes.client.openapi.models.V1ServiceAccount) V1DeleteOptions(io.kubernetes.client.openapi.models.V1DeleteOptions) ImmutableMap(com.google.common.collect.ImmutableMap) Predicate(java.util.function.Predicate) V1Secret(io.kubernetes.client.openapi.models.V1Secret) CONFLICT(javax.ws.rs.core.Response.Status.CONFLICT) NOT_FOUND(javax.ws.rs.core.Response.Status.NOT_FOUND) RbacAuthorizationV1beta1Api(io.kubernetes.client.openapi.apis.RbacAuthorizationV1beta1Api) V1Status(io.kubernetes.client.openapi.models.V1Status) Collectors(java.util.stream.Collectors) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) Optional(java.util.Optional) ApiCallback(io.kubernetes.client.openapi.ApiCallback) PatchUtils(io.kubernetes.client.util.PatchUtils) Futures(io.pravega.common.concurrent.Futures) V1Deployment(io.kubernetes.client.openapi.models.V1Deployment) Exceptions(io.pravega.common.Exceptions) Watch(io.kubernetes.client.util.Watch) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) AppsV1Api(io.kubernetes.client.openapi.apis.AppsV1Api) ApiClient(io.kubernetes.client.openapi.ApiClient) ApiException(io.kubernetes.client.openapi.ApiException) V1ConfigMap(io.kubernetes.client.openapi.models.V1ConfigMap) V1ContainerStateTerminated(io.kubernetes.client.openapi.models.V1ContainerStateTerminated) V1ObjectMeta(io.kubernetes.client.openapi.models.V1ObjectMeta) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) V1ContainerStatus(io.kubernetes.client.openapi.models.V1ContainerStatus) V1Namespace(io.kubernetes.client.openapi.models.V1Namespace) V1beta1Role(io.kubernetes.client.openapi.models.V1beta1Role) JsonSyntaxException(com.google.gson.JsonSyntaxException) Files(java.nio.file.Files) CustomObjectsApi(io.kubernetes.client.openapi.apis.CustomObjectsApi) IOException(java.io.IOException) CoreV1Api(io.kubernetes.client.openapi.apis.CoreV1Api) Config(io.kubernetes.client.util.Config) TimeUnit(java.util.concurrent.TimeUnit) ConnectionFailed(io.pravega.test.system.framework.TestFrameworkException.Type.ConnectionFailed) Paths(java.nio.file.Paths) V1ContainerState(io.kubernetes.client.openapi.models.V1ContainerState) ExecutorServiceHelpers(io.pravega.common.concurrent.ExecutorServiceHelpers) V1beta1RoleBinding(io.kubernetes.client.openapi.models.V1beta1RoleBinding) SECONDS(java.util.concurrent.TimeUnit.SECONDS) V1Pod(io.kubernetes.client.openapi.models.V1Pod) InputStream(java.io.InputStream) V1Pod(io.kubernetes.client.openapi.models.V1Pod) CoreV1Api(io.kubernetes.client.openapi.apis.CoreV1Api) SneakyThrows(lombok.SneakyThrows)

Example 4 with V1Pod

use of io.kubernetes.client.openapi.models.V1Pod in project java by kubernetes-client.

the class KubectlLabelTest method testKubectlLabelNamespacedResourceShouldWork.

@Test
public void testKubectlLabelNamespacedResourceShouldWork() throws KubectlException {
    wireMockRule.stubFor(get(urlPathEqualTo("/api/v1/namespaces/default/pods/foo")).willReturn(aResponse().withStatus(200).withBody("{\"metadata\":{\"name\":\"foo\",\"namespace\":\"default\"}}")));
    wireMockRule.stubFor(put(urlPathEqualTo("/api/v1/namespaces/default/pods/foo")).willReturn(aResponse().withStatus(200).withBody("{\"metadata\":{\"name\":\"foo\",\"namespace\":\"default\"}}")));
    V1Pod labelledPod = Kubectl.label(V1Pod.class).apiClient(apiClient).skipDiscovery().namespace("default").name("foo").addLabel("k1", "v1").addLabel("k2", "v2").execute();
    wireMockRule.verify(1, getRequestedFor(urlPathEqualTo("/api/v1/namespaces/default/pods/foo")));
    wireMockRule.verify(1, putRequestedFor(urlPathEqualTo("/api/v1/namespaces/default/pods/foo")));
    assertNotNull(labelledPod);
}
Also used : V1Pod(io.kubernetes.client.openapi.models.V1Pod) Test(org.junit.Test)

Example 5 with V1Pod

use of io.kubernetes.client.openapi.models.V1Pod in project java by kubernetes-client.

the class KubectlAnnotateTest method testKubectlAnnotateNamespacedResourceShouldWork.

@Test
public void testKubectlAnnotateNamespacedResourceShouldWork() throws KubectlException {
    wireMockRule.stubFor(get(urlPathEqualTo("/api/v1/namespaces/default/pods/foo")).willReturn(aResponse().withStatus(200).withBody("{\"metadata\":{\"name\":\"foo\",\"namespace\":\"default\"}}")));
    wireMockRule.stubFor(put(urlPathEqualTo("/api/v1/namespaces/default/pods/foo")).willReturn(aResponse().withStatus(200).withBody("{\"metadata\":{\"name\":\"foo\",\"namespace\":\"default\"}}")));
    V1Pod annotatedPod = Kubectl.annotate(V1Pod.class).apiClient(apiClient).skipDiscovery().namespace("default").name("foo").addAnnotation("k1", "v1").addAnnotation("k2", "v2").execute();
    wireMockRule.verify(1, getRequestedFor(urlPathEqualTo("/api/v1/namespaces/default/pods/foo")));
    wireMockRule.verify(1, putRequestedFor(urlPathEqualTo("/api/v1/namespaces/default/pods/foo")));
    assertNotNull(annotatedPod);
}
Also used : V1Pod(io.kubernetes.client.openapi.models.V1Pod) Test(org.junit.Test)

Aggregations

V1Pod (io.kubernetes.client.openapi.models.V1Pod)96 Test (org.junit.Test)55 V1ObjectMeta (io.kubernetes.client.openapi.models.V1ObjectMeta)38 V1PodList (io.kubernetes.client.openapi.models.V1PodList)31 Type (java.lang.reflect.Type)22 ApiException (io.kubernetes.client.openapi.ApiException)17 CoreV1Api (io.kubernetes.client.openapi.apis.CoreV1Api)17 V1ListMeta (io.kubernetes.client.openapi.models.V1ListMeta)15 ApiClient (io.kubernetes.client.openapi.ApiClient)12 V1Status (io.kubernetes.client.openapi.models.V1Status)9 Watch (io.kubernetes.client.util.Watch)9 CallGeneratorParams (io.kubernetes.client.util.CallGeneratorParams)8 JSON (io.kubernetes.client.openapi.JSON)7 V1PodSpec (io.kubernetes.client.openapi.models.V1PodSpec)7 SharedInformerFactory (io.kubernetes.client.informer.SharedInformerFactory)6 IOException (java.io.IOException)6 InputStream (java.io.InputStream)5 WireMock.aResponse (com.github.tomakehurst.wiremock.client.WireMock.aResponse)4 V1Patch (io.kubernetes.client.custom.V1Patch)4 V1PodBuilder (io.kubernetes.client.openapi.models.V1PodBuilder)4