Python kubernetes.client.V1ContainerPort() Examples

The following are 11 code examples of kubernetes.client.V1ContainerPort(). 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: translate_outputs.py    From tacker with Apache License 2.0 6 votes vote down vote up
def init_containers(self, container_props, limit_resource, name):
        list_env_var = self.init_envs(container_props, name)
        container_name = self.pre_process_name(container_props.name)
        list_container_port = list()
        if container_props.ports:
            for container_port in container_props.ports:
                port = int(container_port)
                cport = client.V1ContainerPort(container_port=port)
                list_container_port.append(cport)
        container = client.V1Container(
            name=container_name,
            image=container_props.image,
            ports=list_container_port,
            resources=limit_resource,
            command=container_props.command,
            args=container_props.args,
            env=list_env_var,
            image_pull_policy="IfNotPresent")
        return container

    # init_deployment initializes Kubernetes Pod object 
Example #2
Source File: ingress_create.py    From python with Apache License 2.0 5 votes vote down vote up
def create_deployment(apps_v1_api):
    container = client.V1Container(
        name="deployment",
        image="gcr.io/google-appengine/fluentd-logger",
        image_pull_policy="Never",
        ports=[client.V1ContainerPort(container_port=5678)],
    )
    # Template
    template = client.V1PodTemplateSpec(
        metadata=client.V1ObjectMeta(labels={"app": "deployment"}),
        spec=client.V1PodSpec(containers=[container]))
    # Spec
    spec = client.V1DeploymentSpec(
        replicas=1,
        template=template)
    # Deployment
    deployment = client.V1Deployment(
        api_version="apps/v1",
        kind="Deployment",
        metadata=client.V1ObjectMeta(name="deployment"),
        spec=spec)
    # Creation of the Deployment in specified namespace
    # (Can replace "default" with a namespace you may have created)
    apps_v1_api.create_namespaced_deployment(
        namespace="default", body=deployment
    ) 
Example #3
Source File: deployment_crud.py    From python with Apache License 2.0 5 votes vote down vote up
def create_deployment_object():
    # Configureate Pod template container
    container = client.V1Container(
        name="nginx",
        image="nginx:1.15.4",
        ports=[client.V1ContainerPort(container_port=80)],
        resources=client.V1ResourceRequirements(
            requests={"cpu": "100m", "memory": "200Mi"},
            limits={"cpu": "500m", "memory": "500Mi"}
        )
    )
    # Create and configurate a spec section
    template = client.V1PodTemplateSpec(
        metadata=client.V1ObjectMeta(labels={"app": "nginx"}),
        spec=client.V1PodSpec(containers=[container]))
    # Create the specification of deployment
    spec = client.V1DeploymentSpec(
        replicas=3,
        template=template,
        selector={'matchLabels': {'app': 'nginx'}})
    # Instantiate the deployment object
    deployment = client.V1Deployment(
        api_version="apps/v1",
        kind="Deployment",
        metadata=client.V1ObjectMeta(name=DEPLOYMENT_NAME),
        spec=spec)

    return deployment 
Example #4
Source File: kubernetes_tools.py    From paasta with Apache License 2.0 5 votes vote down vote up
def get_kubernetes_containers(
        self,
        docker_volumes: Sequence[DockerVolume],
        system_paasta_config: SystemPaastaConfig,
        aws_ebs_volumes: Sequence[AwsEbsVolume],
        service_namespace_config: ServiceNamespaceConfig,
    ) -> Sequence[V1Container]:
        service_container = V1Container(
            image=self.get_docker_url(),
            command=self.get_cmd(),
            args=self.get_args(),
            env=self.get_container_env(),
            resources=self.get_resource_requirements(),
            lifecycle=V1Lifecycle(
                pre_stop=V1Handler(
                    _exec=V1ExecAction(command=["/bin/sh", "-c", "sleep 30"])
                )
            ),
            name=self.get_sanitised_instance_name(),
            liveness_probe=self.get_liveness_probe(service_namespace_config),
            ports=[V1ContainerPort(container_port=self.get_container_port())],
            security_context=self.get_security_context(),
            volume_mounts=self.get_volume_mounts(
                docker_volumes=docker_volumes,
                aws_ebs_volumes=aws_ebs_volumes,
                persistent_volumes=self.get_persistent_volumes(),
            ),
        )
        containers = [service_container] + self.get_sidecar_containers(  # type: ignore
            system_paasta_config=system_paasta_config,
            service_namespace_config=service_namespace_config,
        )
        return containers 
Example #5
Source File: kfservingdeployer.py    From pipelines with Apache License 2.0 5 votes vote down vote up
def customEndpointSpec(custom_model_spec, service_account):
    env = (
        [
            client.V1EnvVar(name=i["name"], value=i["value"])
            for i in custom_model_spec["env"]
        ]
        if custom_model_spec.get("env", "")
        else None
    )
    ports = (
        [client.V1ContainerPort(container_port=int(custom_model_spec.get("port", "")))]
        if custom_model_spec.get("port", "")
        else None
    )
    containerSpec = client.V1Container(
        name=custom_model_spec.get("name", "custom-container"),
        image=custom_model_spec["image"],
        env=env,
        ports=ports,
        command=custom_model_spec.get("command", None),
        args=custom_model_spec.get("args", None),
        image_pull_policy=custom_model_spec.get("image_pull_policy", None),
        working_dir=custom_model_spec.get("working_dir", None),
    )
    return V1alpha2EndpointSpec(
        predictor=V1alpha2PredictorSpec(
            custom=V1alpha2CustomSpec(container=containerSpec),
            service_account_name=service_account,
        )
    ) 
Example #6
Source File: test_base.py    From node with Apache License 2.0 5 votes vote down vote up
def deploy(self, image, name, ns, port, replicas=1, svc_type="NodePort", traffic_policy="Local", cluster_ip=None, ipv6=False):
        """
        Creates a deployment and corresponding service with the given
        parameters.
        """
        # Run a deployment with <replicas> copies of <image>, with the
        # pods labelled with "app": <name>.
        deployment = client.V1Deployment(
            api_version="apps/v1",
            kind="Deployment",
            metadata=client.V1ObjectMeta(name=name),
            spec=client.V1DeploymentSpec(
                replicas=replicas,
                selector={'matchLabels': {'app': name}},
                template=client.V1PodTemplateSpec(
                    metadata=client.V1ObjectMeta(labels={"app": name}),
                    spec=client.V1PodSpec(containers=[
                        client.V1Container(name=name,
                                           image=image,
                                           ports=[client.V1ContainerPort(container_port=port)]),
                    ]))))
        api_response = client.AppsV1Api().create_namespaced_deployment(
            body=deployment,
            namespace=ns)
        logger.debug("Deployment created. status='%s'" % str(api_response.status))

        # Create a service called <name> whose endpoints are the pods
        # with "app": <name>; i.e. those just created above.
        self.create_service(name, name, ns, port, svc_type, traffic_policy, ipv6=ipv6) 
Example #7
Source File: conftest.py    From kubetest with GNU General Public License v3.0 5 votes vote down vote up
def simple_deployment():
    """Return the Kubernetes config matching the simple-deployment.yaml manifest."""
    return client.V1Deployment(
        api_version='apps/v1',
        kind='Deployment',
        metadata=client.V1ObjectMeta(
            name='nginx-deployment',
            labels={
                'app': 'nginx'
            }
        ),
        spec=client.V1DeploymentSpec(
            replicas=3,
            selector=client.V1LabelSelector(
                match_labels={
                    'app': 'nginx'
                }
            ),
            template=client.V1PodTemplateSpec(
                metadata=client.V1ObjectMeta(
                    labels={
                        'app': 'nginx'
                    }
                ),
                spec=client.V1PodSpec(
                    containers=[
                        client.V1Container(
                            name='nginx',
                            image='nginx:1.7.9',
                            ports=[
                                client.V1ContainerPort(
                                    container_port=80
                                )
                            ]
                        )
                    ]
                )
            )
        )
    ) 
Example #8
Source File: conftest.py    From kubetest with GNU General Public License v3.0 5 votes vote down vote up
def simple_statefulset():
    """Return the Kubernetes config matching the simple-statefulset.yaml manifest."""
    return client.V1StatefulSet(
        api_version='apps/v1',
        kind='StatefulSet',
        metadata=client.V1ObjectMeta(
            name='postgres-statefulset',
            labels={
                'app': 'postgres'
            }
        ),
        spec=client.V1StatefulSetSpec(
            replicas=3,
            selector=client.V1LabelSelector(
                match_labels={
                    'app': 'postgres'
                }
            ),
            service_name='simple-service',
            template=client.V1PodTemplateSpec(
                metadata=client.V1ObjectMeta(
                    labels={
                        'app': 'postgres'
                    }
                ),
                spec=client.V1PodSpec(
                    containers=[
                        client.V1Container(
                            name='postgres',
                            image='postgres:9.6',
                            ports=[
                                client.V1ContainerPort(
                                    container_port=5432
                                )
                            ]
                        )
                    ]
                )
            )
        )
    ) 
Example #9
Source File: conftest.py    From kubetest with GNU General Public License v3.0 5 votes vote down vote up
def simple_daemonset():
    """Return the Kubernetes config matching the simple-daemonset.yaml manifest."""
    return client.V1DaemonSet(
        api_version='apps/v1',
        kind='DaemonSet',
        metadata=client.V1ObjectMeta(
            name='canal-daemonset',
            labels={
                'app': 'canal'
            }
        ),
        spec=client.V1DaemonSetSpec(
            selector=client.V1LabelSelector(
                match_labels={
                    'app': 'canal'
                }
            ),
            template=client.V1PodTemplateSpec(
                metadata=client.V1ObjectMeta(
                    labels={
                        'app': 'canal'
                    }
                ),
                spec=client.V1PodSpec(
                    containers=[
                        client.V1Container(
                            name='canal',
                            image='canal:3.7.2',
                            ports=[
                                client.V1ContainerPort(
                                    container_port=9099
                                )
                            ]
                        )
                    ]
                )
            )
        )
    ) 
Example #10
Source File: kubernetes_tools.py    From paasta with Apache License 2.0 4 votes vote down vote up
def get_sidecar_containers(
        self,
        system_paasta_config: SystemPaastaConfig,
        service_namespace_config: ServiceNamespaceConfig,
    ) -> Sequence[V1Container]:
        registrations = " ".join(self.get_registrations())
        # s_m_j currently asserts that services are healthy in smartstack before
        # continuing a bounce. this readiness check lets us achieve the same thing
        readiness_probe: Optional[V1Probe]
        if (
            self.get_enable_nerve_readiness_check()
            and service_namespace_config.is_in_smartstack()
        ):
            readiness_probe = V1Probe(
                _exec=V1ExecAction(
                    command=[
                        system_paasta_config.get_nerve_readiness_check_script(),
                        str(self.get_container_port()),
                    ]
                    + self.get_registrations()
                ),
                initial_delay_seconds=10,
                period_seconds=10,
            )
        else:
            readiness_probe = None

        sidecars = []
        if service_namespace_config.is_in_smartstack():
            sidecars.append(
                V1Container(
                    image=system_paasta_config.get_hacheck_sidecar_image_url(),
                    lifecycle=V1Lifecycle(
                        pre_stop=V1Handler(
                            _exec=V1ExecAction(
                                command=[
                                    "/bin/sh",
                                    "-c",
                                    f"/usr/bin/hadown {registrations}; sleep 31",
                                ]
                            )
                        )
                    ),
                    resources=self.get_sidecar_resource_requirements(),
                    name=HACHECK_POD_NAME,
                    env=self.get_kubernetes_environment(),
                    ports=[V1ContainerPort(container_port=6666)],
                    readiness_probe=readiness_probe,
                )
            )
        return sidecars 
Example #11
Source File: pod.py    From conu with GNU General Public License v3.0 4 votes vote down vote up
def create(image_data):
        """
        :param image_data: ImageMetadata
        :return: V1Pod,
            https://github.com/kubernetes-client/python/blob/master/kubernetes/docs/V1Pod.md
        """

        # convert environment variables to Kubernetes objects
        env_variables = []
        for key, value in image_data.env_variables.items():
            env_variables.append(client.V1EnvVar(name=key, value=value))

        # convert exposed ports to Kubernetes objects
        exposed_ports = []
        if image_data.exposed_ports is not None:
            for port in image_data.exposed_ports:
                splits = port.split("/", 1)
                port = int(splits[0])
                protocol = splits[1].upper() if len(splits) > 1 else None
                exposed_ports.append(client.V1ContainerPort(container_port=port, protocol=protocol))

        # generate container name {image-name}-{username}-{random-4-letters}
        # take just name of image and remove tag
        image_name = image_data.name.split("/")[-1].split(":")[0]
        random_string = ''.join(
            random.choice(string.ascii_lowercase + string.digits) for _ in range(4))
        container_name = '{image_name}-{user_name}-{random_string}'.format(
            image_name=image_name,
            user_name=getpass.getuser(),
            random_string=random_string)

        container = client.V1Container(command=image_data.command,
                                       env=env_variables,
                                       image=image_data.name,
                                       name=container_name,
                                       ports=exposed_ports)

        pod_metadata = client.V1ObjectMeta(name=container_name + "-pod")
        pod_spec = client.V1PodSpec(containers=[container])
        pod = client.V1Pod(spec=pod_spec, metadata=pod_metadata)

        return pod