Ejemplo n.º 1
0
def main():
    # Creating a dynamic client
    client = dynamic.DynamicClient(
        api_client.ApiClient(configuration=config.load_kube_config())
    )

    # fetching the configmap api
    api = client.resources.get(api_version="v1", kind="ConfigMap")

    configmap_name = "test-configmap"

    configmap_manifest = {
        "kind": "ConfigMap",
        "apiVersion": "v1",
        "metadata": {
            "name": configmap_name,
            "labels": {
                "foo": "bar",
            },
        },
        "data": {
            "config.json": '{"command":"/usr/bin/mysqld_safe"}',
            "frontend.cnf": "[mysqld]\nbind-address = 10.0.0.3\n",
        },
    }

    # Creating configmap `test-configmap` in the `default` namespace

    configmap = api.create(body=configmap_manifest, namespace="default")

    print("\n[INFO] configmap `test-configmap` created\n")

    # Listing the configmaps in the `default` namespace

    configmap_list = api.get(
        name=configmap_name, namespace="default", label_selector="foo=bar"
    )

    print("NAME:\n%s\n" % (configmap_list.metadata.name))
    print("DATA:\n%s\n" % (configmap_list.data))

    # Updating the configmap's data, `config.json`

    configmap_manifest["data"]["config.json"] = "{}"

    configmap_patched = api.patch(
        name=configmap_name, namespace="default", body=configmap_manifest
    )

    print("\n[INFO] configmap `test-configmap` patched\n")
    print("NAME:\n%s\n" % (configmap_patched.metadata.name))
    print("DATA:\n%s\n" % (configmap_patched.data))

    # Deleting configmap `test-configmap` from the `default` namespace

    configmap_deleted = api.delete(name=configmap_name, body={}, namespace="default")
    print("\n[INFO] configmap `test-configmap` deleted\n")
Ejemplo n.º 2
0
def handler(event: Dict[str, Any], context: Optional[Dict[str, Any]]) -> Any:
    create_kubeconfig()

    api_CoreV1 = client.CoreV1Api()
    userspace_dc = dynamic.DynamicClient(client=api_client.ApiClient()).resources.get(
        group=ORBIT_API_GROUP, api_version=ORBIT_API_VERSION, kind=USERSPACE_CR_KIND
    )

    manage_user_namespace(event, api_CoreV1, userspace_dc)
Ejemplo n.º 3
0
def get_api(api_name):
    client = dynamic.DynamicClient(
        api_client.ApiClient(configuration=config.load_kube_config()))

    _apis = {
        "msp": (lambda: client.resources.get(api_version="openebs.io/v1alpha1",
                                             kind="MayastorPool")),
        "msv": (lambda: client.resources.get(api_version="openebs.io/v1alpha1",
                                             kind="MayastorVolume")),
        "pvc": (lambda: client.resources.get(api_version="v1",
                                             kind="PersistentVolumeClaim")),
        "pod": (lambda: client.resources.get(api_version="v1", kind="Pod")),
    }

    return _apis[api_name]()
Ejemplo n.º 4
0
def main():
    # Creating a dynamic client
    client = dynamic.DynamicClient(
        api_client.ApiClient(configuration=config.load_kube_config()))

    # fetching the node api
    api = client.resources.get(api_version="v1", kind="Node")

    # Listing cluster nodes

    print("%s\t\t%s\t\t%s" % ("NAME", "STATUS", "VERSION"))
    for item in api.get().items:
        node = api.get(name=item.metadata.name)
        print("%s\t%s\t\t%s\n" % (
            node.metadata.name,
            node.status.conditions[3]["type"],
            node.status.nodeInfo.kubeProxyVersion,
        ))
Ejemplo n.º 5
0
def main():
    # Creating a dynamic client
    client = dynamic.DynamicClient(
        api_client.ApiClient(configuration=config.load_kube_config()))

    # fetching the node api
    api = client.resources.get(api_version="v1", kind="Node")

    # Creating a custom header
    params = {
        'header_params': {
            'Accept':
            'application/json;as=PartialObjectMetadataList;v=v1;g=meta.k8s.io'
        }
    }

    resp = api.get(**params)

    # Printing the kind and apiVersion after passing new header params.
    print("%s\t\t\t%s" % ("VERSION", "KIND"))
    print("%s\t\t%s" % (resp.apiVersion, resp.kind))
Ejemplo n.º 6
0
def _dynamic_client() -> dynamic.DynamicClient:
    load_kube_config()
    return dynamic.DynamicClient(client=api_client.ApiClient())
def main():
    # Creating a dynamic client
    client = dynamic.DynamicClient(
        api_client.ApiClient(configuration=config.load_kube_config()))

    # fetching the deployment api
    api = client.resources.get(api_version="apps/v1", kind="Deployment")

    name = "nginx-deployment"

    deployment_manifest = {
        "apiVersion": "apps/v1",
        "kind": "Deployment",
        "metadata": {
            "labels": {
                "app": "nginx"
            },
            "name": name
        },
        "spec": {
            "replicas": 3,
            "selector": {
                "matchLabels": {
                    "app": "nginx"
                }
            },
            "template": {
                "metadata": {
                    "labels": {
                        "app": "nginx"
                    }
                },
                "spec": {
                    "containers": [{
                        "name": "nginx",
                        "image": "nginx:1.14.2",
                        "ports": [{
                            "containerPort": 80
                        }],
                    }]
                },
            },
        },
    }

    # Creating deployment `nginx-deployment` in the `default` namespace

    deployment = api.create(body=deployment_manifest, namespace="default")

    print("\n[INFO] deployment `nginx-deployment` created\n")

    # Listing deployment `nginx-deployment` in the `default` namespace

    deployment_created = api.get(name=name, namespace="default")

    print("%s\t%s\t\t\t%s\t%s" %
          ("NAMESPACE", "NAME", "REVISION", "RESTARTED-AT"))
    print("%s\t\t%s\t%s\t\t%s\n" % (
        deployment_created.metadata.namespace,
        deployment_created.metadata.name,
        deployment_created.metadata.annotations,
        deployment_created.spec.template.metadata.annotations,
    ))

    # Patching the `spec.template.metadata` section to add `kubectl.kubernetes.io/restartedAt` annotation
    # In order to perform a rolling restart on the deployment `nginx-deployment`

    deployment_manifest["spec"]["template"]["metadata"] = {
        "annotations": {
            "kubectl.kubernetes.io/restartedAt":
            datetime.datetime.utcnow().replace(tzinfo=pytz.UTC).isoformat()
        }
    }

    deployment_patched = api.patch(body=deployment_manifest,
                                   name=name,
                                   namespace="default")

    print("\n[INFO] deployment `nginx-deployment` restarted\n")
    print("%s\t%s\t\t\t%s\t\t\t\t\t\t%s" %
          ("NAMESPACE", "NAME", "REVISION", "RESTARTED-AT"))
    print("%s\t\t%s\t%s\t\t%s\n" % (
        deployment_patched.metadata.namespace,
        deployment_patched.metadata.name,
        deployment_patched.metadata.annotations,
        deployment_patched.spec.template.metadata.annotations,
    ))

    # Deleting deployment `nginx-deployment` from the `default` namespace

    deployment_deleted = api.delete(name=name, body={}, namespace="default")

    print("\n[INFO] deployment `nginx-deployment` deleted\n")
Ejemplo n.º 8
0
def main():
    # Creating a dynamic client
    client = dynamic.DynamicClient(
        api_client.ApiClient(configuration=config.load_kube_config()))

    # fetching the custom resource definition (CRD) api
    crd_api = client.resources.get(api_version="apiextensions.k8s.io/v1",
                                   kind="CustomResourceDefinition")

    # Creating a Namespaced CRD named "ingressroutes.apps.example.com"
    name = "ingressroutes.apps.example.com"

    crd_manifest = {
        "apiVersion": "apiextensions.k8s.io/v1",
        "kind": "CustomResourceDefinition",
        "metadata": {
            "name": name,
            "namespace": "default"
        },
        "spec": {
            "group":
            "apps.example.com",
            "versions": [{
                "name": "v1",
                "schema": {
                    "openAPIV3Schema": {
                        "properties": {
                            "spec": {
                                "properties": {
                                    "strategy": {
                                        "type": "string"
                                    },
                                    "virtualhost": {
                                        "properties": {
                                            "fqdn": {
                                                "type": "string"
                                            },
                                            "tls": {
                                                "properties": {
                                                    "secretName": {
                                                        "type": "string"
                                                    }
                                                },
                                                "type": "object",
                                            },
                                        },
                                        "type": "object",
                                    },
                                },
                                "type": "object",
                            }
                        },
                        "type": "object",
                    }
                },
                "served": True,
                "storage": True,
            }],
            "scope":
            "Namespaced",
            "names": {
                "plural": "ingressroutes",
                "listKind": "IngressRouteList",
                "singular": "ingressroute",
                "kind": "IngressRoute",
                "shortNames": ["ir"],
            },
        },
    }

    crd_creation_respone = crd_api.create(crd_manifest)
    print(
        "\n[INFO] custom resource definition `ingressroutes.apps.example.com` created\n"
    )
    print("%s\t\t%s" % ("SCOPE", "NAME"))
    print(
        "%s\t%s\n" %
        (crd_creation_respone.spec.scope, crd_creation_respone.metadata.name))

    # Fetching the "ingressroutes" CRD api

    try:
        ingressroute_api = client.resources.get(
            api_version="apps.example.com/v1", kind="IngressRoute")
    except ResourceNotFoundError:
        # Need to wait a sec for the discovery layer to get updated
        time.sleep(2)

    ingressroute_api = client.resources.get(api_version="apps.example.com/v1",
                                            kind="IngressRoute")

    # Creating a custom resource (CR) `ingress-route-*`, using the above CRD `ingressroutes.apps.example.com`

    ingressroute_manifest_first = {
        "apiVersion": "apps.example.com/v1",
        "kind": "IngressRoute",
        "metadata": {
            "name": "ingress-route-first",
            "namespace": "default",
        },
        "spec": {
            "virtualhost": {
                "fqdn": "www.google.com",
                "tls": {
                    "secretName": "google-tls"
                },
            },
            "strategy": "RoundRobin",
        },
    }

    ingressroute_manifest_second = {
        "apiVersion": "apps.example.com/v1",
        "kind": "IngressRoute",
        "metadata": {
            "name": "ingress-route-second",
            "namespace": "default",
        },
        "spec": {
            "virtualhost": {
                "fqdn": "www.yahoo.com",
                "tls": {
                    "secretName": "yahoo-tls"
                },
            },
            "strategy": "RoundRobin",
        },
    }

    ingressroute_api.create(body=ingressroute_manifest_first,
                            namespace="default")
    ingressroute_api.create(body=ingressroute_manifest_second,
                            namespace="default")
    print("\n[INFO] custom resources `ingress-route-*` created\n")

    # Listing the `ingress-route-*` custom resources

    ingress_routes_list = ingressroute_api.get()
    print("%s\t\t\t%s\t%s\t\t%s\t\t\t\t%s" %
          ("NAME", "NAMESPACE", "FQDN", "TLS", "STRATEGY"))
    for item in ingress_routes_list.items:
        print("%s\t%s\t\t%s\t%s\t%s" % (
            item.metadata.name,
            item.metadata.namespace,
            item.spec.virtualhost.fqdn,
            item.spec.virtualhost.tls,
            item.spec.strategy,
        ))

    # Patching the ingressroutes custom resources

    ingressroute_manifest_first["spec"]["strategy"] = "Random"
    ingressroute_manifest_second["spec"]["strategy"] = "WeightedLeastRequest"

    patch_ingressroute_first = ingressroute_api.patch(
        body=ingressroute_manifest_first,
        content_type="application/merge-patch+json")
    patch_ingressroute_second = ingressroute_api.patch(
        body=ingressroute_manifest_second,
        content_type="application/merge-patch+json")

    print(
        "\n[INFO] custom resources `ingress-route-*` patched to update the strategy\n"
    )
    ingress_routes_list = ingressroute_api.get()
    print("%s\t\t\t%s\t%s\t\t%s\t\t\t\t%s" %
          ("NAME", "NAMESPACE", "FQDN", "TLS", "STRATEGY"))
    for item in ingress_routes_list.items:
        print("%s\t%s\t\t%s\t%s\t%s" % (
            item.metadata.name,
            item.metadata.namespace,
            item.spec.virtualhost.fqdn,
            item.spec.virtualhost.tls,
            item.spec.strategy,
        ))

    # Deleting the ingressroutes custom resources

    delete_ingressroute_first = ingressroute_api.delete(
        name="ingress-route-first", namespace="default")
    delete_ingressroute_second = ingressroute_api.delete(
        name="ingress-route-second", namespace="default")

    print("\n[INFO] custom resources `ingress-route-*` deleted")

    # Deleting the ingressroutes.apps.example.com custom resource definition

    crd_api.delete(name=name)
    print(
        "\n[INFO] custom resource definition `ingressroutes.apps.example.com` deleted"
    )
    pod_list = api.get(namespace="open-cluster-management-addon-observability")

    return len(pod_list.items) != 0


if __name__ == '__main__':
    opts = option.NewOption()
    format = "%(asctime)s: %(message)s"
    logging.basicConfig(filename=opts.log_file,
                        filemode='w',
                        format=format,
                        level=logging.INFO,
                        datefmt="%H:%M:%S")

    hubClient = dynamic.DynamicClient(
        api_client.ApiClient(configuration=config.load_kube_config(
            config_file=opts.hub_config)))

    if opts.clean:
        err = removeSimulators(hubClient, opts.prefix)
        if err != None:
            logging.error("failed to clean up the simulators, err %s", err)
            exit(1)
        exit(0)

    if not isObservabilityAddonEnabled(hubClient):
        logging.error(
            "Observability Addon is not up, won't be get Obs cert template")
        exit(1)

    # watch the managedcluster CR and create observability simlutor in the managed
Ejemplo n.º 10
0
def main():
    # Creating a dynamic client
    client = dynamic.DynamicClient(
        api_client.ApiClient(configuration=config.load_kube_config()))

    # fetching the replication controller api
    api = client.resources.get(api_version="v1", kind="ReplicationController")

    name = "frontend-replication-controller"

    replication_controller_manifest = {
        "apiVersion": "v1",
        "kind": "ReplicationController",
        "metadata": {
            "labels": {
                "name": name
            },
            "name": name
        },
        "spec": {
            "replicas": 2,
            "selector": {
                "name": name
            },
            "template": {
                "metadata": {
                    "labels": {
                        "name": name
                    }
                },
                "spec": {
                    "containers": [{
                        "image":
                        "nginx",
                        "name":
                        "nginx",
                        "ports": [{
                            "containerPort": 80,
                            "protocol": "TCP"
                        }],
                    }]
                },
            },
        },
    }

    # Creating replication-controller `frontend-replication-controller` in the `default` namespace
    replication_controller = api.create(body=replication_controller_manifest,
                                        namespace="default")

    print(
        "\n[INFO] replication-controller `frontend-replication-controller` created\n"
    )

    # Listing replication-controllers in the `default` namespace
    replication_controller_created = api.get(name=name, namespace="default")

    print("%s\t%s\t\t\t\t\t%s" % ("NAMESPACE", "NAME", "REPLICAS"))
    print("%s\t\t%s\t\t%s\n" % (
        replication_controller_created.metadata.namespace,
        replication_controller_created.metadata.name,
        replication_controller_created.spec.replicas,
    ))

    # Deleting replication-controller `frontend-service` from the `default` namespace

    replication_controller_deleted = api.delete(name=name,
                                                body={},
                                                namespace="default")

    print(
        "[INFO] replication-controller `frontend-replication-controller` deleted\n"
    )
def _dynamic_client() -> dynamic.DynamicClient:
    return dynamic.DynamicClient(client=api_client.ApiClient())
Ejemplo n.º 12
0
def main():
    # Creating a dynamic client
    client = dynamic.DynamicClient(
        api_client.ApiClient(configuration=config.load_kube_config()))

    # fetching the service api
    api = client.resources.get(api_version="v1", kind="Service")

    name = "frontend-service"

    service_manifest = {
        "apiVersion": "v1",
        "kind": "Service",
        "metadata": {
            "labels": {
                "name": name
            },
            "name": name,
            "resourceversion": "v1"
        },
        "spec": {
            "ports": [{
                "name": "port",
                "port": 80,
                "protocol": "TCP",
                "targetPort": 80
            }],
            "selector": {
                "name": name
            },
        },
    }

    # Creating service `frontend-service` in the `default` namespace

    service = api.create(body=service_manifest, namespace="default")

    print("\n[INFO] service `frontend-service` created\n")

    # Listing service `frontend-service` in the `default` namespace
    service_created = api.get(name=name, namespace="default")

    print("%s\t%s" % ("NAMESPACE", "NAME"))
    print("%s\t\t%s\n" %
          (service_created.metadata.namespace, service_created.metadata.name))

    # Patching the `spec` section of the `frontend-service`

    service_manifest["spec"]["ports"] = [{
        "name": "new",
        "port": 8080,
        "protocol": "TCP",
        "targetPort": 8080
    }]

    service_patched = api.patch(body=service_manifest,
                                name=name,
                                namespace="default")

    print("\n[INFO] service `frontend-service` patched\n")
    print("%s\t%s\t\t\t%s" % ("NAMESPACE", "NAME", "PORTS"))
    print("%s\t\t%s\t%s\n" % (
        service_patched.metadata.namespace,
        service_patched.metadata.name,
        service_patched.spec.ports,
    ))

    # Deleting service `frontend-service` from the `default` namespace
    service_deleted = api.delete(name=name, body={}, namespace="default")

    print("\n[INFO] service `frontend-service` deleted\n")
Ejemplo n.º 13
0
 def __init__(self, conf=None):
     self.clientCoreV1 = client.CoreV1Api(conf)
     self.clientDyn = dynamic.DynamicClient(
         api_client.ApiClient(configuration=conf))
     self.clientApps = client.AppsV1Api(conf)
     self.clientsAppsV1 = client.AppsV1beta1Api(conf)