kubernetes-watch 0.1.3__tar.gz → 0.1.5__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. {kubernetes_watch-0.1.3 → kubernetes_watch-0.1.5}/PKG-INFO +1 -1
  2. kubernetes_watch-0.1.5/kube_watch/modules/logic/load.py +23 -0
  3. {kubernetes_watch-0.1.3 → kubernetes_watch-0.1.5}/kube_watch/modules/providers/aws.py +2 -2
  4. kubernetes_watch-0.1.5/kube_watch/modules/providers/vault.py +188 -0
  5. {kubernetes_watch-0.1.3 → kubernetes_watch-0.1.5}/kube_watch/watch/helpers.py +34 -7
  6. {kubernetes_watch-0.1.3 → kubernetes_watch-0.1.5}/pyproject.toml +1 -1
  7. kubernetes_watch-0.1.3/kube_watch/modules/logic/load.py +0 -8
  8. kubernetes_watch-0.1.3/kube_watch/modules/providers/vault.py +0 -113
  9. {kubernetes_watch-0.1.3 → kubernetes_watch-0.1.5}/LICENSE +0 -0
  10. {kubernetes_watch-0.1.3 → kubernetes_watch-0.1.5}/README.md +0 -0
  11. {kubernetes_watch-0.1.3 → kubernetes_watch-0.1.5}/kube_watch/__init__.py +0 -0
  12. {kubernetes_watch-0.1.3 → kubernetes_watch-0.1.5}/kube_watch/enums/__init__.py +0 -0
  13. {kubernetes_watch-0.1.3 → kubernetes_watch-0.1.5}/kube_watch/enums/kube.py +0 -0
  14. {kubernetes_watch-0.1.3 → kubernetes_watch-0.1.5}/kube_watch/enums/logic.py +0 -0
  15. {kubernetes_watch-0.1.3 → kubernetes_watch-0.1.5}/kube_watch/enums/providers.py +0 -0
  16. {kubernetes_watch-0.1.3 → kubernetes_watch-0.1.5}/kube_watch/enums/workflow.py +0 -0
  17. {kubernetes_watch-0.1.3 → kubernetes_watch-0.1.5}/kube_watch/models/__init__.py +0 -0
  18. {kubernetes_watch-0.1.3 → kubernetes_watch-0.1.5}/kube_watch/models/common.py +0 -0
  19. {kubernetes_watch-0.1.3 → kubernetes_watch-0.1.5}/kube_watch/models/workflow.py +0 -0
  20. {kubernetes_watch-0.1.3 → kubernetes_watch-0.1.5}/kube_watch/modules/__init__.py +0 -0
  21. {kubernetes_watch-0.1.3 → kubernetes_watch-0.1.5}/kube_watch/modules/clusters/__init__.py +0 -0
  22. {kubernetes_watch-0.1.3 → kubernetes_watch-0.1.5}/kube_watch/modules/clusters/kube.py +0 -0
  23. {kubernetes_watch-0.1.3 → kubernetes_watch-0.1.5}/kube_watch/modules/logic/actions.py +0 -0
  24. {kubernetes_watch-0.1.3 → kubernetes_watch-0.1.5}/kube_watch/modules/logic/checks.py +0 -0
  25. {kubernetes_watch-0.1.3 → kubernetes_watch-0.1.5}/kube_watch/modules/logic/merge.py +0 -0
  26. {kubernetes_watch-0.1.3 → kubernetes_watch-0.1.5}/kube_watch/modules/logic/scheduler.py +0 -0
  27. {kubernetes_watch-0.1.3 → kubernetes_watch-0.1.5}/kube_watch/modules/logic/trasnform.py +0 -0
  28. {kubernetes_watch-0.1.3 → kubernetes_watch-0.1.5}/kube_watch/modules/mock/__init__.py +0 -0
  29. {kubernetes_watch-0.1.3 → kubernetes_watch-0.1.5}/kube_watch/modules/mock/mock_generator.py +0 -0
  30. {kubernetes_watch-0.1.3 → kubernetes_watch-0.1.5}/kube_watch/modules/providers/__init__.py +0 -0
  31. {kubernetes_watch-0.1.3 → kubernetes_watch-0.1.5}/kube_watch/modules/providers/git.py +0 -0
  32. {kubernetes_watch-0.1.3 → kubernetes_watch-0.1.5}/kube_watch/modules/providers/github.py +0 -0
  33. {kubernetes_watch-0.1.3 → kubernetes_watch-0.1.5}/kube_watch/standalone/metarecogen/ckan_to_gn.py +0 -0
  34. {kubernetes_watch-0.1.3 → kubernetes_watch-0.1.5}/kube_watch/watch/__init__.py +0 -0
  35. {kubernetes_watch-0.1.3 → kubernetes_watch-0.1.5}/kube_watch/watch/workflow.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: kubernetes-watch
3
- Version: 0.1.3
3
+ Version: 0.1.5
4
4
  Summary:
5
5
  Author: bmotevalli
6
6
  Author-email: b.motevalli@gmail.com
@@ -0,0 +1,23 @@
1
+ import os
2
+ from prefect import get_run_logger
3
+ logger = get_run_logger()
4
+
5
+ def load_secrets_to_env(data):
6
+ for key, value in data.items():
7
+ if key in os.environ:
8
+ del os.environ[key]
9
+ os.environ[key] = value
10
+ # logger.info(f"ENV VAR: {key} loaded")
11
+
12
+ def load_env_from_file(filepath):
13
+ with open(filepath, "r") as f:
14
+ for line in f:
15
+ # Remove whitespace and ignore comments
16
+ line = line.strip()
17
+ if line and not line.startswith('#'):
18
+ key, value = line.split('=', 1)
19
+ # Remove the environment variable if it already exists
20
+ if key in os.environ:
21
+ del os.environ[key]
22
+ # Set the new value
23
+ os.environ[key] = value
@@ -1,10 +1,10 @@
1
1
  #========================================================================
2
2
  # This class is deprecated. Please refer to aws.py
3
3
  #========================================================================
4
- import boto3
5
- import base64
6
4
  import json
5
+ import base64
7
6
  from datetime import datetime , timezone, timedelta
7
+ import boto3
8
8
  from botocore.exceptions import ClientError
9
9
  from prefect import get_run_logger
10
10
  from kube_watch.enums.providers import AwsResources
@@ -0,0 +1,188 @@
1
+ import hvac
2
+ import os
3
+ from prefect import get_run_logger
4
+
5
+ from kube_watch.enums.providers import Providers
6
+
7
+ logger = get_run_logger()
8
+
9
+ def login(url, app_role_id, secret_id, path):
10
+ """
11
+ Login to Vault, using an existing token if available, or via AppRole otherwise.
12
+
13
+ Parameters:
14
+ url (str): Vault server URL.
15
+ app_role_id (str): AppRole ID.
16
+ secret_id (str): AppRole Secret ID.
17
+ path (str): Path where the AppRole is enabled.
18
+
19
+ Returns:
20
+ dict: Dictionary containing the initialized vault_client.
21
+ """
22
+ vault_client = hvac.Client(url=url)
23
+
24
+ # Attempt to use an existing token from environment variables
25
+ vault_token = os.getenv('VAULT_TOKEN', None)
26
+ if vault_token:
27
+ vault_client.token = vault_token
28
+ # Verify if the current token is still valid
29
+ try:
30
+ if vault_client.is_authenticated():
31
+ logger.info("Authenticated with existing token.")
32
+ return vault_client
33
+ except hvac.exceptions.InvalidRequest as e:
34
+ logger.warning(f"Failed to authenticate with the existing token: {str(e)}")
35
+
36
+ # If token is not valid or not present, authenticate with AppRole
37
+ try:
38
+ vault_client.auth.approle.login(
39
+ role_id=app_role_id,
40
+ secret_id=secret_id,
41
+ mount_point=f'approle/{path}'
42
+ )
43
+
44
+ # Store the new token in environment variables for subsequent use
45
+ os.environ['VAULT_TOKEN'] = vault_client.token
46
+ logger.info("Authenticated with new token and stored in environment variable.")
47
+
48
+ return vault_client
49
+ except hvac.exceptions.InvalidRequest as e:
50
+ logger.error(f"Authentication failed with provided secret_id: {str(e)}")
51
+ raise RuntimeError("Authentication failed: unable to log in with the provided credentials.") from e
52
+
53
+
54
+
55
+ def get_secret(vault_client, secret_path, vault_mount_point):
56
+ """
57
+ Retrieve a secret from Vault
58
+ """
59
+ res = vault_client.secrets.kv.v2.read_secret_version(
60
+ path=secret_path,
61
+ mount_point=vault_mount_point,
62
+ raise_on_deleted_version=True
63
+ )
64
+ return res.get('data', {}).get('data')
65
+
66
+
67
+ def update_secret(vault_client, secret_path, secret_data, vault_mount_point):
68
+ """
69
+ Update or create a secret in Vault at the specified path.
70
+
71
+ Args:
72
+ vault_client: The authenticated Vault client instance.
73
+ secret_path (str): The path where the secret will be stored or updated in Vault.
74
+ secret_data (dict): The secret data to store as a dictionary.
75
+ vault_mount_point (str): The mount point for the KV store.
76
+
77
+ Returns:
78
+ bool: True if the operation was successful, False otherwise.
79
+ """
80
+ try:
81
+ # Writing the secret data to Vault at the specified path
82
+ vault_client.secrets.kv.v2.create_or_update_secret(
83
+ path=secret_path,
84
+ secret=secret_data,
85
+ mount_point=vault_mount_point
86
+ )
87
+ print("Secret updated successfully.")
88
+ return True
89
+ except Exception as e:
90
+ print(f"Failed to update secret: {e}")
91
+ return False
92
+
93
+ def generate_provider_creds(vault_client, provider, backend_path, role_name):
94
+ """
95
+ Generate credentials for a specified provider
96
+ """
97
+ if provider == Providers.AWS:
98
+ backend_path = backend_path
99
+ role_name = role_name
100
+ creds_path = f"{backend_path}/creds/{role_name}"
101
+ return vault_client.read(creds_path)
102
+
103
+ raise ValueError("Unknown provider")
104
+
105
+
106
+
107
+ def generate_new_secret_id(vault_client, role_name, vault_path, env_var_name):
108
+ """
109
+ Generates new secret_id. Note an admin role is required for this.
110
+ """
111
+ try:
112
+ # Write directly to the Vault endpoint to create the secret ID with num_uses
113
+ # response = vault_client.write(
114
+ # f"auth/approle/{vault_path}/role/{role_name}/secret-id",
115
+ # )
116
+ response = vault_client.auth.approle.generate_secret_id(
117
+ role_name=role_name,
118
+ mount_point=f'approle/{vault_path}'
119
+ )
120
+ # Check if the response contains the secret ID
121
+ if response and 'data' in response:
122
+ secret_id = response['data']['secret_id']
123
+ secret_id_accessor = response['data']['secret_id_accessor']
124
+ logger.info("Generated a new secret ID with usage buffer.")
125
+ return {env_var_name: secret_id, f"{env_var_name}_ACCESSOR": secret_id_accessor}
126
+ else:
127
+ logger.error("No secret ID returned in the response.")
128
+ raise RuntimeError("Failed to generate new secret ID: No content returned.")
129
+ except hvac.exceptions.InvalidRequest as e:
130
+ logger.error("Error generating new secret ID: %s", str(e))
131
+ raise RuntimeError("Failed to generate new secret ID.") from e
132
+ # new_secret_response = vault_client.auth.approle.generate_secret_id(
133
+ # role_name=role_name,
134
+ # mount_point=f'approle/{vault_path}'
135
+ # )
136
+
137
+ # return { env_var_name : new_secret_response['data']['secret_id'] }
138
+
139
+
140
+
141
+ def delete_secret_id(vault_client, role_name, secret_id, vault_path):
142
+ """
143
+ Delete (revoke) a secret ID associated with a role in Vault.
144
+
145
+ Parameters:
146
+ vault_client (hvac.Client): An authenticated Vault client.
147
+ role_name (str): The name of the role the secret ID is associated with.
148
+ secret_id (str): The secret ID to be deleted.
149
+ vault_path (str): The path where the AppRole is enabled.
150
+ """
151
+ try:
152
+ vault_client.auth.approle.destroy_secret_id(
153
+ mount_point=f"approle/{vault_path}",
154
+ role_name=role_name,
155
+ secret_id=secret_id
156
+ )
157
+
158
+ logger.info("Secret ID successfully revoked.")
159
+ except hvac.exceptions.InvalidRequest as e:
160
+ logger.error("Failed to revoke the secret ID: %s", str(e))
161
+ raise RuntimeError("Failed to delete the secret ID.") from e
162
+
163
+
164
+ def clean_secret_ids(vault_client, role_name, secret_id_env, vault_path, has_kube_secret_updated):
165
+ """
166
+ This function removes all idle secret-ids from `role_name`, except the
167
+ inputted `secret_id_env`.
168
+
169
+ Note: secret_id_env is a dictionary. The key, VAULT_SECRET_ID, has the secret_id value.
170
+ """
171
+ secret_id = secret_id_env.get("VAULT_SECRET_ID_ACCESSOR")
172
+
173
+ if has_kube_secret_updated:
174
+ secret_ids_path = f'auth/approle/{vault_path}/role/{role_name}/secret-id'
175
+ try:
176
+ response = vault_client.list(secret_ids_path)
177
+ if 'data' in response:
178
+ secret_ids = response['data']['keys']
179
+ for idx in secret_ids:
180
+ if idx != secret_id:
181
+ delete_secret_id(vault_client, role_name, secret_id, vault_path)
182
+ logger.info(f"Revoking idle secret id for role: {role_name}")
183
+ else:
184
+ logger.info("No secrets found at this path.")
185
+ except hvac.exceptions.Forbidden:
186
+ logger.error("Access denied. Ensure your token has the correct policies to read this path.")
187
+ except Exception as e:
188
+ logger.error(f"An error occurred: {e}")
@@ -39,9 +39,9 @@ def func_task(name="default_task_name", task_input_type: TaskInputsType = TaskIn
39
39
  return execute_task
40
40
  if task_input_type == TaskInputsType.DICT:
41
41
  @task(name=name)
42
- def execute_task(func, dict_inp):
42
+ def execute_task_dict(func, dict_inp):
43
43
  return func(dict_inp)
44
- return execute_task
44
+ return execute_task_dict
45
45
  raise ValueError(f'Unknow Task Input Type. It should either be {TaskInputsType.ARG} or {TaskInputsType.DICT} but {task_input_type} is provided.')
46
46
 
47
47
 
@@ -79,10 +79,10 @@ def get_task_function(module_name, task_name, plugin_path=None):
79
79
  raise ImportError(f"Unable to import module '{module_name}': {e}")
80
80
  except AttributeError as e:
81
81
  raise AttributeError(f"The module '{module_name}' does not have a function named '{task_name}': {e}")
82
- finally:
83
- if plugin_path:
84
- # Remove the plugin path from sys.path after importing
85
- sys.path.pop(0) # Using pop(0) is safer in the context of insert(0, plugin_path)
82
+ # finally:
83
+ # if plugin_path:
84
+ # # Remove the plugin path from sys.path after importing
85
+ # sys.path.pop(0) # Using pop(0) is safer in the context of insert(0, plugin_path)
86
86
 
87
87
 
88
88
 
@@ -141,4 +141,31 @@ def resolve_runner(runner):
141
141
  if runner == TaskRunners.RAY:
142
142
  raise ValueError("Ray Not Implemented")
143
143
  # return RayTaskRunner
144
- raise ValueError("Invalid task runner type")
144
+ raise ValueError("Invalid task runner type")
145
+
146
+
147
+ def filter_attributes(obj):
148
+ import uuid
149
+ from collections.abc import Iterable
150
+ import inspect
151
+
152
+ def is_simple(value):
153
+ """ Check if the value is a simple data type or a collection of simple data types """
154
+ if isinstance(value, (int, float, str, bool, type(None), uuid.UUID)):
155
+ return True
156
+ if isinstance(value, dict):
157
+ return all(is_simple(k) and is_simple(v) for k, v in value.items())
158
+ if isinstance(value, Iterable) and not isinstance(value, (str, bytes)):
159
+ return all(is_simple(item) for item in value)
160
+ return False
161
+
162
+ result = {}
163
+ for attr in dir(obj):
164
+ # Avoid magic methods and attributes
165
+ if attr.startswith("__") and attr.endswith("__"):
166
+ continue
167
+ value = getattr(obj, attr)
168
+ # Filter out methods and check if the attribute value is simple
169
+ if not callable(value) and not inspect.isclass(value) and is_simple(value):
170
+ result[attr] = value
171
+ return result
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "kubernetes-watch"
3
- version = "0.1.3"
3
+ version = "0.1.5"
4
4
  description = ""
5
5
  authors = ["bmotevalli <b.motevalli@gmail.com>"]
6
6
  packages = [{include = "kube_watch"}]
@@ -1,8 +0,0 @@
1
- import os
2
- from prefect import get_run_logger
3
- logger = get_run_logger()
4
-
5
- def load_secrets_to_env(data):
6
- for key, value in data.items():
7
- os.environ[key] = value
8
- # logger.info(f"ENV VAR: {key} loaded")
@@ -1,113 +0,0 @@
1
- import hvac
2
- import os
3
- from prefect import get_run_logger
4
-
5
- from kube_watch.enums.providers import Providers
6
-
7
- logger = get_run_logger()
8
-
9
- def login(url, app_role_id, secret_id, path):
10
- """
11
- Login to Vault, using an existing token if available, or via AppRole otherwise.
12
-
13
- Parameters:
14
- url (str): Vault server URL.
15
- app_role_id (str): AppRole ID.
16
- secret_id (str): AppRole Secret ID.
17
- path (str): Path where the AppRole is enabled.
18
-
19
- Returns:
20
- dict: Dictionary containing the initialized vault_client.
21
- """
22
- vault_client = hvac.Client(url=url)
23
-
24
- # Attempt to use an existing token from environment variables
25
- vault_token = os.getenv('VAULT_TOKEN', None)
26
- if vault_token:
27
- vault_client.token = vault_token
28
- # Verify if the current token is still valid
29
- try:
30
- if vault_client.is_authenticated():
31
- logger.info("Authenticated with existing token.")
32
- return vault_client
33
- except hvac.exceptions.InvalidRequest as e:
34
- logger.warning("Failed to authenticate with the existing token:", str(e))
35
-
36
- # If token is not valid or not present, authenticate with AppRole
37
- try:
38
- vault_client.auth.approle.login(
39
- role_id=app_role_id,
40
- secret_id=secret_id,
41
- mount_point=f'approle/{path}'
42
- )
43
-
44
- # Store the new token in environment variables for subsequent use
45
- os.environ['VAULT_TOKEN'] = vault_client.token
46
- logger.info("Authenticated with new token and stored in environment variable.")
47
-
48
- return vault_client
49
- except hvac.exceptions.InvalidRequest as e:
50
- logger.error("Authentication failed with provided secret_id:", str(e))
51
- raise RuntimeError("Authentication failed: unable to log in with the provided credentials.") from e
52
-
53
-
54
-
55
- def get_secret(vault_client, secret_path, vault_mount_point):
56
- """
57
- Retrieve a secret from Vault
58
- """
59
- res = vault_client.secrets.kv.v2.read_secret_version(
60
- path=secret_path,
61
- mount_point=vault_mount_point,
62
- raise_on_deleted_version=True
63
- )
64
- return res.get('data', {}).get('data')
65
-
66
-
67
- def update_secret(vault_client, secret_path, secret_data, vault_mount_point):
68
- """
69
- Update or create a secret in Vault at the specified path.
70
-
71
- Args:
72
- vault_client: The authenticated Vault client instance.
73
- secret_path (str): The path where the secret will be stored or updated in Vault.
74
- secret_data (dict): The secret data to store as a dictionary.
75
- vault_mount_point (str): The mount point for the KV store.
76
-
77
- Returns:
78
- bool: True if the operation was successful, False otherwise.
79
- """
80
- try:
81
- # Writing the secret data to Vault at the specified path
82
- vault_client.secrets.kv.v2.create_or_update_secret(
83
- path=secret_path,
84
- secret=secret_data,
85
- mount_point=vault_mount_point
86
- )
87
- print("Secret updated successfully.")
88
- return True
89
- except Exception as e:
90
- print(f"Failed to update secret: {e}")
91
- return False
92
-
93
- def generate_provider_creds(vault_client, provider, backend_path, role_name):
94
- """
95
- Generate credentials for a specified provider
96
- """
97
- if provider == Providers.AWS:
98
- backend_path = backend_path
99
- role_name = role_name
100
- creds_path = f"{backend_path}/creds/{role_name}"
101
- return vault_client.read(creds_path)
102
-
103
- raise ValueError("Unknown provider")
104
-
105
-
106
-
107
- def generate_new_secret_id(vault_client, role_name, vault_path, env_var_name):
108
- new_secret_response = vault_client.auth.approle.generate_secret_id(
109
- role_name=role_name,
110
- mount_point=f'approle/{vault_path}'
111
- )
112
-
113
- return { env_var_name : new_secret_response['data']['secret_id'] }