Skip to content
This repository has been archived by the owner on Jun 13, 2024. It is now read-only.

Add cache_file parameter for DynamicClient #405

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions changelogs/fragments/405-cachefile_dynamic_client.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
---
minor_changes:
- Add logic for cache file name generation (https://github.com/ansible-collections/community.kubernetes/pull/405).
- Add cache_file when DynamicClient is created (https://github.com/ansible-collections/community.kubernetes/pull/405).
47 changes: 45 additions & 2 deletions plugins/module_utils/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,14 @@
import os
import traceback
import sys
import tempfile
from datetime import datetime
from distutils.version import LooseVersion

from ansible_collections.community.kubernetes.plugins.module_utils.args_common import (AUTH_ARG_MAP, AUTH_ARG_SPEC)

from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.six import iteritems, string_types
from ansible.module_utils.six import iteritems, string_types, PY3
from ansible.module_utils._text import to_native, to_bytes, to_text
from ansible.module_utils.common.dict_transformations import dict_merge
from ansible.module_utils.parsing.convert_bool import boolean
Expand Down Expand Up @@ -118,6 +119,40 @@ def configuration_digest(configuration):
return digest


def get_user():
if hasattr(os, 'getlogin'):
try:
user = os.getlogin()
if user:
return str(user)
except OSError:
pass
if hasattr(os, 'getuid'):
try:
user = os.getuid()
if user:
return str(user)
except OSError:
pass
user = os.environ.get("USERNAME")
if user:
return str(user)
return None


def get_default_cache_id(client):
user = get_user()
if user:
cache_id = "{0}-{1}".format(client.configuration.host, user)
else:
cache_id = client.configuration.host

if PY3:
return cache_id.encode('utf-8')

return cache_id


def get_api_client(module=None, **kwargs):
auth = {}

Expand Down Expand Up @@ -181,8 +216,16 @@ def auth_set(*names):
client = get_api_client._pool[digest]
return client

def generate_cache_file(kubeclient):
import hashlib
cache_file_name = 'k8srcp-{0}.json'.format(hashlib.sha1(get_default_cache_id(kubeclient)).hexdigest())
return os.path.join(tempfile.gettempdir(), cache_file_name)

kubeclient = kubernetes.client.ApiClient(configuration)
cache_file = generate_cache_file(kubeclient)

try:
client = DynamicClient(kubernetes.client.ApiClient(configuration))
client = DynamicClient(kubeclient, cache_file)
except Exception as err:
_raise_or_fail(err, 'Failed to get client due to %s')

Expand Down