本文整理汇总了Java中io.fabric8.kubernetes.client.KubernetesClient类的典型用法代码示例。如果您正苦于以下问题:Java KubernetesClient类的具体用法?Java KubernetesClient怎么用?Java KubernetesClient使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
KubernetesClient类属于io.fabric8.kubernetes.client包,在下文中一共展示了KubernetesClient类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: createKubernetesClient
import io.fabric8.kubernetes.client.KubernetesClient; //导入依赖的package包/类
static KubernetesClient createKubernetesClient(ContainerEngineCluster gkeCluster) {
try {
final GoogleCredential credential = GoogleCredential.getApplicationDefault()
.createScoped(ContainerScopes.all());
final Container gke = new Container.Builder(credential.getTransport(), credential.getJsonFactory(), credential)
.setApplicationName("hype")
.build();
final Cluster cluster = gke.projects().zones().clusters()
.get(gkeCluster.project(), gkeCluster.zone(), gkeCluster.cluster())
.execute();
final io.fabric8.kubernetes.client.Config kubeConfig = new ConfigBuilder()
.withMasterUrl("https://" + cluster.getEndpoint())
.withCaCertData(cluster.getMasterAuth().getClusterCaCertificate())
.withClientCertData(cluster.getMasterAuth().getClientCertificate())
.withClientKeyData(cluster.getMasterAuth().getClientKey())
.build();
return new DefaultKubernetesClient(kubeConfig).inNamespace(NAMESPACE);
} catch (IOException e) {
throw Throwables.propagate(e);
}
}
示例2: fetchPods
import io.fabric8.kubernetes.client.KubernetesClient; //导入依赖的package包/类
private void fetchPods(KubernetesClient dockerClient) throws ParseException {
final Map<String, KubernetesNode> dockerNodeMap = nodes.stream().distinct().collect(toMap(KubernetesNode::getName, node -> node));
final List<Pod> pods = dockerClient.pods().inNamespace(Constants.KUBERNETES_NAMESPACE_KEY)
.withLabel(Constants.CREATED_BY_LABEL_KEY, Constants.PLUGIN_ID)
.list().getItems();
LOG.info("Running pods " + pods.size());
for (Pod pod : pods) {
final KubernetesPod kubernetesPod = new KubernetesPod(pod);
final KubernetesNode kubernetesNode = dockerNodeMap.get(kubernetesPod.getNodeName());
if (kubernetesNode != null) {
kubernetesNode.add(kubernetesPod);
}
}
}
示例3: unregisteredAfterTimeout
import io.fabric8.kubernetes.client.KubernetesClient; //导入依赖的package包/类
private KubernetesAgentInstances unregisteredAfterTimeout(PluginSettings settings, Agents knownAgents) throws Exception {
Period period = settings.getAutoRegisterPeriod();
KubernetesAgentInstances unregisteredInstances = new KubernetesAgentInstances();
KubernetesClient client = factory.kubernetes(settings);
for (String instanceName : instances.keySet()) {
if (knownAgents.containsAgentWithId(instanceName)) {
continue;
}
Pod pod = client.pods().inNamespace(Constants.KUBERNETES_NAMESPACE_KEY).withName(instanceName).get();
Date createdAt = getSimpleDateFormat().parse(pod.getMetadata().getCreationTimestamp());
DateTime dateTimeCreated = new DateTime(createdAt);
if (clock.now().isAfter(dateTimeCreated.plus(period))) {
unregisteredInstances.register(kubernetesInstanceFactory.fromKubernetesPod(pod));
}
}
return unregisteredInstances;
}
示例4: shouldCreateKubernetesClusterObject
import io.fabric8.kubernetes.client.KubernetesClient; //导入依赖的package包/类
@Test
public void shouldCreateKubernetesClusterObject() throws Exception {
final KubernetesClient kubernetesClient = mock(KubernetesClient.class);
NodeOperationsImpl nodes = mock(NodeOperationsImpl.class);
PodOperationsImpl pods = mock(PodOperationsImpl.class);
when(nodes.list()).thenReturn(new NodeList());
when(kubernetesClient.nodes()).thenReturn(nodes);
when(pods.inNamespace(Constants.KUBERNETES_NAMESPACE_KEY)).thenReturn(pods);
when(pods.withLabel(Constants.CREATED_BY_LABEL_KEY, Constants.PLUGIN_ID)).thenReturn(pods);
when(pods.list()).thenReturn(new PodList());
when(kubernetesClient.pods()).thenReturn(pods);
final KubernetesCluster cluster = new KubernetesCluster(kubernetesClient);
verify(kubernetesClient, times(1)).nodes();
verify(kubernetesClient, times(1)).pods();
}
示例5: selectNamespace
import io.fabric8.kubernetes.client.KubernetesClient; //导入依赖的package包/类
/**
* Choose a namespace that sounds like the specified namespace.
* @param client The client instance to use to query namespaces.
* @param namespace The specified namespace.
* @return The closest namespace if resemblance is over 80%, else null.
*/
public static final String selectNamespace(KubernetesClient client, String namespace) {
if (client.isAdaptable(OpenShiftClient.class)) {
return selectName(client.adapt(OpenShiftClient.class).projects()
.list()
.getItems()
.stream()
.map(n -> n.getMetadata().getName()), namespace);
} else {
return selectName(client.namespaces()
.list()
.getItems()
.stream()
.map(n -> n.getMetadata().getName()), namespace);
}
}
示例6: getData
import io.fabric8.kubernetes.client.KubernetesClient; //导入依赖的package包/类
private static Map<String, String> getData(KubernetesClient client, String name, String namespace) {
Map<String, String> result = new HashMap<>();
try {
ConfigMap map = namespace == null || namespace.isEmpty()
? client.configMaps().withName(name).get()
: client.configMaps().inNamespace(namespace).withName(name).get();
if (map != null) {
for (Map.Entry<String, String> entry : map.getData().entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if (key.equals(APPLICATION_YAML) || key.equals(APPLICATION_YML)) {
result.putAll(YAML_TO_PROPETIES.andThen(PROPERTIES_TO_MAP).apply(value));
} else if (key.equals(APPLICATION_PROPERTIES)) {
result.putAll(KEY_VALUE_TO_PROPERTIES.andThen(PROPERTIES_TO_MAP).apply(value));
} else {
result.put(key, value);
}
}
}
} catch (Exception e) {
LOGGER.warn("Can't read configMap with name: [" + name + "] in namespace:[" + namespace + "]. Ignoring");
}
return result;
}
示例7: createTestEnvironment
import io.fabric8.kubernetes.client.KubernetesClient; //导入依赖的package包/类
public static KubernetesTestEnvironment createTestEnvironment(Strategy strategy) throws IOException, ResourceConfigException, ResourceException {
Map<String, String> environmentVariables = TestEnvironmentUtil.loadEnvironmentVariables(
KUBERNETES_URL_ENV,
KUBERNETES_USERNAME_ENV,
KUBERNETES_PASSWORD_ENV,
KUBERNETES_NAMESPACE_PREFIX_ENV
);
String namespace = createNewTestNamespace(environmentVariables);
KubernetesEnvironmentConfig environmentConfig = createEnvironmentConfig(environmentVariables, strategy, namespace);
ClientFactory clientFactory = createClientFactory(environmentConfig);
KubernetesClient kubernetesClient = createKubernetesClient(environmentConfig);
NamespaceResource namespaceResource = createNamespaceResource(clientFactory, namespace);
return new KubernetesTestEnvironment(clientFactory, environmentConfig, namespaceResource, kubernetesClient);
}
示例8: getResource
import io.fabric8.kubernetes.client.KubernetesClient; //导入依赖的package包/类
@Override
public Resource<Pod> getResource(ObserverKey observerKey, KubernetesClient client) {
return new Resource<Pod>() {
@Override
public Watch watchResources(Watcher watcher) {
return client.pods().inNamespace(client.getNamespace()).withLabels(observerKey.getLabelFilter()).watch(watcher);
}
@Override
public Set<Pod> listResources() {
return client.pods().inNamespace(client.getNamespace()).withLabels(observerKey.getLabelFilter()).list().getItems().stream()
.filter(pod -> filterPod(observerKey, pod))
.map(Pod::new)
.collect(Collectors.toSet());
}
};
}
示例9: getResource
import io.fabric8.kubernetes.client.KubernetesClient; //导入依赖的package包/类
@Override
public Resource<TestResource> getResource(ObserverKey observerKey, KubernetesClient client) {
return new Resource<TestResource>() {
@Override
public Watch watchResources(Watcher watcher) {
return testWatch;
}
@Override
public Set<TestResource> listResources() {
try {
return stream.take();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
};
}
示例10: findServiceEntryAndSetValue
import io.fabric8.kubernetes.client.KubernetesClient; //导入依赖的package包/类
private static void findServiceEntryAndSetValue(
Object bean, List<Field> serverNameFields, JsonObject env, KubernetesClient client)
throws KubernetesClientException {
Objects.requireNonNull(client, "no client available");
serverNameFields.forEach(
serviceNameField -> {
final ServiceName serviceNameAnnotation =
serviceNameField.getAnnotation(ServiceName.class);
final String serviceName = serviceNameAnnotation.value();
final boolean withLabel = serviceNameField.isAnnotationPresent(WithLabel.class);
final boolean withLabels = serviceNameField.isAnnotationPresent(WithLabels.class);
if (isServiceNameOnly(withLabel, withLabels)) {
resolveByServiceName(bean, env, client, serviceNameField, serviceName);
} else {
resolveServiceByLabelOnly(bean, env, client, serviceNameField, withLabel, withLabels);
}
});
}
示例11: resolveServiceByLabelOnly
import io.fabric8.kubernetes.client.KubernetesClient; //导入依赖的package包/类
private static void resolveServiceByLabelOnly(
Object bean,
JsonObject env,
KubernetesClient client,
Field serviceNameField,
boolean withLabel,
boolean withLabels)
throws KubernetesClientException {
final Map<String, String> labels =
getLabelsFromAnnotation(env, serviceNameField, withLabel, withLabels);
final ServiceList serviceListResult = getServicesByLabel(labels, client);
Optional.ofNullable(serviceListResult)
.ifPresent(
list -> {
if (!list.getItems().isEmpty() && list.getItems().size() == 1) {
final Service serviceEntry = list.getItems().get(0);
resolveHostAndSetValue(bean, env, serviceNameField, serviceEntry);
} else if (!list.getItems().isEmpty() && list.getItems().size() > 1) {
handleNonUniqueLabelsError(labels);
}
});
}
示例12: logLastLines
import io.fabric8.kubernetes.client.KubernetesClient; //导入依赖的package包/类
/**
* Log the last lines of containers logs
*/
private void logLastLines(List<ContainerStatus> containers, String podId, String namespace, KubernetesSlave slave,
Map<String, Integer> errors, KubernetesClient client) {
for (ContainerStatus containerStatus : containers) {
String containerName = containerStatus.getName();
PrettyLoggable<String, LogWatch> tailingLines = client.pods().inNamespace(namespace)
.withName(podId).inContainer(containerStatus.getName()).tailingLines(30);
String log = tailingLines.getLog();
if (!StringUtils.isBlank(log)) {
String msg = errors != null ? String.format(" exited with error %s", errors.get(containerName))
: "";
LOGGER.log(Level.SEVERE,
"Error in provisioning; agent={0}, template={1}. Container {2}{3}. Logs: {4}",
new Object[]{slave, slave.getTemplate(), containerName, msg, tailingLines.getLog()});
}
}
}
示例13: runWithOverriddenNamespace
import io.fabric8.kubernetes.client.KubernetesClient; //导入依赖的package包/类
@Test
public void runWithOverriddenNamespace() throws Exception {
String overriddenNamespace = testingNamespace + "-overridden-namespace";
KubernetesClient client = cloud.connect();
// Run in our own testing namespace
if (client.namespaces().withName(overriddenNamespace).get() == null) {
client.namespaces().createOrReplace(
new NamespaceBuilder().withNewMetadata().withName(overriddenNamespace).endMetadata().build());
}
WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "overriddenNamespace");
p.setDefinition(new CpsFlowDefinition(loadPipelineScript("runWithOverriddenNamespace.groovy"), true));
WorkflowRun b = p.scheduleBuild2(0).waitForStart();
assertNotNull(b);
NamespaceAction.push(b, overriddenNamespace);
r.assertBuildStatusSuccess(r.waitForCompletion(b));
r.assertLogContains(overriddenNamespace, b);
}
示例14: runWithStepOverriddenNamespace
import io.fabric8.kubernetes.client.KubernetesClient; //导入依赖的package包/类
@Test
/**
* Step namespace should have priority over anything else.
*/
public void runWithStepOverriddenNamespace() throws Exception {
String overriddenNamespace = testingNamespace + "-overridden-namespace";
String stepNamespace = testingNamespace + "-overridden-namespace2";
KubernetesClient client = cloud.connect();
// Run in our own testing namespace
if (client.namespaces().withName(stepNamespace).get() == null) {
client.namespaces().createOrReplace(
new NamespaceBuilder().withNewMetadata().withName(stepNamespace).endMetadata().build());
}
WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "stepOverriddenNamespace");
p.setDefinition(new CpsFlowDefinition(loadPipelineScript("runWithStepOverriddenNamespace.groovy")
.replace("OVERRIDDEN_NAMESPACE", stepNamespace), true));
WorkflowRun b = p.scheduleBuild2(0).waitForStart();
assertNotNull(b);
NamespaceAction.push(b, overriddenNamespace);
r.assertBuildStatusSuccess(r.waitForCompletion(b));
r.assertLogContains(stepNamespace, b);
}
示例15: createAndSaveKubernetesAppDeployers
import io.fabric8.kubernetes.client.KubernetesClient; //导入依赖的package包/类
protected Deployer createAndSaveKubernetesAppDeployers(String account,
KubernetesDeployerProperties kubernetesProperties) {
KubernetesClient kubernetesClient = new DefaultKubernetesClient()
.inNamespace(kubernetesProperties.getNamespace());
ContainerFactory containerFactory = new DefaultContainerFactory(
kubernetesProperties);
KubernetesAppDeployer kubernetesAppDeployer = new KubernetesAppDeployer(
kubernetesProperties, kubernetesClient, containerFactory);
Deployer deployer = new Deployer(account, "kubernetes", kubernetesAppDeployer);
deployer.setDescription(
String.format("master url = [%s], namespace = [%s], api version = [%s]",
kubernetesClient.getMasterUrl(), kubernetesClient.getNamespace(),
kubernetesClient.getApiVersion()));
return deployer;
}