io.fabric8.kubernetes.api.model.Endpoints Java Examples

The following examples show how to use io.fabric8.kubernetes.api.model.Endpoints. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: EndpointsTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeleteMulti() {
  Endpoints endpoint1 = new EndpointsBuilder().withNewMetadata().withName("endpoint1").withNamespace("test").endMetadata().build();
  Endpoints endpoint2 = new EndpointsBuilder().withNewMetadata().withName("endpoint2").withNamespace("ns1").endMetadata().build();
  Endpoints endpoint3 = new EndpointsBuilder().withNewMetadata().withName("endpoint3").withNamespace("any").endMetadata().build();

  server.expect().withPath("/api/v1/namespaces/test/endpoints/endpoint1").andReturn(200, endpoint1).once();
  server.expect().withPath("/api/v1/namespaces/ns1/endpoints/endpoint2").andReturn(200, endpoint2).once();

  KubernetesClient client = server.getClient();
  Boolean deleted = client.endpoints().inAnyNamespace().delete(endpoint1, endpoint2);
  assertTrue(deleted);

  deleted = client.endpoints().inAnyNamespace().delete(endpoint3);
  assertFalse(deleted);
}
 
Example #2
Source File: K8sEndpointsManager.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public void removeEndpoints(String uid) {
    checkArgument(!Strings.isNullOrEmpty(uid), ERR_NULL_ENDPOINTS_UID);

    synchronized (this) {
        if (isEndpointsInUse(uid)) {
            final String error = String.format(MSG_ENDPOINTS, uid, ERR_IN_USE);
            throw new IllegalStateException(error);
        }

        Endpoints endpoints = k8sEndpointsStore.removeEndpoints(uid);

        if (endpoints != null) {
            log.info(String.format(MSG_ENDPOINTS,
                    endpoints.getMetadata().getName(), MSG_REMOVED));
        }
    }
}
 
Example #3
Source File: KubernetesDiscoveryClient.java    From spring-cloud-kubernetes with Apache License 2.0 6 votes vote down vote up
@Override
public ServiceInstance getLocalServiceInstance() {
    String serviceName = properties.getServiceName();
    String podName = System.getenv(HOSTNAME);
    ServiceInstance defaultInstance = new DefaultServiceInstance(serviceName, "localhost", 8080, false);

    Endpoints endpoints = client.endpoints().withName(serviceName).get();
    if (Utils.isNullOrEmpty(podName) || endpoints == null) {
        return defaultInstance;
    }
    try {
        return endpoints.getSubsets()
                .stream()
                .filter(s -> s.getAddresses().get(0).getTargetRef().getName().equals(podName))
                .map(s -> (ServiceInstance) new KubernetesServiceInstance(serviceName,
                        s.getAddresses().stream().findFirst().orElseThrow(IllegalStateException::new),
                        s.getPorts().stream().findFirst().orElseThrow(IllegalStateException::new),
                        false))
                .findFirst().orElse(defaultInstance);
    } catch (Throwable t) {
        return defaultInstance;
    }
}
 
Example #4
Source File: KubernetesDiscoveryClientFilterMetadataTest.java    From spring-cloud-kubernetes with Apache License 2.0 6 votes vote down vote up
private void setupServiceWithLabelsAndAnnotationsAndPorts(String serviceId,
		String namespace, Map<String, String> labels, Map<String, String> annotations,
		Map<Integer, String> ports) {
	final Service service = new ServiceBuilder().withNewMetadata()
			.withNamespace(namespace).withLabels(labels).withAnnotations(annotations)
			.endMetadata().withNewSpec().withPorts(getServicePorts(ports)).endSpec()
			.build();
	when(this.serviceOperation.withName(serviceId)).thenReturn(this.serviceResource);
	when(this.serviceResource.get()).thenReturn(service);
	when(this.kubernetesClient.services()).thenReturn(this.serviceOperation);
	when(this.kubernetesClient.services().inNamespace(anyString()))
			.thenReturn(this.serviceOperation);

	ObjectMeta objectMeta = new ObjectMeta();
	objectMeta.setNamespace(namespace);

	final Endpoints endpoints = new EndpointsBuilder().withMetadata(objectMeta)
			.addNewSubset().addAllToPorts(getEndpointPorts(ports)).addNewAddress()
			.endAddress().endSubset().build();

	when(this.endpointsResource.get()).thenReturn(endpoints);
	when(this.endpointsOperation.withName(serviceId))
			.thenReturn(this.endpointsResource);
	when(this.kubernetesClient.endpoints()).thenReturn(this.endpointsOperation);
}
 
Example #5
Source File: KubernetesNameResolver.java    From grpc-by-example-java with Apache License 2.0 6 votes vote down vote up
@Override
@GuardedBy("this")
public void refresh() {
  if (refreshing) return;
  try {
    refreshing = true;

    Endpoints endpoints = kubernetesClient.endpoints().inNamespace(namespace)
        .withName(name)
        .get();

    if (endpoints == null) {
      // Didn't find anything, retrying
      ScheduledExecutorService timerService = SharedResourceHolder.get(timerServiceResource);
      timerService.schedule(() -> {
        refresh();
      }, 30, TimeUnit.SECONDS);
      return;
    }

    update(endpoints);
    watch();
  } finally {
    refreshing = false;
  }
}
 
Example #6
Source File: KubernetesNameResolver.java    From grpc-by-example-java with Apache License 2.0 6 votes vote down vote up
private void update(Endpoints endpoints) {
    List<EquivalentAddressGroup> servers = new ArrayList<>();
    if (endpoints.getSubsets() == null) return;
    endpoints.getSubsets().stream().forEach(subset -> {
      long matchingPorts = subset.getPorts().stream().filter(p -> {
        return p != null && p.getPort() == port;
      }).count();
      if (matchingPorts > 0) {
        subset.getAddresses().stream().map(address -> {
          return new EquivalentAddressGroup(new InetSocketAddress(address.getIp(), port));
        }).forEach(address -> {
          servers.add(address);
        });
      }
    });

    listener.onAddresses(servers, Attributes.EMPTY);
}
 
Example #7
Source File: K8sEndpointsWatcher.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public void eventReceived(Action action, Endpoints endpoints) {
    switch (action) {
        case ADDED:
            eventExecutor.execute(() -> processAddition(endpoints));
            break;
        case MODIFIED:
            eventExecutor.execute(() -> processModification(endpoints));
            break;
        case DELETED:
            eventExecutor.execute(() -> processDeletion(endpoints));
            break;
        case ERROR:
            log.warn("Failures processing endpoints manipulation.");
            break;
        default:
            // do nothing
            break;
    }
}
 
Example #8
Source File: Readiness.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
public static boolean isEndpointsReady(Endpoints e) {
  Utils.checkNotNull(e, "Endpoints can't be null.");
  String name = e.getMetadata().getName();
  Utils.checkNotNull(name, "Endpoints name can't be null.");

  if (e.getSubsets() == null) {
    return false;
  }

  for (EndpointSubset subset : e.getSubsets()) {
    if(!subset.getAddresses().isEmpty() && !subset.getPorts().isEmpty()) {
      return true;
    }
  }
  return false;
}
 
Example #9
Source File: Readiness.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
public static boolean isReady(HasMetadata item) {
  if (item instanceof Deployment) {
    return isDeploymentReady((Deployment) item);
  } else if (item instanceof ReplicaSet) {
    return isReplicaSetReady((ReplicaSet) item);
  } else if (item instanceof Pod) {
    return isPodReady((Pod) item);
  } else if (item instanceof DeploymentConfig) {
    return isDeploymentConfigReady((DeploymentConfig) item);
  } else if (item instanceof ReplicationController) {
    return isReplicationControllerReady((ReplicationController) item);
  } else if (item instanceof Endpoints) {
    return isEndpointsReady((Endpoints) item);
  } else if (item instanceof Node) {
    return isNodeReady((Node) item);
  } else if (item instanceof StatefulSet) {
    return isStatefulSetReady((StatefulSet) item);
  } else {
    throw new IllegalArgumentException("Item needs to be one of [Node, Deployment, ReplicaSet, StatefulSet, Pod, DeploymentConfig, ReplicationController], but was: [" + (item != null ? item.getKind() : "Unknown (null)") + "]");
  }
}
 
Example #10
Source File: EndpointsTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testBuild() {
  Endpoints endpoints = new EndpointsBuilder()
    .withNewMetadata().withName("endpoint").withNamespace("test").endMetadata()
    .withSubsets().addNewSubset().addNewAddress().withIp("10.10.50.53").endAddress()
    .addNewPort().withPort(80).withName("apache").endPort()
    .endSubset()
    .build();

  server.expect().withPath("/api/v1/namespaces/test/endpoints/endpoint").andReturn(200, endpoints).once();

  KubernetesClient client = server.getClient();
  endpoints = client.endpoints().inNamespace("test").withName("endpoint").get();
  assertNotNull(endpoints);
  assertEquals("apache", endpoints.getSubsets().get(0).getPorts().get(0).getName());
}
 
Example #11
Source File: K8sSyncStateCommand.java    From onos with Apache License 2.0 6 votes vote down vote up
private void printEndpoints(Endpoints endpoints) {
    List<String> ips = Lists.newArrayList();
    List<Integer> ports = Lists.newArrayList();

    endpoints.getSubsets().forEach(e -> {
        e.getAddresses().forEach(a -> ips.add(a.getIp()));
        e.getPorts().forEach(p -> ports.add(p.getPort()));
    });

    print(ENDPOINTS_FORMAT,
            StringUtils.substring(endpoints.getMetadata().getName(),
                    0, CLI_NAME_LENGTH - CLI_MARGIN_LENGTH),
            ips.isEmpty() ? "" : StringUtils.substring(ips.toString(),
                    0, CLI_IP_ADDRESSES_LENGTH - CLI_MARGIN_LENGTH),
            ports.isEmpty() ? "" : ports);
}
 
Example #12
Source File: KubernetesDiscoveryClient.java    From spring-cloud-kubernetes with Apache License 2.0 6 votes vote down vote up
@Override
public List<ServiceInstance> getInstances(String serviceId) {
	Assert.notNull(serviceId,
			"[Assertion failed] - the object argument must not be null");

	List<Endpoints> endpointsList = this.properties.isAllNamespaces()
			? this.client.endpoints().inAnyNamespace()
					.withField("metadata.name", serviceId).list().getItems()
			: Collections
					.singletonList(this.client.endpoints().withName(serviceId).get());

	List<EndpointSubsetNS> subsetsNS = endpointsList.stream()
			.map(endpoints -> getSubsetsFromEndpoints(endpoints))
			.collect(Collectors.toList());

	List<ServiceInstance> instances = new ArrayList<>();
	if (!subsetsNS.isEmpty()) {
		for (EndpointSubsetNS es : subsetsNS) {
			instances.addAll(this.getNamespaceServiceInstances(es, serviceId));
		}
	}

	return instances;
}
 
Example #13
Source File: ServiceMockBuilder.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
/** Override Service creation to also create Endpoints */
@Override
protected void mockCreate(String resourceName, ServiceResource<Service, DoneableService> resource) {
    when(resource.create(any())).thenAnswer(i -> {
        Service argument = i.getArgument(0);
        db.put(resourceName, copyResource(argument));
        LOGGER.debug("create {} (and endpoint) {} ", resourceType, resourceName);
        endpointsDb.put(resourceName, new Endpoints());
        return argument;
    });
}
 
Example #14
Source File: EndpointsExample.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
  String master = "https://localhost:8443";

  Config config = new ConfigBuilder().withMasterUrl(master).build();
  try (final KubernetesClient client = new DefaultKubernetesClient(config)) {
    try {
      String namespace = "default";
      log("namespace", namespace);
      Deployment deployment = client.apps().deployments().inNamespace(namespace).load(EndpointsExample.class.getResourceAsStream("/endpoints-deployment.yml")).get();
      log("Deployment created");
      client.apps().deployments().inNamespace(namespace).create(deployment);

      Service service = client.services().inNamespace(namespace).load(EndpointsExample.class.getResourceAsStream("/endpoints-service.yml")).get();
      log("Service created");
      client.services().inNamespace(namespace).create(service);

      Endpoints endpoints = new EndpointsBuilder()
        .withNewMetadata().withName("external-web").withNamespace(namespace).endMetadata()
        .withSubsets().addNewSubset().addNewAddress().withIp("10.10.50.53").endAddress()
        .addNewPort().withPort(80).withName("apache").endPort()
        .endSubset()
        .build();
      log("Endpoint created");
      client.endpoints().inNamespace(namespace).create(endpoints);
      log("Endpoint url");
      endpoints = client.endpoints().inNamespace(namespace).withName("external-web").get();
      log("Endpoint Port", endpoints.getSubsets().get(0).getPorts().get(0).getName());
    } finally {
      // clear resources
      client.apps().deployments().inNamespace("default").withName("endpoints-deployment").delete();
      client.services().inNamespace("default").withName("endpoints-nginx").delete();
      client.endpoints().inNamespace("default").withName("external-web").delete();
    }
  } catch (Exception e) {
    log("Exception occurred: ", e.getMessage());
    e.printStackTrace();
  }
}
 
Example #15
Source File: Readiness.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
public static boolean isReadinessApplicable(Class<? extends HasMetadata> itemClass) {
  return Deployment.class.isAssignableFrom(itemClass)
    || ReplicaSet.class.isAssignableFrom(itemClass)
    || Pod.class.isAssignableFrom(itemClass)
    || DeploymentConfig.class.isAssignableFrom(itemClass)
    || ReplicationController.class.isAssignableFrom(itemClass)
    || Endpoints.class.isAssignableFrom(itemClass)
    || Node.class.isAssignableFrom(itemClass)
    || StatefulSet.class.isAssignableFrom(itemClass)
    ;
}
 
Example #16
Source File: K8sEndpointsManager.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public void createEndpoints(Endpoints endpoints) {
    checkNotNull(endpoints, ERR_NULL_ENDPOINTS);
    checkArgument(!Strings.isNullOrEmpty(endpoints.getMetadata().getUid()),
            ERR_NULL_ENDPOINTS_UID);

    k8sEndpointsStore.createEndpoints(endpoints);

    log.info(String.format(MSG_ENDPOINTS, endpoints.getMetadata().getName(), MSG_CREATED));
}
 
Example #17
Source File: K8sEndpointsManager.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public void updateEndpoints(Endpoints endpoints) {
    checkNotNull(endpoints, ERR_NULL_ENDPOINTS);
    checkArgument(!Strings.isNullOrEmpty(endpoints.getMetadata().getUid()),
            ERR_NULL_ENDPOINTS_UID);

    k8sEndpointsStore.updateEndpoints(endpoints);

    log.debug(String.format(MSG_ENDPOINTS, endpoints.getMetadata().getName(), MSG_UPDATED));
}
 
Example #18
Source File: KubernetesCatalogWatch.java    From spring-cloud-kubernetes with Apache License 2.0 5 votes vote down vote up
@Scheduled(
		fixedDelayString = "${spring.cloud.kubernetes.discovery.catalogServicesWatchDelay:30000}")
public void catalogServicesWatch() {
	try {
		List<String> previousState = this.catalogEndpointsState.get();

		// not all pods participate in the service discovery. only those that have
		// endpoints.
		List<Endpoints> endpoints = this.properties.isAllNamespaces()
				? this.kubernetesClient.endpoints().inAnyNamespace().list().getItems()
				: this.kubernetesClient.endpoints().list().getItems();
		List<String> endpointsPodNames = endpoints.stream().map(Endpoints::getSubsets)
				.filter(Objects::nonNull).flatMap(Collection::stream)
				.map(EndpointSubset::getAddresses).filter(Objects::nonNull)
				.flatMap(Collection::stream).map(EndpointAddress::getTargetRef)
				.filter(Objects::nonNull).map(ObjectReference::getName) // pod name
																		// unique in
																		// namespace
				.sorted(String::compareTo).collect(Collectors.toList());

		this.catalogEndpointsState.set(endpointsPodNames);

		if (!endpointsPodNames.equals(previousState)) {
			logger.trace("Received endpoints update from kubernetesClient: {}",
					endpointsPodNames);
			this.publisher.publishEvent(new HeartbeatEvent(this, endpointsPodNames));
		}
	}
	catch (Exception e) {
		logger.error("Error watching Kubernetes Services", e);
	}
}
 
Example #19
Source File: K8sServiceHandler.java    From onos with Apache License 2.0 5 votes vote down vote up
private void setEndpointsRules(Endpoints endpoints, boolean install) {
    String appName = endpoints.getMetadata().getName();
    Service service = k8sServiceService.services().stream().filter(s ->
            appName.equals(s.getMetadata().getName()))
            .findFirst().orElse(null);

    if (service == null) {
        return;
    }

    setGroupBuckets(service, install);
}
 
Example #20
Source File: K8sServiceHandler.java    From onos with Apache License 2.0 5 votes vote down vote up
private void processEndpointsCreation(Endpoints endpoints) {
    if (!isRelevantHelper()) {
        return;
    }

    setEndpointsRules(endpoints, true);
}
 
Example #21
Source File: K8sServiceHandler.java    From onos with Apache License 2.0 5 votes vote down vote up
private void processEndpointsRemoval(Endpoints endpoints) {
    if (!isRelevantHelper()) {
        return;
    }

    setEndpointsRules(endpoints, false);
}
 
Example #22
Source File: DistributedK8sEndpointsStore.java    From onos with Apache License 2.0 5 votes vote down vote up
@Activate
protected void activate() {
    ApplicationId appId = coreService.registerApplication(APP_ID);
    endpointsStore = storageService.<String, Endpoints>consistentMapBuilder()
            .withSerializer(Serializer.using(SERIALIZER_K8S_ENDPOINTS))
            .withName("k8s-endpoints-store")
            .withApplicationId(appId)
            .build();

    endpointsStore.addListener(endpointsMapListener);
    log.info("Started");
}
 
Example #23
Source File: DistributedK8sEndpointsStore.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public void createEndpoints(Endpoints endpoints) {
    endpointsStore.compute(endpoints.getMetadata().getUid(), (uid, existing) -> {
        final String error = endpoints.getMetadata().getUid() + ERR_DUPLICATE;
        checkArgument(existing == null, error);
        return endpoints;
    });
}
 
Example #24
Source File: DistributedK8sEndpointsStore.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public void updateEndpoints(Endpoints endpoints) {
    endpointsStore.compute(endpoints.getMetadata().getUid(), (uid, existing) -> {
        final String error = endpoints.getMetadata().getUid() + ERR_NOT_FOUND;
        checkArgument(existing != null, error);
        return endpoints;
    });
}
 
Example #25
Source File: DistributedK8sEndpointsStore.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public Endpoints removeEndpoints(String uid) {
    Versioned<Endpoints> endpoints = endpointsStore.remove(uid);
    if (endpoints == null) {
        final String error = uid + ERR_NOT_FOUND;
        throw new IllegalArgumentException(error);
    }
    return endpoints.value();
}
 
Example #26
Source File: K8sEndpointsWatcher.java    From onos with Apache License 2.0 5 votes vote down vote up
private void processAddition(Endpoints endpoints) {
    if (!isMaster()) {
        return;
    }

    log.trace("Process endpoints {} creating event from API server.",
            endpoints.getMetadata().getName());

    if (k8sEndpointsAdminService.endpoints(
            endpoints.getMetadata().getUid()) == null) {
        k8sEndpointsAdminService.createEndpoints(endpoints);
    }
}
 
Example #27
Source File: K8sEndpointsWatcher.java    From onos with Apache License 2.0 5 votes vote down vote up
private void processModification(Endpoints endpoints) {
    if (!isMaster()) {
        return;
    }

    log.trace("Process endpoints {} updating event from API server.",
            endpoints.getMetadata().getName());

    if (k8sEndpointsAdminService.endpoints(
            endpoints.getMetadata().getUid()) != null) {
        k8sEndpointsAdminService.updateEndpoints(endpoints);
    }
}
 
Example #28
Source File: K8sEndpointsWatcher.java    From onos with Apache License 2.0 5 votes vote down vote up
private void processDeletion(Endpoints endpoints) {
    if (!isMaster()) {
        return;
    }

    log.trace("Process endpoints {} removal event from API server.",
            endpoints.getMetadata().getName());

    k8sEndpointsAdminService.removeEndpoints(endpoints.getMetadata().getUid());
}
 
Example #29
Source File: K8sEndpointsListCommand.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
protected void doExecute() {
    K8sEndpointsService service = get(K8sEndpointsService.class);
    List<Endpoints> endpointses = Lists.newArrayList(service.endpointses());
    endpointses.sort(Comparator.comparing(e -> e.getMetadata().getName()));

    String format = genFormatString(ImmutableList.of(CLI_NAME_LENGTH,
            CLI_IP_ADDRESSES_LENGTH, CLI_PORTS_LENGTH));

    if (outputJson()) {
        print("%s", json(endpointses));
    } else {
        print(format, "Name", "IP Addresses", "Ports");

        for (Endpoints endpoints : endpointses) {

            List<String> ips = Lists.newArrayList();
            List<String> portWithProtocol = Lists.newArrayList();

            endpoints.getSubsets().forEach(e -> {
                e.getAddresses().forEach(a -> ips.add(a.getIp()));
                e.getPorts().forEach(p -> portWithProtocol.add(p.getPort() +
                        PORT_PROTOCOL_SEPARATOR + p.getProtocol()));
            });

            print(format,
                    StringUtils.substring(endpoints.getMetadata().getName(),
                            0, CLI_NAME_LENGTH - CLI_MARGIN_LENGTH),
                    ips.isEmpty() ? "" : StringUtils.substring(ips.toString(),
                            0, CLI_IP_ADDRESSES_LENGTH - CLI_MARGIN_LENGTH),
                    portWithProtocol.isEmpty() ? "" : portWithProtocol);
        }
    }
}
 
Example #30
Source File: K8sEndpointsManagerTest.java    From onos with Apache License 2.0 5 votes vote down vote up
private static Endpoints createK8sEndpoints(String uid, String name) {
    ObjectMeta meta = new ObjectMeta();
    meta.setUid(uid);
    meta.setName(name);

    Endpoints endpoints = new Endpoints();
    endpoints.setApiVersion("v1");
    endpoints.setKind("endpoints");
    endpoints.setMetadata(meta);

    return endpoints;
}