1

I am using kubernetes-client library in python and looking at the various examples, it appears we don't need to explicitly close the client connection to the API server. Does the client connection gets terminated automatically or are the examples missing the call to close the connection? I also found the docs page for the APIs (AppsV1 for example) and the examples shown there use context manager for the calls so the connection gets disconnected automatically there but I still have questions for the scripts that don't use the context manager approach.

Krishna Chaurasia
  • 8,924
  • 6
  • 22
  • 35

1 Answers1

1

Kubernetes's API is HTTP-based, so you can often get away without explicitly closing a connection. If you have a short script, things should get cleaned up automatically at the end of the script and it's okay to not explicitly close things.

The specific documentation page you link to shows a safe way to do it:

with kubernetes.client.ApiClient(configuration) as api_client:
    api_instance = kubernetes.client.AppsV1Api(api_client)
    api_instance.create_namespaced_controller_revision(...)

The per-API-version client object is stateless if you pass in an ApiClient to its constructor, so it's safe to create these objects as needed.

The ApiClient class includes an explicit close method, so you could also do this (less safely) without the context-manager syntax:

api_client = kubernetes.client.ApiClient(configuration)
apps_client = kubernetes.client.AppsV1Api(api_client)
...
api_client.close()

The library client front-page README suggests a path that doesn't explicitly create an ApiClient. Looking at one of the generated models' code, if you don't pass an ApiClient option explicitly, a new one will be created for each API-version client object; that includes a connection pool as well. That can leak local memory and cause extra connections to the cluster, but this might not matter to you for small scripts.

David Maze
  • 130,717
  • 29
  • 175
  • 215
  • > If you have a short script, things should get cleaned up automatically at the end of the script and it's okay to not explicitly close things. How does it matter whether the script is short or long? Can you please elaborate? – Krishna Chaurasia Jan 05 '21 at 08:36
  • 1
    The client object maintains a connection pool. If you have a long-running script, and don't close the client, it's possible that connections in the pool will stay open much longer than you need them. In a shorter script, connections will never stay open after the script completes. – David Maze Jan 05 '21 at 11:13