kubexec 0.2.0__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.
- kubexec-0.2.0/PKG-INFO +75 -0
- kubexec-0.2.0/README.md +48 -0
- kubexec-0.2.0/kubexec/__init__.py +12 -0
- kubexec-0.2.0/kubexec/cli.py +250 -0
- kubexec-0.2.0/kubexec/config.py +159 -0
- kubexec-0.2.0/kubexec/exceptions.py +26 -0
- kubexec-0.2.0/kubexec/executor.py +262 -0
- kubexec-0.2.0/kubexec/k8s_client.py +249 -0
- kubexec-0.2.0/kubexec/templates.py +154 -0
- kubexec-0.2.0/kubexec/utils.py +67 -0
- kubexec-0.2.0/kubexec.egg-info/PKG-INFO +75 -0
- kubexec-0.2.0/kubexec.egg-info/SOURCES.txt +17 -0
- kubexec-0.2.0/kubexec.egg-info/dependency_links.txt +1 -0
- kubexec-0.2.0/kubexec.egg-info/entry_points.txt +2 -0
- kubexec-0.2.0/kubexec.egg-info/requires.txt +3 -0
- kubexec-0.2.0/kubexec.egg-info/top_level.txt +2 -0
- kubexec-0.2.0/setup.cfg +4 -0
- kubexec-0.2.0/setup.py +47 -0
- kubexec-0.2.0/tests/__init__.py +1 -0
kubexec-0.2.0/PKG-INFO
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: kubexec
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Execute commands and scripts on Kubernetes pods with Docker access
|
|
5
|
+
Author: kubexec team
|
|
6
|
+
Classifier: Development Status :: 3 - Alpha
|
|
7
|
+
Classifier: Intended Audience :: Developers
|
|
8
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
9
|
+
Classifier: Operating System :: OS Independent
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
15
|
+
Requires-Python: >=3.10
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
Requires-Dist: kubernetes>=28.1.0
|
|
18
|
+
Requires-Dist: PyYAML>=6.0
|
|
19
|
+
Requires-Dist: rich>=13.0.0
|
|
20
|
+
Dynamic: author
|
|
21
|
+
Dynamic: classifier
|
|
22
|
+
Dynamic: description
|
|
23
|
+
Dynamic: description-content-type
|
|
24
|
+
Dynamic: requires-dist
|
|
25
|
+
Dynamic: requires-python
|
|
26
|
+
Dynamic: summary
|
|
27
|
+
|
|
28
|
+
# kubexec
|
|
29
|
+
|
|
30
|
+
Execute commands and scripts on Kubernetes pods with Docker access.
|
|
31
|
+
|
|
32
|
+
## Installation
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
pip install -e .
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## Usage
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
kubexec [-h] [-d DOCKER_IMAGE] [-n NAMESPACE] [-p POD_NAME]
|
|
42
|
+
[-m MEMORY] [-c CPU] [-w WORKDIR] [-v VOLUME_MOUNT]
|
|
43
|
+
[--config CONFIG] [--context CONTEXT] [--create-pod]
|
|
44
|
+
[--cleanup] [--verbose] [--dry-run] TARGET
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Examples
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
# Run a simple command
|
|
51
|
+
kubexec 'echo "Hello, Kubernetes!"'
|
|
52
|
+
|
|
53
|
+
# Use specific Docker image
|
|
54
|
+
kubexec -d python:3.9 'python -c "import sys; print(sys.version)"'
|
|
55
|
+
|
|
56
|
+
# Run with resource limits
|
|
57
|
+
kubexec -m 4Gi -c 2 'stress --cpu 2 --timeout 60s'
|
|
58
|
+
|
|
59
|
+
# Execute script file
|
|
60
|
+
kubexec ./my_script.sh
|
|
61
|
+
|
|
62
|
+
# Use existing pod
|
|
63
|
+
kubexec -p my-existing-pod 'ls -la'
|
|
64
|
+
|
|
65
|
+
# Volume mounting
|
|
66
|
+
kubexec -v /host/data:/pod/data 'ls /pod/data'
|
|
67
|
+
|
|
68
|
+
# Save output to local files (works like local commands)
|
|
69
|
+
kubexec "ls -la > output.txt"
|
|
70
|
+
|
|
71
|
+
# Bioinformatics example with SPAdes genome assembler
|
|
72
|
+
# This will create spades-out/ directory in your current working directory
|
|
73
|
+
kubexec -d community.wave.seqera.io/library/spades:4.1.0--77799c52e1d1054a \
|
|
74
|
+
"spades.py -1 tests/reads/s_6_1.fastq.gz -2 tests/reads/s_6_2.fastq.gz -o spades-out"
|
|
75
|
+
```
|
kubexec-0.2.0/README.md
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
# kubexec
|
|
2
|
+
|
|
3
|
+
Execute commands and scripts on Kubernetes pods with Docker access.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install -e .
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Usage
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
kubexec [-h] [-d DOCKER_IMAGE] [-n NAMESPACE] [-p POD_NAME]
|
|
15
|
+
[-m MEMORY] [-c CPU] [-w WORKDIR] [-v VOLUME_MOUNT]
|
|
16
|
+
[--config CONFIG] [--context CONTEXT] [--create-pod]
|
|
17
|
+
[--cleanup] [--verbose] [--dry-run] TARGET
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## Examples
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
# Run a simple command
|
|
24
|
+
kubexec 'echo "Hello, Kubernetes!"'
|
|
25
|
+
|
|
26
|
+
# Use specific Docker image
|
|
27
|
+
kubexec -d python:3.9 'python -c "import sys; print(sys.version)"'
|
|
28
|
+
|
|
29
|
+
# Run with resource limits
|
|
30
|
+
kubexec -m 4Gi -c 2 'stress --cpu 2 --timeout 60s'
|
|
31
|
+
|
|
32
|
+
# Execute script file
|
|
33
|
+
kubexec ./my_script.sh
|
|
34
|
+
|
|
35
|
+
# Use existing pod
|
|
36
|
+
kubexec -p my-existing-pod 'ls -la'
|
|
37
|
+
|
|
38
|
+
# Volume mounting
|
|
39
|
+
kubexec -v /host/data:/pod/data 'ls /pod/data'
|
|
40
|
+
|
|
41
|
+
# Save output to local files (works like local commands)
|
|
42
|
+
kubexec "ls -la > output.txt"
|
|
43
|
+
|
|
44
|
+
# Bioinformatics example with SPAdes genome assembler
|
|
45
|
+
# This will create spades-out/ directory in your current working directory
|
|
46
|
+
kubexec -d community.wave.seqera.io/library/spades:4.1.0--77799c52e1d1054a \
|
|
47
|
+
"spades.py -1 tests/reads/s_6_1.fastq.gz -2 tests/reads/s_6_2.fastq.gz -o spades-out"
|
|
48
|
+
```
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""
|
|
2
|
+
kubexec - Execute commands and scripts on Kubernetes pods with Docker access
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
__version__ = "0.2.0"
|
|
6
|
+
__author__ = "kubexec team"
|
|
7
|
+
|
|
8
|
+
from .cli import main
|
|
9
|
+
from .executor import KubeExecutor
|
|
10
|
+
from .config import Config
|
|
11
|
+
|
|
12
|
+
__all__ = ["main", "KubeExecutor", "Config"]
|
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
"""Command-line interface for kubexec"""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import logging
|
|
5
|
+
import sys
|
|
6
|
+
import os
|
|
7
|
+
from typing import List, Optional
|
|
8
|
+
from .config import Config
|
|
9
|
+
from .executor import KubeExecutor
|
|
10
|
+
from .k8s_client import KubernetesClient
|
|
11
|
+
from .exceptions import KubeExecError
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def setup_logging(verbose: bool = False) -> None:
|
|
15
|
+
"""Setup logging configuration"""
|
|
16
|
+
level = logging.DEBUG if verbose else logging.INFO
|
|
17
|
+
logging.basicConfig(
|
|
18
|
+
level=level,
|
|
19
|
+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' if verbose else '%(message)s',
|
|
20
|
+
datefmt='%Y-%m-%d %H:%M:%S'
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def create_parser() -> argparse.ArgumentParser:
|
|
25
|
+
"""Create command-line argument parser"""
|
|
26
|
+
parser = argparse.ArgumentParser(
|
|
27
|
+
prog='kubexec',
|
|
28
|
+
description='Execute commands or scripts on Kubernetes pods with Docker access',
|
|
29
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
30
|
+
epilog="""
|
|
31
|
+
Examples:
|
|
32
|
+
kubexec 'echo "Hello, Kubernetes!"'
|
|
33
|
+
kubexec -d python:3.9 'python -c "import sys; print(sys.version)"'
|
|
34
|
+
kubexec -m 4Gi -c 2 ./my_script.sh
|
|
35
|
+
kubexec -p existing-pod 'ls -la'
|
|
36
|
+
kubexec --dry-run -d alpine 'apk add --no-cache curl'
|
|
37
|
+
"""
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
parser.add_argument(
|
|
41
|
+
'target',
|
|
42
|
+
metavar='TARGET',
|
|
43
|
+
help='Command string or path to script file to execute'
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
parser.add_argument(
|
|
47
|
+
'-d', '--docker-image',
|
|
48
|
+
help='Docker image for new pods (default: ubuntu:latest)'
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
parser.add_argument(
|
|
52
|
+
'-n', '--namespace',
|
|
53
|
+
help='Kubernetes namespace (default: default)'
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
parser.add_argument(
|
|
57
|
+
'-p', '--pod-name',
|
|
58
|
+
help='Target existing pod name or name for new pod'
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
parser.add_argument(
|
|
62
|
+
'-m', '--memory',
|
|
63
|
+
help='Memory limit for new pods (default: 1Gi)'
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
parser.add_argument(
|
|
67
|
+
'-c', '--cpu',
|
|
68
|
+
help='CPU limit for new pods (default: 1)'
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
parser.add_argument(
|
|
72
|
+
'-w', '--workdir',
|
|
73
|
+
help='Working directory inside pod (default: /tmp)'
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
parser.add_argument(
|
|
77
|
+
'-v', '--volume',
|
|
78
|
+
action='append',
|
|
79
|
+
dest='volume_mounts',
|
|
80
|
+
help='Volume mount (format: host_path:pod_path[:ro]). Can be used multiple times.'
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
parser.add_argument(
|
|
84
|
+
'--config',
|
|
85
|
+
help='Configuration file (default: ~/.config/kubexec/config.yaml)'
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
parser.add_argument(
|
|
89
|
+
'--context',
|
|
90
|
+
help='Kubernetes context to use'
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
parser.add_argument(
|
|
94
|
+
'--create-pod',
|
|
95
|
+
action='store_true',
|
|
96
|
+
help='Force creation of new pod (vs using existing)'
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
parser.add_argument(
|
|
100
|
+
'--cleanup',
|
|
101
|
+
action='store_true',
|
|
102
|
+
help='Delete pod after execution (only for created pods)'
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
parser.add_argument(
|
|
106
|
+
'--no-cleanup',
|
|
107
|
+
action='store_true',
|
|
108
|
+
help='Do not delete pod after execution'
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
parser.add_argument(
|
|
112
|
+
'--verbose',
|
|
113
|
+
action='store_true',
|
|
114
|
+
help='Verbose output'
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
parser.add_argument(
|
|
118
|
+
'--dry-run',
|
|
119
|
+
action='store_true',
|
|
120
|
+
help='Show what would be executed without running'
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
parser.add_argument(
|
|
124
|
+
'--list-jobs',
|
|
125
|
+
action='store_true',
|
|
126
|
+
help='List recent kubexec jobs'
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
parser.add_argument(
|
|
130
|
+
'--cleanup-old',
|
|
131
|
+
type=int,
|
|
132
|
+
metavar='HOURS',
|
|
133
|
+
help='Cleanup jobs older than specified hours'
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
return parser
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def main() -> int:
|
|
140
|
+
"""Main CLI entry point"""
|
|
141
|
+
parser = create_parser()
|
|
142
|
+
args = parser.parse_args()
|
|
143
|
+
|
|
144
|
+
# Setup logging
|
|
145
|
+
setup_logging(args.verbose)
|
|
146
|
+
logger = logging.getLogger(__name__)
|
|
147
|
+
|
|
148
|
+
try:
|
|
149
|
+
# Load configuration
|
|
150
|
+
config = Config(args.config)
|
|
151
|
+
|
|
152
|
+
# Initialize Kubernetes client
|
|
153
|
+
k8s_client = KubernetesClient(args.context)
|
|
154
|
+
|
|
155
|
+
# Handle special operations
|
|
156
|
+
if args.list_jobs:
|
|
157
|
+
return _handle_list_jobs(k8s_client, args.namespace or config.get('namespace'))
|
|
158
|
+
|
|
159
|
+
if args.cleanup_old:
|
|
160
|
+
return _handle_cleanup_old(k8s_client, args.namespace or config.get('namespace'), args.cleanup_old)
|
|
161
|
+
|
|
162
|
+
# Validate target
|
|
163
|
+
if not args.target:
|
|
164
|
+
parser.error("TARGET argument is required")
|
|
165
|
+
|
|
166
|
+
# Resolve cleanup setting
|
|
167
|
+
cleanup = None
|
|
168
|
+
if args.cleanup:
|
|
169
|
+
cleanup = True
|
|
170
|
+
elif args.no_cleanup:
|
|
171
|
+
cleanup = False
|
|
172
|
+
|
|
173
|
+
# Execute command/script
|
|
174
|
+
executor = KubeExecutor(config, k8s_client)
|
|
175
|
+
|
|
176
|
+
exit_code, output = executor.execute(
|
|
177
|
+
target=args.target,
|
|
178
|
+
docker_image=args.docker_image,
|
|
179
|
+
namespace=args.namespace,
|
|
180
|
+
pod_name=args.pod_name,
|
|
181
|
+
memory=args.memory,
|
|
182
|
+
cpu=args.cpu,
|
|
183
|
+
workdir=args.workdir,
|
|
184
|
+
volume_mounts=args.volume_mounts,
|
|
185
|
+
create_pod=args.create_pod,
|
|
186
|
+
cleanup=cleanup,
|
|
187
|
+
dry_run=args.dry_run
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
# Print output
|
|
191
|
+
if output:
|
|
192
|
+
print(output)
|
|
193
|
+
|
|
194
|
+
return exit_code
|
|
195
|
+
|
|
196
|
+
except KubeExecError as e:
|
|
197
|
+
logger.error(f"kubexec error: {e}")
|
|
198
|
+
return 1
|
|
199
|
+
except KeyboardInterrupt:
|
|
200
|
+
logger.info("Interrupted by user")
|
|
201
|
+
return 130
|
|
202
|
+
except Exception as e:
|
|
203
|
+
logger.error(f"Unexpected error: {e}")
|
|
204
|
+
if args.verbose:
|
|
205
|
+
import traceback
|
|
206
|
+
traceback.print_exc()
|
|
207
|
+
return 1
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _handle_list_jobs(k8s_client: KubernetesClient, namespace: str) -> int:
|
|
211
|
+
"""Handle --list-jobs operation"""
|
|
212
|
+
try:
|
|
213
|
+
from .executor import KubeExecutor
|
|
214
|
+
executor = KubeExecutor(Config(), k8s_client)
|
|
215
|
+
jobs = executor.list_jobs(namespace)
|
|
216
|
+
|
|
217
|
+
if not jobs:
|
|
218
|
+
print("No kubexec jobs found")
|
|
219
|
+
return 0
|
|
220
|
+
|
|
221
|
+
print(f"{'NAME':<30} {'STATUS':<12} {'IMAGE':<30} {'CREATED'}")
|
|
222
|
+
print("-" * 90)
|
|
223
|
+
for job in jobs:
|
|
224
|
+
created = job['created'].strftime('%Y-%m-%d %H:%M:%S') if job['created'] else 'unknown'
|
|
225
|
+
print(f"{job['name']:<30} {job['status']:<12} {job['image']:<30} {created}")
|
|
226
|
+
|
|
227
|
+
return 0
|
|
228
|
+
|
|
229
|
+
except Exception as e:
|
|
230
|
+
logging.error(f"Failed to list jobs: {e}")
|
|
231
|
+
return 1
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _handle_cleanup_old(k8s_client: KubernetesClient, namespace: str, max_age_hours: int) -> int:
|
|
235
|
+
"""Handle --cleanup-old operation"""
|
|
236
|
+
try:
|
|
237
|
+
from .executor import KubeExecutor
|
|
238
|
+
executor = KubeExecutor(Config(), k8s_client)
|
|
239
|
+
cleaned_count = executor.cleanup_old_jobs(namespace, max_age_hours)
|
|
240
|
+
|
|
241
|
+
print(f"Cleaned up {cleaned_count} jobs older than {max_age_hours} hours")
|
|
242
|
+
return 0
|
|
243
|
+
|
|
244
|
+
except Exception as e:
|
|
245
|
+
logging.error(f"Failed to cleanup old jobs: {e}")
|
|
246
|
+
return 1
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
if __name__ == '__main__':
|
|
250
|
+
sys.exit(main())
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
"""Configuration management for kubexec"""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import yaml
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Dict, Any, Optional
|
|
7
|
+
from .exceptions import ConfigurationError
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Config:
|
|
11
|
+
"""Configuration manager for kubexec"""
|
|
12
|
+
|
|
13
|
+
DEFAULT_CONFIG_DIRS = [
|
|
14
|
+
f"/shared/team/kubexec/{os.getenv('USER', 'default')}/",
|
|
15
|
+
os.path.join(os.path.expanduser("~"), ".config", "kubexec"),
|
|
16
|
+
f"/tmp/kubexec"
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
DEFAULT_CONFIG_FILE = "config.yaml"
|
|
20
|
+
|
|
21
|
+
DEFAULT_CONFIG = {
|
|
22
|
+
'docker_image': 'ubuntu:latest',
|
|
23
|
+
'namespace': None, # Will be auto-detected from service account
|
|
24
|
+
'memory': '1Gi',
|
|
25
|
+
'cpu': '1',
|
|
26
|
+
'workdir': '/tmp',
|
|
27
|
+
'cleanup': True,
|
|
28
|
+
'verbose': False,
|
|
29
|
+
'timeout': 3600, # 1 hour default timeout
|
|
30
|
+
'ttl_seconds_after_finished': 60, # Based on Nextflow config
|
|
31
|
+
'security_context': {
|
|
32
|
+
'fsGroup': 1000,
|
|
33
|
+
'runAsUser': 1000,
|
|
34
|
+
'runAsGroup': 1000,
|
|
35
|
+
'fsGroupChangePolicy': 'OnRootMismatch'
|
|
36
|
+
},
|
|
37
|
+
'node_selector': {
|
|
38
|
+
'hub.jupyter.org/node-purpose': 'user'
|
|
39
|
+
},
|
|
40
|
+
'automount_service_account_token': False
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
def __init__(self, config_file: Optional[str] = None):
|
|
44
|
+
self.config_file = config_file or self._find_config_file()
|
|
45
|
+
# Detect namespace before loading config so it can be used as default
|
|
46
|
+
self._detected_namespace = self._detect_namespace()
|
|
47
|
+
self.config = self._load_config()
|
|
48
|
+
|
|
49
|
+
def _find_config_file(self) -> str:
|
|
50
|
+
"""Find configuration file using fallback strategy"""
|
|
51
|
+
for config_dir in self.DEFAULT_CONFIG_DIRS:
|
|
52
|
+
config_path = os.path.join(config_dir, self.DEFAULT_CONFIG_FILE)
|
|
53
|
+
if os.path.exists(config_path):
|
|
54
|
+
return config_path
|
|
55
|
+
|
|
56
|
+
# Return first directory as default location
|
|
57
|
+
return os.path.join(self.DEFAULT_CONFIG_DIRS[0], self.DEFAULT_CONFIG_FILE)
|
|
58
|
+
|
|
59
|
+
def _load_config(self) -> Dict[str, Any]:
|
|
60
|
+
"""Load configuration from file or create default"""
|
|
61
|
+
if not os.path.exists(self.config_file):
|
|
62
|
+
self._create_default_config()
|
|
63
|
+
|
|
64
|
+
try:
|
|
65
|
+
with open(self.config_file, 'r') as f:
|
|
66
|
+
config = yaml.safe_load(f) or {}
|
|
67
|
+
except yaml.YAMLError as e:
|
|
68
|
+
raise ConfigurationError(f"Invalid YAML in config file {self.config_file}: {e}")
|
|
69
|
+
except IOError as e:
|
|
70
|
+
raise ConfigurationError(f"Cannot read config file {self.config_file}: {e}")
|
|
71
|
+
|
|
72
|
+
# Merge with defaults
|
|
73
|
+
merged_config = self.DEFAULT_CONFIG.copy()
|
|
74
|
+
merged_config.update(config)
|
|
75
|
+
|
|
76
|
+
# Auto-detect namespace if not set
|
|
77
|
+
if not merged_config.get('namespace'):
|
|
78
|
+
merged_config['namespace'] = self._detected_namespace
|
|
79
|
+
|
|
80
|
+
# Override with environment variables
|
|
81
|
+
self._apply_env_overrides(merged_config)
|
|
82
|
+
|
|
83
|
+
return merged_config
|
|
84
|
+
|
|
85
|
+
def _create_default_config(self) -> None:
|
|
86
|
+
"""Create default configuration file"""
|
|
87
|
+
config_dir = os.path.dirname(self.config_file)
|
|
88
|
+
os.makedirs(config_dir, exist_ok=True)
|
|
89
|
+
|
|
90
|
+
# Use detected namespace in default config
|
|
91
|
+
default_config = self.DEFAULT_CONFIG.copy()
|
|
92
|
+
default_config['namespace'] = self._detected_namespace
|
|
93
|
+
|
|
94
|
+
with open(self.config_file, 'w') as f:
|
|
95
|
+
yaml.dump(default_config, f, default_flow_style=False, indent=2)
|
|
96
|
+
|
|
97
|
+
def _apply_env_overrides(self, config: Dict[str, Any]) -> None:
|
|
98
|
+
"""Apply environment variable overrides"""
|
|
99
|
+
env_mappings = {
|
|
100
|
+
'KUBEXEC_DOCKER_IMAGE': 'docker_image',
|
|
101
|
+
'KUBEXEC_NAMESPACE': 'namespace',
|
|
102
|
+
'KUBEXEC_MEMORY': 'memory',
|
|
103
|
+
'KUBEXEC_CPU': 'cpu',
|
|
104
|
+
'KUBEXEC_WORKDIR': 'workdir',
|
|
105
|
+
'KUBEXEC_CLEANUP': 'cleanup',
|
|
106
|
+
'KUBEXEC_VERBOSE': 'verbose',
|
|
107
|
+
'KUBEXEC_TIMEOUT': 'timeout',
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
for env_var, config_key in env_mappings.items():
|
|
111
|
+
env_value = os.getenv(env_var)
|
|
112
|
+
if env_value is not None:
|
|
113
|
+
if config_key in ['cleanup', 'verbose']:
|
|
114
|
+
config[config_key] = env_value.lower() in ('true', '1', 'yes', 'on')
|
|
115
|
+
elif config_key == 'timeout':
|
|
116
|
+
config[config_key] = int(env_value)
|
|
117
|
+
else:
|
|
118
|
+
config[config_key] = env_value
|
|
119
|
+
|
|
120
|
+
def get(self, key: str, default: Any = None) -> Any:
|
|
121
|
+
"""Get configuration value"""
|
|
122
|
+
return self.config.get(key, default)
|
|
123
|
+
|
|
124
|
+
def update(self, updates: Dict[str, Any]) -> None:
|
|
125
|
+
"""Update configuration values"""
|
|
126
|
+
self.config.update(updates)
|
|
127
|
+
|
|
128
|
+
def _detect_namespace(self) -> str:
|
|
129
|
+
"""Auto-detect current namespace from service account or kubectl context"""
|
|
130
|
+
# Try service account namespace first (in-cluster)
|
|
131
|
+
try:
|
|
132
|
+
with open('/var/run/secrets/kubernetes.io/serviceaccount/namespace', 'r') as f:
|
|
133
|
+
namespace = f.read().strip()
|
|
134
|
+
if namespace:
|
|
135
|
+
return namespace
|
|
136
|
+
except (FileNotFoundError, IOError):
|
|
137
|
+
pass
|
|
138
|
+
|
|
139
|
+
# Try kubectl config
|
|
140
|
+
try:
|
|
141
|
+
import subprocess
|
|
142
|
+
result = subprocess.run(
|
|
143
|
+
['kubectl', 'config', 'view', '--minify', '--output', 'jsonpath={..namespace}'],
|
|
144
|
+
capture_output=True,
|
|
145
|
+
text=True,
|
|
146
|
+
timeout=10
|
|
147
|
+
)
|
|
148
|
+
if result.returncode == 0 and result.stdout.strip():
|
|
149
|
+
return result.stdout.strip()
|
|
150
|
+
except (subprocess.TimeoutExpired, subprocess.CalledProcessError, FileNotFoundError):
|
|
151
|
+
pass
|
|
152
|
+
|
|
153
|
+
# Default fallback
|
|
154
|
+
return 'default'
|
|
155
|
+
|
|
156
|
+
def save(self) -> None:
|
|
157
|
+
"""Save current configuration to file"""
|
|
158
|
+
with open(self.config_file, 'w') as f:
|
|
159
|
+
yaml.dump(self.config, f, default_flow_style=False, indent=2)
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""Custom exceptions for kubexec"""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class KubeExecError(Exception):
|
|
5
|
+
"""Base exception for kubexec"""
|
|
6
|
+
pass
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class KubernetesClientError(KubeExecError):
|
|
10
|
+
"""Kubernetes client operation failed"""
|
|
11
|
+
pass
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class JobExecutionError(KubeExecError):
|
|
15
|
+
"""Job execution failed"""
|
|
16
|
+
pass
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class ConfigurationError(KubeExecError):
|
|
20
|
+
"""Configuration error"""
|
|
21
|
+
pass
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class PodNotFoundError(KubeExecError):
|
|
25
|
+
"""Pod not found"""
|
|
26
|
+
pass
|