From 272076bcc6448bad3080c51e557e012fb6b86054 Mon Sep 17 00:00:00 2001 From: Tomasz Prus Date: Sat, 2 Mar 2024 00:05:57 +0100 Subject: [PATCH] Rename example scripts, reformat with Black (#304) --- examples/create_deployment_from_yaml.py | 5 +- examples/dynamic-client/accept_header.py | 6 +- .../cluster_scoped_custom_resource.py | 30 ++++++--- .../deployment_rolling_restart.py | 12 ++-- .../namespaced_custom_resource.py | 22 ++++-- .../dynamic-client/replication_controller.py | 12 ++-- examples/dynamic-client/request_timeout.py | 5 +- examples/dynamic-client/service.py | 10 ++- examples/in_cluster_config.py | 2 +- examples/{example1.py => list_pods.py} | 2 +- examples/{example3.py => pod_exec.py} | 30 +++++---- examples/tail.py | 67 +++++++++++-------- examples/{example2.py => watch_namespaces.py} | 4 +- examples/{example4.py => watch_ns_pods.py} | 13 ++-- test-requirements.txt | 1 + 15 files changed, 142 insertions(+), 79 deletions(-) rename examples/{example1.py => list_pods.py} (96%) rename examples/{example3.py => pod_exec.py} (59%) rename examples/{example2.py => watch_namespaces.py} (87%) rename examples/{example4.py => watch_ns_pods.py} (77%) diff --git a/examples/create_deployment_from_yaml.py b/examples/create_deployment_from_yaml.py index 94246b637..11ed01d7e 100644 --- a/examples/create_deployment_from_yaml.py +++ b/examples/create_deployment_from_yaml.py @@ -25,12 +25,11 @@ async def main(): k8s_client = client.ApiClient() await utils.create_from_yaml(k8s_client, "nginx-deployment.yaml") k8s_api = client.ExtensionsV1beta1Api(k8s_client) - deps = await k8s_api.read_namespaced_deployment("nginx-deployment", - "default") + deps = await k8s_api.read_namespaced_deployment("nginx-deployment", "default") print("Deployment {0} created".format(deps.metadata.name)) -if __name__ == '__main__': +if __name__ == "__main__": loop = asyncio.get_event_loop() loop.run_until_complete(main()) loop.close() diff --git a/examples/dynamic-client/accept_header.py b/examples/dynamic-client/accept_header.py index cec077785..e3a68f75f 100644 --- a/examples/dynamic-client/accept_header.py +++ b/examples/dynamic-client/accept_header.py @@ -35,7 +35,11 @@ async def main(): api = await 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'}} + params = { + "header_params": { + "Accept": "application/json;as=PartialObjectMetadataList;v=v1;g=meta.k8s.io" + } + } resp = await api.get(**params) diff --git a/examples/dynamic-client/cluster_scoped_custom_resource.py b/examples/dynamic-client/cluster_scoped_custom_resource.py index cf135df11..7e4cf4674 100644 --- a/examples/dynamic-client/cluster_scoped_custom_resource.py +++ b/examples/dynamic-client/cluster_scoped_custom_resource.py @@ -66,7 +66,9 @@ async def main(): "fqdn": {"type": "string"}, "tls": { "properties": { - "secretName": {"type": "string"} + "secretName": { + "type": "string" + } }, "type": "object", }, @@ -100,7 +102,9 @@ async def main(): "\n[INFO] custom resource definition `ingressroutes.apps.example.com` created\n" ) print("SCOPE\t\tNAME") - print(f"{crd_creation_response.spec.scope}\t\t{crd_creation_response.metadata.name}") + print( + f"{crd_creation_response.spec.scope}\t\t{crd_creation_response.metadata.name}" + ) # Fetching the "ingressroutes" CRD api @@ -157,16 +161,24 @@ async def main(): ingress_routes_list = await ingressroute_api.get() print("NAME\t\t\t\tFQDN\t\tTLS\t\t\t\tSTRATEGY") for item in ingress_routes_list.items: - print(f"{item.metadata.name}\t{item.spec.virtualhost.fqdn}\t{item.spec.virtualhost.tls}\t" - f"{item.spec.strategy}") + print( + f"{item.metadata.name}\t{item.spec.virtualhost.fqdn}\t{item.spec.virtualhost.tls}\t" + f"{item.spec.strategy}" + ) # Patching the ingressroutes custom resources ingressroute_manifest_first["spec"]["strategy"] = "Random" ingressroute_manifest_second["spec"]["strategy"] = "WeightedLeastRequest" - await ingressroute_api.patch(body=ingressroute_manifest_first, content_type="application/merge-patch+json") - await ingressroute_api.patch(body=ingressroute_manifest_second, content_type="application/merge-patch+json") + await ingressroute_api.patch( + body=ingressroute_manifest_first, + content_type="application/merge-patch+json", + ) + await 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" @@ -174,8 +186,10 @@ async def main(): patched_ingress_routes_list = await ingressroute_api.get() print("NAME\t\t\t\tFQDN\t\t\tTLS\t\t\tSTRATEGY") for item in patched_ingress_routes_list.items: - print(f"{item.metadata.name}\t{item.spec.virtualhost.fqdn}\t{item.spec.virtualhost.tls}\t" - f"{item.spec.strategy}") + print( + f"{item.metadata.name}\t{item.spec.virtualhost.fqdn}\t{item.spec.virtualhost.tls}\t" + f"{item.spec.strategy}" + ) # Deleting the ingressroutes custom resources diff --git a/examples/dynamic-client/deployment_rolling_restart.py b/examples/dynamic-client/deployment_rolling_restart.py index c54a63e30..1c6766562 100644 --- a/examples/dynamic-client/deployment_rolling_restart.py +++ b/examples/dynamic-client/deployment_rolling_restart.py @@ -74,8 +74,10 @@ async def main(): deployment_created = await api.get(name=name, namespace="default") print("NAMESPACE\tNAME\t\t\t\tREVISION\t\t\t\t\t\t\t\t\t\tRESTARTED-AT") - print(f"{deployment_created.metadata.namespace}\t\t{deployment_created.metadata.name}\t" - f"{deployment_created.metadata.annotations}\t\t{deployment_created.spec.template.metadata.annotations}") + print( + f"{deployment_created.metadata.namespace}\t\t{deployment_created.metadata.name}\t" + f"{deployment_created.metadata.annotations}\t\t{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` @@ -94,8 +96,10 @@ async def main(): print("\n[INFO] deployment `nginx-deployment` restarted\n") print("NAMESPACE\tNAME\t\t\t\tREVISION\t\t\t\t\t\t\t\t\tRESTARTED-AT") - print(f"{deployment_patched.metadata.namespace}\t\t{deployment_patched.metadata.name}\t" - f"{deployment_patched.metadata.annotations}\t{deployment_patched.spec.template.metadata.annotations}") + print( + f"{deployment_patched.metadata.namespace}\t\t{deployment_patched.metadata.name}\t" + f"{deployment_patched.metadata.annotations}\t{deployment_patched.spec.template.metadata.annotations}" + ) # Deleting deployment `nginx-deployment` from the `default` namespace diff --git a/examples/dynamic-client/namespaced_custom_resource.py b/examples/dynamic-client/namespaced_custom_resource.py index c80650a92..7394452c1 100644 --- a/examples/dynamic-client/namespaced_custom_resource.py +++ b/examples/dynamic-client/namespaced_custom_resource.py @@ -79,7 +79,9 @@ async def main(): "fqdn": {"type": "string"}, "tls": { "properties": { - "secretName": {"type": "string"} + "secretName": { + "type": "string" + } }, "type": "object", }, @@ -172,8 +174,12 @@ async def main(): }, } - await ingressroute_api.create(body=ingressroute_manifest_first, namespace=namespace_first) - await ingressroute_api.create(body=ingressroute_manifest_second, namespace=namespace_second) + await ingressroute_api.create( + body=ingressroute_manifest_first, namespace=namespace_first + ) + await ingressroute_api.create( + body=ingressroute_manifest_second, namespace=namespace_second + ) print("\n[INFO] custom resources `ingress-route-*` created\n") # Listing the `ingress-route-*` custom resources @@ -192,7 +198,7 @@ async def main(): item["metadata"]["namespace"], item["spec"]["virtualhost"]["fqdn"], item["spec"]["virtualhost"]["tls"], - item["spec"]["strategy"] + item["spec"]["strategy"], ) ) @@ -202,10 +208,12 @@ async def main(): ingressroute_manifest_second["spec"]["strategy"] = "WeightedLeastRequest" await ingressroute_api.patch( - body=ingressroute_manifest_first, content_type="application/merge-patch+json" + body=ingressroute_manifest_first, + content_type="application/merge-patch+json", ) await ingressroute_api.patch( - body=ingressroute_manifest_second, content_type="application/merge-patch+json" + body=ingressroute_manifest_second, + content_type="application/merge-patch+json", ) print( @@ -227,7 +235,7 @@ async def main(): item["metadata"]["namespace"], item["spec"]["virtualhost"]["fqdn"], item["spec"]["virtualhost"]["tls"], - item["spec"]["strategy"] + item["spec"]["strategy"], ) ) diff --git a/examples/dynamic-client/replication_controller.py b/examples/dynamic-client/replication_controller.py index 98934742d..636098a50 100644 --- a/examples/dynamic-client/replication_controller.py +++ b/examples/dynamic-client/replication_controller.py @@ -59,11 +59,11 @@ async def main(): } # Creating replication-controller `frontend-replication-controller` in the `default` namespace - await api.create( - body=replication_controller_manifest, namespace="default" - ) + await api.create(body=replication_controller_manifest, namespace="default") - print("\n[INFO] replication-controller `frontend-replication-controller` created\n") + print( + "\n[INFO] replication-controller `frontend-replication-controller` created\n" + ) # Listing replication-controllers in the `default` namespace replication_controller_created = await api.get(name=name, namespace="default") @@ -81,7 +81,9 @@ async def main(): # Deleting replication-controller `frontend-service` from the `default` namespace await api.delete(name=name, body={}, namespace="default") - print("[INFO] replication-controller `frontend-replication-controller` deleted\n") + print( + "[INFO] replication-controller `frontend-replication-controller` deleted\n" + ) if __name__ == "__main__": diff --git a/examples/dynamic-client/request_timeout.py b/examples/dynamic-client/request_timeout.py index 920d89d43..4b5725221 100644 --- a/examples/dynamic-client/request_timeout.py +++ b/examples/dynamic-client/request_timeout.py @@ -64,7 +64,10 @@ async def main(): # Client-side timeout to 60 seconds configmap_list = await api.get( - name=configmap_name, namespace="default", label_selector="foo=bar", _request_time=60 + name=configmap_name, + namespace="default", + label_selector="foo=bar", + _request_time=60, ) print(f"NAME:\n{configmap_list.metadata.name}\n") diff --git a/examples/dynamic-client/service.py b/examples/dynamic-client/service.py index ae53fc5c3..7fbdd41a5 100644 --- a/examples/dynamic-client/service.py +++ b/examples/dynamic-client/service.py @@ -41,7 +41,11 @@ async def main(): service_manifest = { "apiVersion": "v1", "kind": "Service", - "metadata": {"labels": {"name": name}, "name": name, "resourceversion": "v1"}, + "metadata": { + "labels": {"name": name}, + "name": name, + "resourceversion": "v1", + }, "spec": { "ports": [ {"name": "port", "port": 80, "protocol": "TCP", "targetPort": 80} @@ -71,7 +75,9 @@ async def main(): {"name": "new", "port": 8080, "protocol": "TCP", "targetPort": 8080} ] - service_patched = await api.patch(body=service_manifest, name=name, namespace="default") + service_patched = await 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")) diff --git a/examples/in_cluster_config.py b/examples/in_cluster_config.py index b9a704acd..503603236 100644 --- a/examples/in_cluster_config.py +++ b/examples/in_cluster_config.py @@ -80,7 +80,7 @@ async def main(): await asyncio.sleep(10) -if __name__ == '__main__': +if __name__ == "__main__": loop = asyncio.get_event_loop() loop.run_until_complete(main()) loop.close() diff --git a/examples/example1.py b/examples/list_pods.py similarity index 96% rename from examples/example1.py rename to examples/list_pods.py index c7d64fbd4..ccb0c607a 100644 --- a/examples/example1.py +++ b/examples/list_pods.py @@ -21,7 +21,7 @@ async def main(): print(i.status.pod_ip, i.metadata.namespace, i.metadata.name) -if __name__ == '__main__': +if __name__ == "__main__": loop = asyncio.get_event_loop() loop.run_until_complete(main()) loop.close() diff --git a/examples/example3.py b/examples/pod_exec.py similarity index 59% rename from examples/example3.py rename to examples/pod_exec.py index 0124296eb..31ffde65e 100644 --- a/examples/example3.py +++ b/examples/pod_exec.py @@ -16,33 +16,39 @@ async def main(): ret = await v1.list_pod_for_all_namespaces() for i in ret.items: - if i.metadata.name.startswith('busybox'): + if i.metadata.name.startswith("busybox"): pod = i.metadata.name namespace = i.metadata.namespace - print('Buxy box', pod, 'namespace', namespace) + print("Buxy box", pod, "namespace", namespace) break else: - print('Busybox not found !') + print("Busybox not found !") return v1_ws = client.CoreV1Api(api_client=WsApiClient()) exec_command = [ - '/bin/sh', - '-c', - 'echo This message goes to stderr >&2; echo This message goes to stdout'] - - resp = v1_ws.connect_get_namespaced_pod_exec(pod, namespace, - command=exec_command, - stderr=True, stdin=False, - stdout=True, tty=False) + "/bin/sh", + "-c", + "echo This message goes to stderr >&2; echo This message goes to stdout", + ] + + resp = v1_ws.connect_get_namespaced_pod_exec( + pod, + namespace, + command=exec_command, + stderr=True, + stdin=False, + stdout=True, + tty=False, + ) ret = await resp print("Response: ", ret) -if __name__ == '__main__': +if __name__ == "__main__": loop = asyncio.get_event_loop() loop.run_until_complete(main()) loop.close() diff --git a/examples/tail.py b/examples/tail.py index 0d7583dd3..5754a858f 100644 --- a/examples/tail.py +++ b/examples/tail.py @@ -18,34 +18,39 @@ def parse_args(): - parser = argparse.ArgumentParser(description='Tail for pods') - parser.add_argument('namespace', help="k8s namespace") - parser.add_argument('pod', help="pod name or prefix") - parser.add_argument('-f', '--follow', action='store_true', - help="output appended data as the file grows") - parser.add_argument('-n', '--lines', default=10, - help='show the last LINES lines') + parser = argparse.ArgumentParser(description="Tail for pods") + parser.add_argument("namespace", help="k8s namespace") + parser.add_argument("pod", help="pod name or prefix") + parser.add_argument( + "-f", + "--follow", + action="store_true", + help="output appended data as the file grows", + ) + parser.add_argument("-n", "--lines", default=10, help="show the last LINES lines") return parser.parse_args() async def print_pod_log(v1_api, pod, namespace, container, lines, follow): if not follow: - resp = await v1_api.read_namespaced_pod_log(pod, - namespace, - container=container, - tail_lines=lines) + resp = await v1_api.read_namespaced_pod_log( + pod, namespace, container=container, tail_lines=lines + ) print(resp) else: - resp = await v1_api.read_namespaced_pod_log(pod, - namespace, - container=container, - tail_lines=lines, - follow=True, _preload_content=False) + resp = await v1_api.read_namespaced_pod_log( + pod, + namespace, + container=container, + tail_lines=lines, + follow=True, + _preload_content=False, + ) while True: line = await resp.content.readline() if not line: break - print(line.decode('utf-8'), end="") + print(line.decode("utf-8"), end="") async def main(): @@ -60,29 +65,35 @@ async def main(): for pod in ret.items: if pod.metadata.name.startswith(args.pod): for container in pod.spec.containers: - cmd.append(print_pod_log(v1_api, - pod.metadata.name, - args.namespace, - container.name, - args.lines, - args.follow)) + cmd.append( + print_pod_log( + v1_api, + pod.metadata.name, + args.namespace, + container.name, + args.lines, + args.follow, + ) + ) if cmd == []: - print('No matching PODs !') + print("No matching PODs !") await api.close() return if args.follow: # autorefresh gcp token - cmd.append(config.refresh_token( - loader=loader, - client_configuration=client_configuration)) + cmd.append( + config.refresh_token( + loader=loader, client_configuration=client_configuration + ) + ) await asyncio.wait(cmd) await api.close() -if __name__ == '__main__': +if __name__ == "__main__": loop = asyncio.get_event_loop() loop.run_until_complete(main()) loop.close() diff --git a/examples/example2.py b/examples/watch_namespaces.py similarity index 87% rename from examples/example2.py rename to examples/watch_namespaces.py index 788e93bfa..09838c8f6 100644 --- a/examples/example2.py +++ b/examples/watch_namespaces.py @@ -14,7 +14,7 @@ async def main(): w = watch.Watch() async for event in w.stream(v1.list_namespace, timeout_seconds=10): - print("Event: {} {}".format(event['type'], event['object'].metadata.name)) + print("Event: {} {}".format(event["type"], event["object"].metadata.name)) count -= 1 if not count: w.stop() @@ -25,7 +25,7 @@ async def main(): await w.close() -if __name__ == '__main__': +if __name__ == "__main__": loop = asyncio.get_event_loop() loop.run_until_complete(main()) loop.close() diff --git a/examples/example4.py b/examples/watch_ns_pods.py similarity index 77% rename from examples/example4.py rename to examples/watch_ns_pods.py index 60b9fdc4c..e31e9b958 100644 --- a/examples/example4.py +++ b/examples/watch_ns_pods.py @@ -1,4 +1,5 @@ """Watch multiple K8s event streams without threads.""" + import asyncio from kubernetes_asyncio import client, config, watch @@ -9,7 +10,7 @@ async def watch_namespaces(): v1 = client.CoreV1Api(api) async with watch.Watch().stream(v1.list_namespace) as stream: async for event in stream: - etype, obj = event['type'], event['object'] + etype, obj = event["type"], event["object"] print("{} namespace {}".format(etype, obj.metadata.name)) @@ -18,8 +19,12 @@ async def watch_pods(): v1 = client.CoreV1Api(api) async with watch.Watch().stream(v1.list_pod_for_all_namespaces) as stream: async for event in stream: - evt, obj = event['type'], event['object'] - print("{} pod {} in NS {}".format(evt, obj.metadata.name, obj.metadata.namespace)) + evt, obj = event["type"], event["object"] + print( + "{} pod {} in NS {}".format( + evt, obj.metadata.name, obj.metadata.namespace + ) + ) def main(): @@ -40,5 +45,5 @@ def main(): loop.close() -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/test-requirements.txt b/test-requirements.txt index 22f6b087f..c4d43b14a 100644 --- a/test-requirements.txt +++ b/test-requirements.txt @@ -8,3 +8,4 @@ pytest-xdist randomize>=0.13 recommonmark sphinx>=1.2.1,!=1.3b1,<7.3 # BSD +black