kubexec 0.2.0__py3-none-any.whl
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/__init__.py +12 -0
- kubexec/cli.py +250 -0
- kubexec/config.py +159 -0
- kubexec/exceptions.py +26 -0
- kubexec/executor.py +262 -0
- kubexec/k8s_client.py +249 -0
- kubexec/templates.py +154 -0
- kubexec/utils.py +67 -0
- kubexec-0.2.0.dist-info/METADATA +75 -0
- kubexec-0.2.0.dist-info/RECORD +14 -0
- kubexec-0.2.0.dist-info/WHEEL +5 -0
- kubexec-0.2.0.dist-info/entry_points.txt +2 -0
- kubexec-0.2.0.dist-info/top_level.txt +2 -0
- tests/__init__.py +1 -0
kubexec/__init__.py
ADDED
|
@@ -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"]
|
kubexec/cli.py
ADDED
|
@@ -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())
|
kubexec/config.py
ADDED
|
@@ -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)
|
kubexec/exceptions.py
ADDED
|
@@ -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
|
kubexec/executor.py
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
"""Command and script execution logic for kubexec"""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import logging
|
|
5
|
+
from typing import List, Optional, Dict, Any, Tuple
|
|
6
|
+
from .k8s_client import KubernetesClient
|
|
7
|
+
from .config import Config
|
|
8
|
+
from .utils import make_unique_name, is_script_file, parse_volume_mount, validate_resource_spec
|
|
9
|
+
from .exceptions import KubeExecError, JobExecutionError
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
logger = logging.getLogger(__name__)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class KubeExecutor:
|
|
16
|
+
"""Main executor for kubexec operations"""
|
|
17
|
+
|
|
18
|
+
def __init__(self, config: Config, k8s_client: Optional[KubernetesClient] = None):
|
|
19
|
+
self.config = config
|
|
20
|
+
self.k8s_client = k8s_client or KubernetesClient()
|
|
21
|
+
|
|
22
|
+
def execute(
|
|
23
|
+
self,
|
|
24
|
+
target: str,
|
|
25
|
+
docker_image: Optional[str] = None,
|
|
26
|
+
namespace: Optional[str] = None,
|
|
27
|
+
pod_name: Optional[str] = None,
|
|
28
|
+
memory: Optional[str] = None,
|
|
29
|
+
cpu: Optional[str] = None,
|
|
30
|
+
workdir: Optional[str] = None,
|
|
31
|
+
volume_mounts: Optional[List[str]] = None,
|
|
32
|
+
create_pod: bool = False,
|
|
33
|
+
cleanup: Optional[bool] = None,
|
|
34
|
+
dry_run: bool = False,
|
|
35
|
+
**kwargs
|
|
36
|
+
) -> Tuple[int, str]:
|
|
37
|
+
"""Execute target command or script"""
|
|
38
|
+
|
|
39
|
+
# Use config defaults, override with parameters
|
|
40
|
+
image = docker_image or self.config.get('docker_image')
|
|
41
|
+
ns = namespace or self.config.get('namespace')
|
|
42
|
+
mem = validate_resource_spec(memory or self.config.get('memory'), 'memory')
|
|
43
|
+
cpu_limit = validate_resource_spec(cpu or self.config.get('cpu'), 'cpu')
|
|
44
|
+
work_dir = workdir or self.config.get('workdir')
|
|
45
|
+
should_cleanup = cleanup if cleanup is not None else self.config.get('cleanup')
|
|
46
|
+
|
|
47
|
+
# Determine execution strategy
|
|
48
|
+
if pod_name and not create_pod and self.k8s_client.pod_exists(pod_name, ns):
|
|
49
|
+
return self._execute_in_existing_pod(target, pod_name, ns, dry_run)
|
|
50
|
+
else:
|
|
51
|
+
return self._execute_in_new_job(
|
|
52
|
+
target, image, ns, mem, cpu_limit, work_dir,
|
|
53
|
+
volume_mounts, should_cleanup, dry_run, **kwargs
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
def _execute_in_existing_pod(
|
|
57
|
+
self,
|
|
58
|
+
target: str,
|
|
59
|
+
pod_name: str,
|
|
60
|
+
namespace: str,
|
|
61
|
+
dry_run: bool
|
|
62
|
+
) -> Tuple[int, str]:
|
|
63
|
+
"""Execute command in existing pod"""
|
|
64
|
+
|
|
65
|
+
# Note: For existing pods, we can't mount volumes, so we work in the current directory
|
|
66
|
+
if is_script_file(target):
|
|
67
|
+
# For script files, we need to copy the script to the pod first
|
|
68
|
+
script_content = self._read_script_file(target)
|
|
69
|
+
script_name = os.path.basename(target)
|
|
70
|
+
command = ["/bin/bash", "-c", f"cat << 'EOF' > /tmp/{script_name}\n{script_content}\nEOF\nchmod +x /tmp/{script_name} && /tmp/{script_name}"]
|
|
71
|
+
else:
|
|
72
|
+
# Direct command execution in existing pod
|
|
73
|
+
command = ["/bin/bash", "-c", target]
|
|
74
|
+
|
|
75
|
+
if dry_run:
|
|
76
|
+
return 0, f"Would execute in pod {pod_name}: {' '.join(command)}"
|
|
77
|
+
|
|
78
|
+
logger.info(f"Executing in existing pod: {pod_name}")
|
|
79
|
+
return self.k8s_client.execute_in_existing_pod(pod_name, command, namespace)
|
|
80
|
+
|
|
81
|
+
def _execute_in_new_job(
|
|
82
|
+
self,
|
|
83
|
+
target: str,
|
|
84
|
+
image: str,
|
|
85
|
+
namespace: str,
|
|
86
|
+
memory: str,
|
|
87
|
+
cpu: str,
|
|
88
|
+
workdir: str,
|
|
89
|
+
volume_mounts: Optional[List[str]],
|
|
90
|
+
cleanup: bool,
|
|
91
|
+
dry_run: bool,
|
|
92
|
+
**kwargs
|
|
93
|
+
) -> Tuple[int, str]:
|
|
94
|
+
"""Execute command in new Kubernetes job"""
|
|
95
|
+
|
|
96
|
+
job_name = make_unique_name("kubexec-job")
|
|
97
|
+
|
|
98
|
+
# Prepare command and volumes
|
|
99
|
+
command, volumes, volume_mount_specs = self._prepare_execution(target, job_name, namespace, volume_mounts)
|
|
100
|
+
|
|
101
|
+
if dry_run:
|
|
102
|
+
return 0, f"Would create job {job_name} with image {image}: {' '.join(command)}"
|
|
103
|
+
|
|
104
|
+
try:
|
|
105
|
+
# Create job
|
|
106
|
+
logger.info(f"Creating job: {job_name}")
|
|
107
|
+
self.k8s_client.create_job(
|
|
108
|
+
name=job_name,
|
|
109
|
+
image=image,
|
|
110
|
+
command=command,
|
|
111
|
+
namespace=namespace,
|
|
112
|
+
memory=memory,
|
|
113
|
+
cpu=cpu,
|
|
114
|
+
workdir=workdir,
|
|
115
|
+
volumes=volumes,
|
|
116
|
+
volume_mounts=volume_mount_specs,
|
|
117
|
+
security_context=self.config.get('security_context'),
|
|
118
|
+
ttl_seconds_after_finished=self.config.get('ttl_seconds_after_finished', 60),
|
|
119
|
+
node_selector=self.config.get('node_selector'),
|
|
120
|
+
automount_service_account_token=self.config.get('automount_service_account_token', False),
|
|
121
|
+
**kwargs
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
# Wait for completion
|
|
125
|
+
logger.info(f"Waiting for job completion: {job_name}")
|
|
126
|
+
exit_code, logs = self.k8s_client.wait_for_job_completion(
|
|
127
|
+
job_name, namespace, timeout=self.config.get('timeout', 3600)
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
return exit_code, logs
|
|
131
|
+
|
|
132
|
+
except Exception as e:
|
|
133
|
+
logger.error(f"Job execution failed: {e}")
|
|
134
|
+
raise JobExecutionError(f"Job execution failed: {e}")
|
|
135
|
+
|
|
136
|
+
finally:
|
|
137
|
+
if cleanup:
|
|
138
|
+
try:
|
|
139
|
+
logger.info(f"Cleaning up job: {job_name}")
|
|
140
|
+
self.k8s_client.cleanup_job(job_name, namespace)
|
|
141
|
+
except Exception as e:
|
|
142
|
+
logger.warning(f"Failed to cleanup job {job_name}: {e}")
|
|
143
|
+
|
|
144
|
+
def _prepare_execution(
|
|
145
|
+
self,
|
|
146
|
+
target: str,
|
|
147
|
+
job_name: str,
|
|
148
|
+
namespace: str,
|
|
149
|
+
volume_mounts: Optional[List[str]]
|
|
150
|
+
) -> Tuple[List[str], List[Dict[str, Any]], List[Dict[str, Any]]]:
|
|
151
|
+
"""Prepare command, volumes, and volume mounts for execution"""
|
|
152
|
+
|
|
153
|
+
volumes = []
|
|
154
|
+
volume_mount_specs = []
|
|
155
|
+
|
|
156
|
+
# Add shared volumes by default
|
|
157
|
+
from .templates import create_shared_volumes, create_shared_volume_mounts
|
|
158
|
+
volumes.extend(create_shared_volumes())
|
|
159
|
+
volume_mount_specs.extend(create_shared_volume_mounts())
|
|
160
|
+
|
|
161
|
+
# Determine kubexec entry path within shared volumes
|
|
162
|
+
import os
|
|
163
|
+
current_dir = os.getcwd()
|
|
164
|
+
|
|
165
|
+
# Map current directory to container path using shared volumes
|
|
166
|
+
if current_dir.startswith('/shared/team'):
|
|
167
|
+
# Already in shared team directory
|
|
168
|
+
kubexec_entry_path = current_dir.replace('/shared/team', '/shared/team')
|
|
169
|
+
elif current_dir.startswith('/shared/public'):
|
|
170
|
+
# In shared public directory
|
|
171
|
+
kubexec_entry_path = current_dir.replace('/shared/public', '/shared/public')
|
|
172
|
+
else:
|
|
173
|
+
# Default to shared team directory
|
|
174
|
+
kubexec_entry_path = '/shared/team'
|
|
175
|
+
|
|
176
|
+
# Add custom volume mounts
|
|
177
|
+
if volume_mounts:
|
|
178
|
+
for vm_spec in volume_mounts:
|
|
179
|
+
host_path, pod_path, readonly = parse_volume_mount(vm_spec)
|
|
180
|
+
|
|
181
|
+
# Create hostPath volume
|
|
182
|
+
volume_name = f"custom-volume-{len(volumes)}"
|
|
183
|
+
volumes.append({
|
|
184
|
+
'name': volume_name,
|
|
185
|
+
'hostPath': {'path': host_path}
|
|
186
|
+
})
|
|
187
|
+
|
|
188
|
+
volume_mount_specs.append({
|
|
189
|
+
'name': volume_name,
|
|
190
|
+
'mountPath': pod_path,
|
|
191
|
+
'readOnly': readonly
|
|
192
|
+
})
|
|
193
|
+
|
|
194
|
+
# Prepare command
|
|
195
|
+
if is_script_file(target):
|
|
196
|
+
script_content = self._read_script_file(target)
|
|
197
|
+
script_name = os.path.basename(target)
|
|
198
|
+
|
|
199
|
+
# Embed script content directly in command instead of using ConfigMap
|
|
200
|
+
# This avoids permission issues with ConfigMap creation
|
|
201
|
+
command = [
|
|
202
|
+
"/bin/bash", "-c",
|
|
203
|
+
f"cd {kubexec_entry_path} && cat << 'KUBEXEC_SCRIPT_EOF' > /tmp/{script_name}\n{script_content}\nKUBEXEC_SCRIPT_EOF\nchmod +x /tmp/{script_name} && /tmp/{script_name}"
|
|
204
|
+
]
|
|
205
|
+
else:
|
|
206
|
+
# Direct command execution - change to entry directory first
|
|
207
|
+
command = ["/bin/bash", "-c", f"cd {kubexec_entry_path} && {target}"]
|
|
208
|
+
|
|
209
|
+
return command, volumes, volume_mount_specs
|
|
210
|
+
|
|
211
|
+
def _read_script_file(self, file_path: str) -> str:
|
|
212
|
+
"""Read script file content"""
|
|
213
|
+
try:
|
|
214
|
+
with open(file_path, 'r') as f:
|
|
215
|
+
return f.read()
|
|
216
|
+
except IOError as e:
|
|
217
|
+
raise KubeExecError(f"Failed to read script file {file_path}: {e}")
|
|
218
|
+
|
|
219
|
+
def list_jobs(self, namespace: str = "default") -> List[Dict[str, Any]]:
|
|
220
|
+
"""List kubexec jobs in namespace"""
|
|
221
|
+
try:
|
|
222
|
+
jobs = self.batch_v1.list_namespaced_job(
|
|
223
|
+
namespace=namespace,
|
|
224
|
+
label_selector="app=kubexec"
|
|
225
|
+
)
|
|
226
|
+
|
|
227
|
+
job_list = []
|
|
228
|
+
for job in jobs.items:
|
|
229
|
+
job_info = {
|
|
230
|
+
'name': job.metadata.name,
|
|
231
|
+
'status': 'completed' if job.status.succeeded else 'failed' if job.status.failed else 'running',
|
|
232
|
+
'created': job.metadata.creation_timestamp,
|
|
233
|
+
'image': job.spec.template.spec.containers[0].image if job.spec.template.spec.containers else 'unknown'
|
|
234
|
+
}
|
|
235
|
+
job_list.append(job_info)
|
|
236
|
+
|
|
237
|
+
return job_list
|
|
238
|
+
|
|
239
|
+
except ApiException as e:
|
|
240
|
+
raise KubernetesClientError(f"Failed to list jobs: {e}")
|
|
241
|
+
|
|
242
|
+
def cleanup_old_jobs(self, namespace: str = "default", max_age_hours: int = 24) -> int:
|
|
243
|
+
"""Cleanup old kubexec jobs"""
|
|
244
|
+
try:
|
|
245
|
+
import datetime
|
|
246
|
+
cutoff_time = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(hours=max_age_hours)
|
|
247
|
+
|
|
248
|
+
jobs = self.batch_v1.list_namespaced_job(
|
|
249
|
+
namespace=namespace,
|
|
250
|
+
label_selector="app=kubexec"
|
|
251
|
+
)
|
|
252
|
+
|
|
253
|
+
cleaned_count = 0
|
|
254
|
+
for job in jobs.items:
|
|
255
|
+
if job.metadata.creation_timestamp < cutoff_time:
|
|
256
|
+
self.k8s_client.cleanup_job(job.metadata.name, namespace)
|
|
257
|
+
cleaned_count += 1
|
|
258
|
+
|
|
259
|
+
return cleaned_count
|
|
260
|
+
|
|
261
|
+
except ApiException as e:
|
|
262
|
+
raise KubernetesClientError(f"Failed to cleanup old jobs: {e}")
|
kubexec/k8s_client.py
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
"""Kubernetes client operations for kubexec"""
|
|
2
|
+
|
|
3
|
+
import time
|
|
4
|
+
import logging
|
|
5
|
+
from typing import List, Tuple, Optional, Dict, Any
|
|
6
|
+
from kubernetes import client, config
|
|
7
|
+
from kubernetes.client.rest import ApiException
|
|
8
|
+
from .exceptions import KubernetesClientError, JobExecutionError, PodNotFoundError
|
|
9
|
+
from .templates import create_job_template, create_configmap_template
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
logger = logging.getLogger(__name__)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class KubernetesClient:
|
|
16
|
+
"""Kubernetes client wrapper for kubexec operations"""
|
|
17
|
+
|
|
18
|
+
def __init__(self, context: Optional[str] = None):
|
|
19
|
+
"""Initialize Kubernetes client"""
|
|
20
|
+
try:
|
|
21
|
+
# Disable SSL verification warnings for self-signed certificates
|
|
22
|
+
import urllib3
|
|
23
|
+
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
|
|
24
|
+
|
|
25
|
+
if context:
|
|
26
|
+
config.load_kube_config(context=context)
|
|
27
|
+
else:
|
|
28
|
+
# Try in-cluster config first, then kube config
|
|
29
|
+
try:
|
|
30
|
+
config.load_incluster_config()
|
|
31
|
+
except config.ConfigException:
|
|
32
|
+
try:
|
|
33
|
+
config.load_kube_config()
|
|
34
|
+
except config.ConfigException:
|
|
35
|
+
# If no kubeconfig exists, try to use service account
|
|
36
|
+
logger.warning("No kubeconfig found, using service account authentication")
|
|
37
|
+
config.load_incluster_config()
|
|
38
|
+
|
|
39
|
+
# Configure client for potential SSL issues
|
|
40
|
+
configuration = client.Configuration.get_default_copy()
|
|
41
|
+
if hasattr(configuration, 'verify_ssl'):
|
|
42
|
+
configuration.verify_ssl = False
|
|
43
|
+
|
|
44
|
+
self.batch_v1 = client.BatchV1Api(client.ApiClient(configuration))
|
|
45
|
+
self.core_v1 = client.CoreV1Api(client.ApiClient(configuration))
|
|
46
|
+
self.apps_v1 = client.AppsV1Api(client.ApiClient(configuration))
|
|
47
|
+
|
|
48
|
+
except Exception as e:
|
|
49
|
+
raise KubernetesClientError(f"Failed to initialize Kubernetes client: {e}")
|
|
50
|
+
|
|
51
|
+
def get_pods(self, namespace: str = "default") -> List[str]:
|
|
52
|
+
"""Get list of pod names in namespace"""
|
|
53
|
+
try:
|
|
54
|
+
pods = self.core_v1.list_namespaced_pod(namespace=namespace)
|
|
55
|
+
return [pod.metadata.name for pod in pods.items]
|
|
56
|
+
except ApiException as e:
|
|
57
|
+
raise KubernetesClientError(f"Failed to list pods: {e}")
|
|
58
|
+
|
|
59
|
+
def pod_exists(self, pod_name: str, namespace: str = "default") -> bool:
|
|
60
|
+
"""Check if pod exists"""
|
|
61
|
+
try:
|
|
62
|
+
self.core_v1.read_namespaced_pod(name=pod_name, namespace=namespace)
|
|
63
|
+
return True
|
|
64
|
+
except ApiException as e:
|
|
65
|
+
if e.status == 404:
|
|
66
|
+
return False
|
|
67
|
+
raise KubernetesClientError(f"Failed to check pod existence: {e}")
|
|
68
|
+
|
|
69
|
+
def create_configmap(self, name: str, namespace: str, script_content: str, script_name: str = "script.sh") -> str:
|
|
70
|
+
"""Create ConfigMap with script content"""
|
|
71
|
+
try:
|
|
72
|
+
configmap_template = create_configmap_template(name, namespace, script_content, script_name)
|
|
73
|
+
self.core_v1.create_namespaced_config_map(
|
|
74
|
+
namespace=namespace,
|
|
75
|
+
body=configmap_template
|
|
76
|
+
)
|
|
77
|
+
return name
|
|
78
|
+
except ApiException as e:
|
|
79
|
+
raise KubernetesClientError(f"Failed to create ConfigMap: {e}")
|
|
80
|
+
|
|
81
|
+
def create_job(
|
|
82
|
+
self,
|
|
83
|
+
name: str,
|
|
84
|
+
image: str,
|
|
85
|
+
command: List[str],
|
|
86
|
+
namespace: str = "default",
|
|
87
|
+
**kwargs
|
|
88
|
+
) -> str:
|
|
89
|
+
"""Create Kubernetes Job"""
|
|
90
|
+
try:
|
|
91
|
+
job_template = create_job_template(
|
|
92
|
+
name=name,
|
|
93
|
+
image=image,
|
|
94
|
+
command=command,
|
|
95
|
+
namespace=namespace,
|
|
96
|
+
**kwargs
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
self.batch_v1.create_namespaced_job(
|
|
100
|
+
namespace=namespace,
|
|
101
|
+
body=job_template
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
logger.info(f"Created job: {name}")
|
|
105
|
+
return name
|
|
106
|
+
|
|
107
|
+
except ApiException as e:
|
|
108
|
+
raise KubernetesClientError(f"Failed to create job: {e}")
|
|
109
|
+
|
|
110
|
+
def wait_for_job_completion(self, job_name: str, namespace: str = "default", timeout: int = 3600) -> Tuple[int, str]:
|
|
111
|
+
"""Wait for job completion and return exit code and logs"""
|
|
112
|
+
start_time = time.time()
|
|
113
|
+
image_pull_check_done = False
|
|
114
|
+
|
|
115
|
+
while time.time() - start_time < timeout:
|
|
116
|
+
try:
|
|
117
|
+
job = self.batch_v1.read_namespaced_job(name=job_name, namespace=namespace)
|
|
118
|
+
|
|
119
|
+
if job.status.succeeded:
|
|
120
|
+
logs = self.get_job_logs(job_name, namespace)
|
|
121
|
+
return 0, logs
|
|
122
|
+
elif job.status.failed:
|
|
123
|
+
logs = self.get_job_logs(job_name, namespace)
|
|
124
|
+
return 1, logs
|
|
125
|
+
|
|
126
|
+
# Check for image pull issues early
|
|
127
|
+
if not image_pull_check_done and time.time() - start_time > 30:
|
|
128
|
+
pod_status = self._check_pod_image_pull_status(job_name, namespace)
|
|
129
|
+
if pod_status == "ImagePullBackOff":
|
|
130
|
+
raise JobExecutionError(f"Job {job_name} failed: Cannot pull Docker image. Check image name and registry access.")
|
|
131
|
+
elif pod_status == "ErrImagePull":
|
|
132
|
+
raise JobExecutionError(f"Job {job_name} failed: Image pull error. Verify image exists and is accessible.")
|
|
133
|
+
image_pull_check_done = True
|
|
134
|
+
|
|
135
|
+
time.sleep(2)
|
|
136
|
+
|
|
137
|
+
except ApiException as e:
|
|
138
|
+
raise KubernetesClientError(f"Failed to check job status: {e}")
|
|
139
|
+
|
|
140
|
+
raise JobExecutionError(f"Job {job_name} timed out after {timeout} seconds")
|
|
141
|
+
|
|
142
|
+
def get_job_logs(self, job_name: str, namespace: str = "default") -> str:
|
|
143
|
+
"""Get logs from job's pod"""
|
|
144
|
+
try:
|
|
145
|
+
# Find pod created by the job
|
|
146
|
+
pods = self.core_v1.list_namespaced_pod(
|
|
147
|
+
namespace=namespace,
|
|
148
|
+
label_selector=f"job-name={job_name}"
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
if not pods.items:
|
|
152
|
+
return "No pod found for job"
|
|
153
|
+
|
|
154
|
+
pod_name = pods.items[0].metadata.name
|
|
155
|
+
logs = self.core_v1.read_namespaced_pod_log(
|
|
156
|
+
name=pod_name,
|
|
157
|
+
namespace=namespace,
|
|
158
|
+
container="kubexec-container"
|
|
159
|
+
)
|
|
160
|
+
return logs
|
|
161
|
+
|
|
162
|
+
except ApiException as e:
|
|
163
|
+
logger.warning(f"Failed to get job logs: {e}")
|
|
164
|
+
return f"Failed to retrieve logs: {e}"
|
|
165
|
+
|
|
166
|
+
def cleanup_job(self, job_name: str, namespace: str = "default") -> None:
|
|
167
|
+
"""Delete job and associated resources"""
|
|
168
|
+
try:
|
|
169
|
+
# Delete job (this will also delete associated pods)
|
|
170
|
+
self.batch_v1.delete_namespaced_job(
|
|
171
|
+
name=job_name,
|
|
172
|
+
namespace=namespace,
|
|
173
|
+
body=client.V1DeleteOptions(
|
|
174
|
+
propagation_policy="Foreground"
|
|
175
|
+
)
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
# Delete ConfigMap if it exists
|
|
179
|
+
try:
|
|
180
|
+
self.core_v1.delete_namespaced_config_map(
|
|
181
|
+
name=f"{job_name}-script",
|
|
182
|
+
namespace=namespace
|
|
183
|
+
)
|
|
184
|
+
except ApiException:
|
|
185
|
+
pass # ConfigMap might not exist
|
|
186
|
+
|
|
187
|
+
logger.info(f"Cleaned up job: {job_name}")
|
|
188
|
+
|
|
189
|
+
except ApiException as e:
|
|
190
|
+
raise KubernetesClientError(f"Failed to cleanup job: {e}")
|
|
191
|
+
|
|
192
|
+
def execute_in_existing_pod(
|
|
193
|
+
self,
|
|
194
|
+
pod_name: str,
|
|
195
|
+
command: List[str],
|
|
196
|
+
namespace: str = "default",
|
|
197
|
+
container: Optional[str] = None
|
|
198
|
+
) -> Tuple[int, str]:
|
|
199
|
+
"""Execute command in existing pod"""
|
|
200
|
+
try:
|
|
201
|
+
if not self.pod_exists(pod_name, namespace):
|
|
202
|
+
raise PodNotFoundError(f"Pod {pod_name} not found in namespace {namespace}")
|
|
203
|
+
|
|
204
|
+
# Use kubectl exec through subprocess as kubernetes client doesn't support exec well
|
|
205
|
+
import subprocess
|
|
206
|
+
|
|
207
|
+
kubectl_cmd = ["kubectl", "exec", "-n", namespace, pod_name]
|
|
208
|
+
if container:
|
|
209
|
+
kubectl_cmd.extend(["-c", container])
|
|
210
|
+
kubectl_cmd.extend(["--"] + command)
|
|
211
|
+
|
|
212
|
+
result = subprocess.run(
|
|
213
|
+
kubectl_cmd,
|
|
214
|
+
capture_output=True,
|
|
215
|
+
text=True,
|
|
216
|
+
timeout=3600
|
|
217
|
+
)
|
|
218
|
+
|
|
219
|
+
return result.returncode, result.stdout + result.stderr
|
|
220
|
+
|
|
221
|
+
except subprocess.TimeoutExpired:
|
|
222
|
+
raise JobExecutionError("Command execution timed out")
|
|
223
|
+
except Exception as e:
|
|
224
|
+
raise KubernetesClientError(f"Failed to execute in pod: {e}")
|
|
225
|
+
|
|
226
|
+
def _check_pod_image_pull_status(self, job_name: str, namespace: str) -> Optional[str]:
|
|
227
|
+
"""Check if pod has image pull issues"""
|
|
228
|
+
try:
|
|
229
|
+
pods = self.core_v1.list_namespaced_pod(
|
|
230
|
+
namespace=namespace,
|
|
231
|
+
label_selector=f"job-name={job_name}"
|
|
232
|
+
)
|
|
233
|
+
|
|
234
|
+
if not pods.items:
|
|
235
|
+
return None
|
|
236
|
+
|
|
237
|
+
pod = pods.items[0]
|
|
238
|
+
|
|
239
|
+
# Check container status
|
|
240
|
+
if pod.status.container_statuses:
|
|
241
|
+
for container_status in pod.status.container_statuses:
|
|
242
|
+
if container_status.state.waiting:
|
|
243
|
+
return container_status.state.waiting.reason
|
|
244
|
+
|
|
245
|
+
return None
|
|
246
|
+
|
|
247
|
+
except ApiException as e:
|
|
248
|
+
logger.warning(f"Failed to check pod image pull status: {e}")
|
|
249
|
+
return None
|
kubexec/templates.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
"""Kubernetes YAML templates for kubexec"""
|
|
2
|
+
|
|
3
|
+
from typing import Dict, List, Any, Optional
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def create_job_template(
|
|
7
|
+
name: str,
|
|
8
|
+
image: str,
|
|
9
|
+
command: List[str],
|
|
10
|
+
namespace: str = "default",
|
|
11
|
+
memory: str = "1Gi",
|
|
12
|
+
cpu: str = "1",
|
|
13
|
+
workdir: str = "/tmp",
|
|
14
|
+
volume_mounts: Optional[List[Dict[str, Any]]] = None,
|
|
15
|
+
volumes: Optional[List[Dict[str, Any]]] = None,
|
|
16
|
+
security_context: Optional[Dict[str, Any]] = None,
|
|
17
|
+
env_vars: Optional[List[Dict[str, str]]] = None,
|
|
18
|
+
restart_policy: str = "Never",
|
|
19
|
+
backoff_limit: int = 0,
|
|
20
|
+
ttl_seconds_after_finished: int = 60,
|
|
21
|
+
node_selector: Optional[Dict[str, str]] = None,
|
|
22
|
+
automount_service_account_token: bool = False
|
|
23
|
+
) -> Dict[str, Any]:
|
|
24
|
+
"""Create a Kubernetes Job template"""
|
|
25
|
+
|
|
26
|
+
if security_context is None:
|
|
27
|
+
security_context = {
|
|
28
|
+
'fsGroup': 1000,
|
|
29
|
+
'runAsUser': 1000,
|
|
30
|
+
'runAsGroup': 1000,
|
|
31
|
+
'fsGroupChangePolicy': 'OnRootMismatch'
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
container_spec = {
|
|
35
|
+
'name': 'kubexec-container',
|
|
36
|
+
'image': image,
|
|
37
|
+
'command': command,
|
|
38
|
+
'workingDir': workdir,
|
|
39
|
+
'resources': {
|
|
40
|
+
'limits': {
|
|
41
|
+
'memory': memory,
|
|
42
|
+
'cpu': cpu
|
|
43
|
+
},
|
|
44
|
+
'requests': {
|
|
45
|
+
'memory': memory,
|
|
46
|
+
'cpu': cpu
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
if volume_mounts:
|
|
52
|
+
container_spec['volumeMounts'] = volume_mounts
|
|
53
|
+
|
|
54
|
+
if env_vars:
|
|
55
|
+
container_spec['env'] = env_vars
|
|
56
|
+
|
|
57
|
+
pod_spec = {
|
|
58
|
+
'restartPolicy': restart_policy,
|
|
59
|
+
'securityContext': security_context,
|
|
60
|
+
'automountServiceAccountToken': automount_service_account_token,
|
|
61
|
+
'containers': [container_spec]
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
if node_selector:
|
|
65
|
+
pod_spec['nodeSelector'] = node_selector
|
|
66
|
+
|
|
67
|
+
if volumes:
|
|
68
|
+
pod_spec['volumes'] = volumes
|
|
69
|
+
|
|
70
|
+
job_template = {
|
|
71
|
+
'apiVersion': 'batch/v1',
|
|
72
|
+
'kind': 'Job',
|
|
73
|
+
'metadata': {
|
|
74
|
+
'name': name,
|
|
75
|
+
'namespace': namespace,
|
|
76
|
+
'labels': {
|
|
77
|
+
'app': 'kubexec',
|
|
78
|
+
'created-by': 'kubexec'
|
|
79
|
+
}
|
|
80
|
+
},
|
|
81
|
+
'spec': {
|
|
82
|
+
'backoffLimit': backoff_limit,
|
|
83
|
+
'ttlSecondsAfterFinished': ttl_seconds_after_finished,
|
|
84
|
+
'template': {
|
|
85
|
+
'metadata': {
|
|
86
|
+
'labels': {
|
|
87
|
+
'app': 'kubexec',
|
|
88
|
+
'job': name
|
|
89
|
+
}
|
|
90
|
+
},
|
|
91
|
+
'spec': pod_spec
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
return job_template
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def create_configmap_template(
|
|
100
|
+
name: str,
|
|
101
|
+
namespace: str,
|
|
102
|
+
script_content: str,
|
|
103
|
+
script_name: str = "script.sh"
|
|
104
|
+
) -> Dict[str, Any]:
|
|
105
|
+
"""Create a ConfigMap template for script storage"""
|
|
106
|
+
|
|
107
|
+
return {
|
|
108
|
+
'apiVersion': 'v1',
|
|
109
|
+
'kind': 'ConfigMap',
|
|
110
|
+
'metadata': {
|
|
111
|
+
'name': name,
|
|
112
|
+
'namespace': namespace,
|
|
113
|
+
'labels': {
|
|
114
|
+
'app': 'kubexec',
|
|
115
|
+
'created-by': 'kubexec'
|
|
116
|
+
}
|
|
117
|
+
},
|
|
118
|
+
'data': {
|
|
119
|
+
script_name: script_content
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def create_shared_volumes() -> List[Dict[str, Any]]:
|
|
125
|
+
"""Create shared volume configurations based on cluster setup"""
|
|
126
|
+
return [
|
|
127
|
+
{
|
|
128
|
+
'name': 'shared-team-volume',
|
|
129
|
+
'persistentVolumeClaim': {
|
|
130
|
+
'claimName': 'cephfs-shared-team'
|
|
131
|
+
}
|
|
132
|
+
},
|
|
133
|
+
{
|
|
134
|
+
'name': 'shared-public-volume',
|
|
135
|
+
'persistentVolumeClaim': {
|
|
136
|
+
'claimName': 'cephfs-shared-ro-public'
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
]
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def create_shared_volume_mounts() -> List[Dict[str, Any]]:
|
|
143
|
+
"""Create shared volume mount configurations"""
|
|
144
|
+
return [
|
|
145
|
+
{
|
|
146
|
+
'name': 'shared-team-volume',
|
|
147
|
+
'mountPath': '/shared/team'
|
|
148
|
+
},
|
|
149
|
+
{
|
|
150
|
+
'name': 'shared-public-volume',
|
|
151
|
+
'mountPath': '/shared/public',
|
|
152
|
+
'readOnly': True
|
|
153
|
+
}
|
|
154
|
+
]
|
kubexec/utils.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""Utility functions for kubexec"""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import random
|
|
5
|
+
import string
|
|
6
|
+
import time
|
|
7
|
+
from typing import Tuple
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def make_unique_name(base_name: str = "kubexec") -> str:
|
|
11
|
+
"""Generate a unique name for pods/jobs with collision avoidance"""
|
|
12
|
+
timestamp = int(time.time())
|
|
13
|
+
random_suffix = ''.join(random.choices(string.ascii_lowercase + string.digits, k=6))
|
|
14
|
+
return f"{base_name}-{timestamp}-{random_suffix}"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def make_unique_filename(filename: str, ext: str = "") -> str:
|
|
18
|
+
"""Generate a unique filename with collision avoidance"""
|
|
19
|
+
base = os.path.splitext(filename)[0]
|
|
20
|
+
if not ext:
|
|
21
|
+
ext = os.path.splitext(filename)[1]
|
|
22
|
+
|
|
23
|
+
timestamp = int(time.time())
|
|
24
|
+
random_suffix = ''.join(random.choices(string.ascii_lowercase + string.digits, k=4))
|
|
25
|
+
return f"{base}-{timestamp}-{random_suffix}{ext}"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def is_script_file(target: str) -> bool:
|
|
29
|
+
"""Detect if target is a script file vs command string"""
|
|
30
|
+
return (
|
|
31
|
+
os.path.exists(target) and
|
|
32
|
+
(target.endswith(('.sh', '.py', '.pl', '.R', '.rb', '.js')) or
|
|
33
|
+
os.access(target, os.X_OK))
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def parse_volume_mount(volume_spec: str) -> Tuple[str, str, bool]:
|
|
38
|
+
"""Parse volume mount specification: host_path:pod_path[:ro]"""
|
|
39
|
+
parts = volume_spec.split(':')
|
|
40
|
+
if len(parts) < 2:
|
|
41
|
+
raise ValueError(f"Invalid volume spec: {volume_spec}. Expected format: host_path:pod_path[:ro]")
|
|
42
|
+
|
|
43
|
+
host_path = parts[0]
|
|
44
|
+
pod_path = parts[1]
|
|
45
|
+
readonly = len(parts) > 2 and parts[2] == "ro"
|
|
46
|
+
|
|
47
|
+
return host_path, pod_path, readonly
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def validate_resource_spec(resource: str, resource_type: str) -> str:
|
|
51
|
+
"""Validate resource specification (memory/CPU)"""
|
|
52
|
+
if resource_type == "memory":
|
|
53
|
+
if not any(resource.endswith(unit) for unit in ['Mi', 'Gi', 'Ti', 'm', 'k', 'M', 'G', 'T']):
|
|
54
|
+
# Add default unit if none specified
|
|
55
|
+
if resource.isdigit():
|
|
56
|
+
return f"{resource}Mi"
|
|
57
|
+
raise ValueError(f"Invalid memory spec: {resource}")
|
|
58
|
+
elif resource_type == "cpu":
|
|
59
|
+
try:
|
|
60
|
+
float(resource)
|
|
61
|
+
return resource
|
|
62
|
+
except ValueError:
|
|
63
|
+
if resource.endswith('m'):
|
|
64
|
+
return resource
|
|
65
|
+
raise ValueError(f"Invalid CPU spec: {resource}")
|
|
66
|
+
|
|
67
|
+
return resource
|
|
@@ -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
|
+
```
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
kubexec/__init__.py,sha256=NsoCYFDlMoKHRBMZt7_1J5sxZ8i4nhBjTDyEfJzbyAE,266
|
|
2
|
+
kubexec/cli.py,sha256=tVH2BeRzr7DswAE9z73xmlRZOmE45g3MXntFdPnXvfw,6949
|
|
3
|
+
kubexec/config.py,sha256=90DQ4dop1sYDsB2OcO5km-JDsxzt0u3FnRaLyTHIhZg,5997
|
|
4
|
+
kubexec/exceptions.py,sha256=LS0hiPvaBmvxskXrbYKUaI3IMmx8j6VldSFXyuTrTmE,453
|
|
5
|
+
kubexec/executor.py,sha256=cp5XsfOtLaq_2zkqm5qmlvLHiIlLhIX6uz6kh47bO5A,10410
|
|
6
|
+
kubexec/k8s_client.py,sha256=NGv3AJ-oQBS1o51jStn3nR1Cy307HCeejzEaR0eIRcY,9861
|
|
7
|
+
kubexec/templates.py,sha256=TFyaU2B9XYpXT6XEzAight9vymXS60oERICLYFkXVx0,4010
|
|
8
|
+
kubexec/utils.py,sha256=AKfpKB4-vwYYrN6oNDC6jK-6aVdX0g4OrJ4_Si_xtQM,2285
|
|
9
|
+
tests/__init__.py,sha256=q20dakDJw394pHnDQGxHDwOI5qoBgEAAQRSvCjpYZjk,31
|
|
10
|
+
kubexec-0.2.0.dist-info/METADATA,sha256=WKCc6IC9PkL321Iy3RJygd8toLpgwf952vFrsbsB8wo,2091
|
|
11
|
+
kubexec-0.2.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
12
|
+
kubexec-0.2.0.dist-info/entry_points.txt,sha256=8fK5qjKMkbdkenQL3z55_I6bD4tXZWEevuG1UGxxqig,45
|
|
13
|
+
kubexec-0.2.0.dist-info/top_level.txt,sha256=kYYHI68o66fs6-cNSU_j1P7M-HxmmXOK6Me2P3gFhv0,14
|
|
14
|
+
kubexec-0.2.0.dist-info/RECORD,,
|
tests/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Tests for kubexec package"""
|