有谁知道API openshift-restclient-java是否可以重新启动POD

时间:2017-11-03 20:50:39

标签: openshift

我正在尝试以编程方式在openshift中重启POD?我可以使用此客户端API openshift-restclient-java

进行连接和查询

如果是,是否有任何示例代码或指向可提供的示例代码或链接?

2 个答案:

答案 0 :(得分:1)

我目前大约是第一次使用opensfhit-restclient-java进行游戏,并按照以下代码片段所示完成了您的任务。

代码的作用:

  1. 将服务实例缩放为0
  2. 等到豆荚真的没了
  3. 将服务实例缩放回1
  4. 等待直到服务实例真正启动
  5. 服务实例启动时需要执行的所有操作

实施:

private static boolean scaleDeployment(final IClient client,
                                           final String dcName,
                                           final String namespace,
                                           final int scale) {
        DeploymentConfig dc = client.get(ResourceKind.DEPLOYMENT_CONFIG, dcName, namespace);
        boolean result = false;
        if (dc != null) {
            dc.setDesiredReplicaCount(scale);
            client.update(dc);
            result = true;
        }

        return result;
    }

    private static boolean waitForPodToDisappear(final IClient client,
                                                 final String namespace,
                                                 final Map<String, String> labels,
                                                 final int maxTries,
                                                 final int waitInMillis) {
        int tries = 0;
        List<Pod> pods = client.list(ResourceKind.POD, namespace, labels);
        while (!pods.isEmpty() && tries < maxTries) {
            pods = client.list(ResourceKind.POD, namespace, labels);
            if (!pods.isEmpty()) {
                tries += 1;
                try {
                    Thread.sleep(waitInMillis);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        return pods.isEmpty();
    }

    private static boolean isPodReady(final Pod pod) {
        final List<ModelNode> conditions = pod.getNode()
                                              .get("status")
                                              .get("conditions")
                                              .asList();
        return conditions.stream()
                         .filter(node -> (node.get("type").asString().contains("Ready")))
                         .filter(node -> node.get("status").asString().contains("True"))
                         .count() == 1;
    }

    private static boolean waitForPodToBecomeReady(final IClient client,
                                                   final String namespace,
                                                   final Map<String, String> labels,
                                                   final int maxTries,
                                                   final int waitInMillis) {
        int tries = 0;
        boolean result = false;
        while (!result && tries < maxTries) {
            final List<Pod> pods = client.list(ResourceKind.POD, namespace, labels);
            if (pods.size() == 1) {
                result = isPodReady(pods.get(0));
            }
            if (!result) {
                tries += 1;
                try {
                    Thread.sleep(waitInMillis);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        return result;
    }

    private static void main(String args[]) {
        IClient client = new ClientBuilder().toCluster("https://127.0.0.1:8443")
                                            .withConnectTimeout(2, TimeUnit.SECONDS)
                                            .withUserName("developer")
                                            .withPassword("developer")
                                            .build();
        boolean result = false;
        // Stop service instance
        scaleDeployment(client, "myservice-dc", "namespace", 0);
        // Wait until service Pod is gone
        result = waitForPodToDisappear(client, "namespace", new HashMap<String, String>() {{
            put("name", "myservice-dc-label");
        }}, 100, 1000);
        if(result) {
          // Start backup service instance
          scaleDeployment(client, "myservice-dc", "namespace", 1);
          result = waitForPodToBecomeReady(client, "namespace", new HashMap<String, String>() {{
              put("name", "myservice-dc-label");
          }}, 100, 1000);
          if(result) {
            // Do stuff, which requires the pod to be ready
          }
        }
    }

正如我已经写过的,这些是我使用openshift-restclient-java的第一步。

对于oc 3.6+,您需要以下依赖项

        <dependency>
        <groupId>com.openshift</groupId>
        <artifactId>openshift-restclient-java</artifactId>
        <version>6.1.2.Final</version>
    </dependency>

答案 1 :(得分:0)

我使用此方法重启pod。我发布这个答案,以防有人有同样的任务。

def restartPod(podName: String, nameSpace: String): Boolean =  {

val serviceList: Seq[IResource] = openshiftClient.list[IResource](ResourceKind.DEPLOYMENT_CONFIG, nameSpace).filter(service => service.getName.startsWith(podName)).toList
serviceList match {
  case service :: _ => {
    scaleTo(service, 0) match {
      case None => println(s"Pod ${podName} successfully stopped.")
      case Some(ex) => {
        println(s"Error stopping pod ${podName} reason: ${ex.getMessage}")
      }
    }
    scaleTo(service, 1) match {
      case None => {
        val message = s"Pod ${podName} successfully started."
        println(message)
        (true)
      }
      case Some(ex) => {
        val message = s"Error starting pod ${podName} reason: ${ex.getMessage}"
        logger.error(message)
        (false)
      }
    }
  }
  case _ => {
    val message = s"Pod ${podName} could not be restarted because it was not found with that name."
    logger.error(message)
    (false)
  }
}
}

您需要以下库:

    <dependency>
        <groupId>com.openshift</groupId>
        <artifactId>openshift-restclient-java</artifactId>
        <version>1.0.1.6</version>
    </dependency>
相关问题