Python kubernetes.client.V1Service() Examples

The following are 18 code examples of kubernetes.client.V1Service(). 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 also want to check out all available functions/classes of the module kubernetes.client , or try the search function .
Example #1
Source File: ingress_create.py    From python with Apache License 2.0 6 votes vote down vote up
def create_service():
    core_v1_api = client.CoreV1Api()
    body = client.V1Service(
        api_version="v1",
        kind="Service",
        metadata=client.V1ObjectMeta(
            name="service-example"
        ),
        spec=client.V1ServiceSpec(
            selector={"app": "deployment"},
            ports=[client.V1ServicePort(
                port=5678,
                target_port=5678
            )]
        )
    )
    # Creation of the Deployment in specified namespace
    # (Can replace "default" with a namespace you may have created)
    core_v1_api.create_namespaced_service(namespace="default", body=body) 
Example #2
Source File: conftest.py    From kubetest with GNU General Public License v3.0 6 votes vote down vote up
def simple_service():
    """Return the Kubernetes config matching the simple-service.yaml manifest."""
    return client.V1Service(
        api_version='v1',
        kind='Service',
        metadata=client.V1ObjectMeta(
            name='my-service'
        ),
        spec=client.V1ServiceSpec(
            selector={
                'app': 'MyApp'
            },
            ports=[
                client.V1ServicePort(
                    protocol='TCP',
                    port=80,
                    target_port=9376
                )
            ]
        )
    ) 
Example #3
Source File: test_base.py    From node with Apache License 2.0 6 votes vote down vote up
def create_service(self, name, app, ns, port, svc_type="NodePort", traffic_policy="Local", cluster_ip=None, ipv6=False):
        service = client.V1Service(
            metadata=client.V1ObjectMeta(
                name=name,
                labels={"name": name},
            ),
            spec={
                "ports": [{"port": port}],
                "selector": {"app": app},
                "type": svc_type,
                "externalTrafficPolicy": traffic_policy,
            }
        )
        if cluster_ip:
          service.spec["clusterIP"] = cluster_ip
        if ipv6:
          service.spec["ipFamily"] = "IPv6"

        api_response = self.cluster.create_namespaced_service(
            body=service,
            namespace=ns,
        )
        logger.debug("Additional Service created. status='%s'" % str(api_response.status)) 
Example #4
Source File: KubernetesService.py    From k8s-mongo-operator with GNU Affero General Public License v3.0 5 votes vote down vote up
def createService(self, cluster_object: V1MongoClusterConfiguration) -> Optional[client.V1Service]:
        """
        Creates the given cluster.
        :param cluster_object: The cluster object from the YAML file.
        :return: The created service.
        """
        namespace = cluster_object.metadata.namespace
        body = KubernetesResources.createService(cluster_object)
        logging.info("Creating service %s @ ns/%s.", body.metadata.name, namespace)
        with IgnoreIfExists():
            return self.core_api.create_namespaced_service(namespace, body) 
Example #5
Source File: service.py    From conu with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, name, ports, namespace='default', labels=None, selector=None,
                 create_in_cluster=False, spec=None):
        """
        Utility functions for kubernetes services.

        :param name: str, name of the service
        :param namespace: str, name of the namespace
        :param ports: list of str, list of exposed ports, example:
                - ['1234/tcp', '8080/udp']
        :param labels: dict, dict of labels
        :param selector: dict, route service traffic to pods with label keys and
            values matching this selector
        """
        self.name = name
        self.namespace = namespace
        self.ports = ports

        exposed_ports = metadata_ports_to_k8s_ports(self.ports)

        self.metadata = client.V1ObjectMeta(name=self.name, namespace=self.namespace, labels=labels)
        self.spec = spec or client.V1ServiceSpec(ports=exposed_ports, selector=selector)

        self.body = client.V1Service(spec=self.spec, metadata=self.metadata)

        self.api = get_core_api()

        if create_in_cluster:
            self.create_in_cluster() 
Example #6
Source File: kubernetes.py    From patroni with MIT License 5 votes vote down vote up
def _create_config_service(self):
        metadata = k8s_client.V1ObjectMeta(namespace=self._namespace, name=self.config_path, labels=self._labels)
        body = k8s_client.V1Service(metadata=metadata, spec=k8s_client.V1ServiceSpec(cluster_ip='None'))
        try:
            if not self._api.create_namespaced_service(self._namespace, body):
                return
        except Exception as e:
            if not isinstance(e, k8s_client.rest.ApiException) or e.status != 409:  # Service already exists
                return logger.exception('create_config_service failed')
        self._should_create_config_service = False 
Example #7
Source File: test_manifest.py    From kubetest with GNU General Public License v3.0 5 votes vote down vote up
def test_ok_multi(self, manifest_dir):
        """Load manifest file with multiple object definitions."""

        objs = manifest.load_file(
            os.path.join(manifest_dir, 'multi-obj-manifest.yaml')
        )

        assert len(objs) == 3
        assert isinstance(objs[0], client.models.v1_service.V1Service)
        assert isinstance(objs[1], client.models.v1_service.V1Service)
        assert isinstance(objs[2], client.models.v1_deployment.V1Deployment) 
Example #8
Source File: test_manifest.py    From kubetest with GNU General Public License v3.0 5 votes vote down vote up
def test_simple_service_ok(self, manifest_dir, simple_service):
        """Test loading the simple service successfully."""
        obj = manifest.load_type(
            client.V1Service,
            os.path.join(manifest_dir, 'simple-service.yaml')
        )
        assert obj == simple_service 
Example #9
Source File: KubernetesService.py    From k8s-mongo-operator with GNU Affero General Public License v3.0 5 votes vote down vote up
def updateService(self, cluster_object: V1MongoClusterConfiguration) -> client.V1Service:
        """
        Updates the given cluster.
        :param cluster_object: The cluster object from the YAML file.
        :return: The updated service.
        """
        name = cluster_object.metadata.name
        namespace = cluster_object.metadata.namespace
        body = KubernetesResources.createService(cluster_object)
        logging.info("Updating service %s @ ns/%s.", name, namespace)
        return self.core_api.patch_namespaced_service(name, namespace, body) 
Example #10
Source File: kubernetes.py    From training_results_v0.6 with Apache License 2.0 5 votes vote down vote up
def create_svc_manifest(name, port, target_port):
    spec = client.V1ServiceSpec(
            selector={"app": name},
            ports=[client.V1ServicePort(protocol="TCP", port=port, target_port=target_port)]
            )
    service = client.V1Service( metadata=client.V1ObjectMeta(name=name), spec=spec)
    return service 
Example #11
Source File: ServiceChecker.py    From k8s-mongo-operator with GNU Affero General Public License v3.0 5 votes vote down vote up
def updateResource(self, cluster_object: V1MongoClusterConfiguration) -> V1Service:
        return self.kubernetes_service.updateService(cluster_object) 
Example #12
Source File: ServiceChecker.py    From k8s-mongo-operator with GNU Affero General Public License v3.0 5 votes vote down vote up
def createResource(self, cluster_object: V1MongoClusterConfiguration) -> V1Service:
        return self.kubernetes_service.createService(cluster_object) 
Example #13
Source File: ServiceChecker.py    From k8s-mongo-operator with GNU Affero General Public License v3.0 5 votes vote down vote up
def getResource(self, cluster_object: V1MongoClusterConfiguration) -> V1Service:
        return self.kubernetes_service.getService(cluster_object.metadata.name, cluster_object.metadata.namespace) 
Example #14
Source File: ServiceChecker.py    From k8s-mongo-operator with GNU Affero General Public License v3.0 5 votes vote down vote up
def listResources(self) -> List[V1Service]:
        return self.kubernetes_service.listAllServicesWithLabels().items 
Example #15
Source File: KubernetesResources.py    From k8s-mongo-operator with GNU Affero General Public License v3.0 5 votes vote down vote up
def createService(cls, cluster_object: V1MongoClusterConfiguration) -> client.V1Service:
        """
        Creates a service model object.
        :param cluster_object: The cluster object from the YAML file.
        :return: The service object.
        """
        # Parse cluster data object.
        name = cluster_object.metadata.name

        # Create service.
        return client.V1Service(
            metadata=client.V1ObjectMeta(
                name=name,
                namespace=cluster_object.metadata.namespace,
                labels=cls.createDefaultLabels(name),
            ),
            spec=client.V1ServiceSpec(
                cluster_ip="None",  # create headless service, no load-balancing and a single service IP
                selector=cls.createDefaultLabels(name),
                ports=[client.V1ServicePort(
                    name="mongod",
                    port=cls.MONGO_PORT,
                    protocol="TCP"
                )],
            ),
        ) 
Example #16
Source File: k8s_resource.py    From sparrow with GNU General Public License v3.0 5 votes vote down vote up
def export_service(self,node_port):
        ports = [client.V1ServicePort(port=int(port), target_port=int(port)) for port in self.container_port]
        spec = client.V1ServiceSpec(ports=ports, selector={'project': self.dm_name},type='ClusterIP')
        if node_port:
            ports = [client.V1ServicePort(port=int(self.container_port[0]), target_port=int(self.container_port[0]),node_port=int(node_port))]
            spec = client.V1ServiceSpec(ports=ports,selector={'project':self.dm_name},type='NodePort')
        service = client.V1Service(
            api_version = 'v1',
            kind = 'Service',
            metadata=client.V1ObjectMeta(name=self.dm_name),
            spec=spec)
        return service 
Example #17
Source File: kubernetes.py    From training_results_v0.6 with Apache License 2.0 5 votes vote down vote up
def create_svc_manifest(name, port, target_port):
    spec = client.V1ServiceSpec(
            selector={"app": name},
            ports=[client.V1ServicePort(protocol="TCP", port=port, target_port=target_port)]
            )
    service = client.V1Service( metadata=client.V1ObjectMeta(name=name), spec=spec)
    return service 
Example #18
Source File: translate_outputs.py    From tacker with Apache License 2.0 4 votes vote down vote up
def init_service(self, tosca_kube_obj, kube_obj_name):
        list_service_port = list()
        service_label = tosca_kube_obj.labels
        for port in tosca_kube_obj.mapping_ports:
            if COLON_CHARACTER in port:
                ports = port.split(COLON_CHARACTER)
                published_port = int(ports[0])
                target_port = int(ports[1])
            else:
                target_port = published_port = int(port)
            service_port = client.V1ServicePort(
                name=str(published_port),
                port=published_port,
                target_port=target_port)
            list_service_port.append(service_port)

        deployment_name = kube_obj_name
        selector_by_name = self.config_labels(deployment_name)
        if tosca_kube_obj.labels:
            selectors = tosca_kube_obj.labels.copy()
        else:
            selectors = selector_by_name
        if tosca_kube_obj.mgmt_connection_point:
            service_label['management_connection'] = 'True'
        if tosca_kube_obj.network_name:
            service_label['network_name'] = tosca_kube_obj.network_name
        service_label['vdu_name'] = tosca_kube_obj.name

        metadata = client.V1ObjectMeta(name=deployment_name,
                                       labels=service_label)
        if tosca_kube_obj.service_type:
            service_type = tosca_kube_obj.service_type
        else:
            service_type = None
        service_spec = client.V1ServiceSpec(
            selector=selectors,
            ports=list_service_port,
            type=service_type)

        service = client.V1Service(
            api_version="v1",
            kind="Service",
            spec=service_spec,
            metadata=metadata)
        return service

    # init_config_map initializes Kubernetes ConfigMap object