lam-cli 0.1.4__tar.gz → 0.1.7__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.
- {lam_cli-0.1.4/lam_cli.egg-info → lam_cli-0.1.7}/PKG-INFO +1 -1
- {lam_cli-0.1.4 → lam_cli-0.1.7}/lam/lam.py +430 -2
- {lam_cli-0.1.4 → lam_cli-0.1.7/lam_cli.egg-info}/PKG-INFO +1 -1
- {lam_cli-0.1.4 → lam_cli-0.1.7}/setup.py +1 -1
- {lam_cli-0.1.4 → lam_cli-0.1.7}/LICENSE +0 -0
- {lam_cli-0.1.4 → lam_cli-0.1.7}/README.md +0 -0
- {lam_cli-0.1.4 → lam_cli-0.1.7}/lam/__init__.py +0 -0
- {lam_cli-0.1.4 → lam_cli-0.1.7}/lam_cli.egg-info/SOURCES.txt +0 -0
- {lam_cli-0.1.4 → lam_cli-0.1.7}/lam_cli.egg-info/dependency_links.txt +0 -0
- {lam_cli-0.1.4 → lam_cli-0.1.7}/lam_cli.egg-info/entry_points.txt +0 -0
- {lam_cli-0.1.4 → lam_cli-0.1.7}/lam_cli.egg-info/requires.txt +0 -0
- {lam_cli-0.1.4 → lam_cli-0.1.7}/lam_cli.egg-info/top_level.txt +0 -0
- {lam_cli-0.1.4 → lam_cli-0.1.7}/setup.cfg +0 -0
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
import json
|
|
4
4
|
import logging
|
|
5
5
|
import os
|
|
6
|
+
import re
|
|
6
7
|
import shutil
|
|
7
8
|
import socket
|
|
8
9
|
import subprocess
|
|
@@ -87,6 +88,7 @@ class Stats:
|
|
|
87
88
|
class EngineType(Enum):
|
|
88
89
|
JQ = "jq"
|
|
89
90
|
JAVASCRIPT = "js"
|
|
91
|
+
PYTHON = "py"
|
|
90
92
|
|
|
91
93
|
class ProcessingError(Exception):
|
|
92
94
|
"""Custom exception for processing errors"""
|
|
@@ -441,11 +443,402 @@ class BunEngine(Engine):
|
|
|
441
443
|
"type": e.__class__.__name__
|
|
442
444
|
}, str(e)
|
|
443
445
|
|
|
446
|
+
class PythonEngine(Engine):
|
|
447
|
+
"""Python execution engine with improved sandboxing for security"""
|
|
448
|
+
def __init__(self, *args, **kwargs):
|
|
449
|
+
super().__init__(*args, **kwargs)
|
|
450
|
+
self.modules_dir = Path(tempfile.gettempdir()) / "lam_python_modules"
|
|
451
|
+
self.modules_dir.mkdir(exist_ok=True)
|
|
452
|
+
# Define allowed modules that can be safely imported
|
|
453
|
+
self.allowed_modules = {
|
|
454
|
+
"json", "datetime", "math", "statistics", "collections",
|
|
455
|
+
"itertools", "functools", "re", "copy", "decimal",
|
|
456
|
+
"csv", "io", "dataclasses", "typing", "enum"
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
def validate_environment(self) -> bool:
|
|
460
|
+
logger.debug("Validating Python environment")
|
|
461
|
+
return sys.executable is not None
|
|
462
|
+
|
|
463
|
+
def create_safe_globals(self) -> dict:
|
|
464
|
+
"""Create a restricted globals dictionary for safer execution"""
|
|
465
|
+
safe_globals = {
|
|
466
|
+
"__builtins__": {
|
|
467
|
+
# Safe builtins only
|
|
468
|
+
"abs": abs, "all": all, "any": any, "bool": bool,
|
|
469
|
+
"chr": chr, "dict": dict, "dir": dir, "divmod": divmod,
|
|
470
|
+
"enumerate": enumerate, "filter": filter, "float": float,
|
|
471
|
+
"format": format, "frozenset": frozenset, "hash": hash,
|
|
472
|
+
"hex": hex, "int": int, "isinstance": isinstance,
|
|
473
|
+
"issubclass": issubclass, "iter": iter, "len": len,
|
|
474
|
+
"list": list, "map": map, "max": max, "min": min,
|
|
475
|
+
"next": next, "oct": oct, "ord": ord, "pow": pow,
|
|
476
|
+
"print": print, "range": range, "repr": repr,
|
|
477
|
+
"reversed": reversed, "round": round, "set": set,
|
|
478
|
+
"slice": slice, "sorted": sorted, "str": str, "sum": sum,
|
|
479
|
+
"tuple": tuple, "type": type, "zip": zip,
|
|
480
|
+
# Add Exception types for error handling
|
|
481
|
+
"Exception": Exception, "ValueError": ValueError,
|
|
482
|
+
"TypeError": TypeError, "KeyError": KeyError,
|
|
483
|
+
"IndexError": IndexError
|
|
484
|
+
},
|
|
485
|
+
# Pre-import safe modules
|
|
486
|
+
"json": json,
|
|
487
|
+
"datetime": datetime,
|
|
488
|
+
"math": __import__("math"),
|
|
489
|
+
"statistics": __import__("statistics"),
|
|
490
|
+
"collections": __import__("collections"),
|
|
491
|
+
"itertools": __import__("itertools"),
|
|
492
|
+
"functools": __import__("functools"),
|
|
493
|
+
"re": __import__("re")
|
|
494
|
+
}
|
|
495
|
+
return safe_globals
|
|
496
|
+
|
|
497
|
+
def check_for_dangerous_code(self, code: str) -> Optional[str]:
|
|
498
|
+
"""Check for potentially dangerous patterns in the code"""
|
|
499
|
+
dangerous_patterns = [
|
|
500
|
+
(r"__import__\s*\(", "Use of __import__ is not allowed"),
|
|
501
|
+
(r"eval\s*\(", "Use of eval() is not allowed"),
|
|
502
|
+
(r"exec\s*\(", "Use of exec() is not allowed"),
|
|
503
|
+
(r"globals\s*\(", "Access to globals() is not allowed"),
|
|
504
|
+
(r"locals\s*\(", "Access to locals() is not allowed"),
|
|
505
|
+
(r"getattr\s*\(", "Use of getattr() is not allowed"),
|
|
506
|
+
(r"setattr\s*\(", "Use of setattr() is not allowed"),
|
|
507
|
+
(r"delattr\s*\(", "Use of delattr() is not allowed"),
|
|
508
|
+
(r"compile\s*\(", "Use of compile() is not allowed"),
|
|
509
|
+
(r"open\s*\(", "Use of open() is not allowed"),
|
|
510
|
+
(r"__subclasses__", "Access to __subclasses__ is not allowed"),
|
|
511
|
+
(r"subprocess", "Access to subprocess module is not allowed"),
|
|
512
|
+
(r"sys\.", "Access to sys module is not allowed"),
|
|
513
|
+
(r"os\.", "Access to os module is not allowed"),
|
|
514
|
+
(r"shutil", "Access to shutil module is not allowed"),
|
|
515
|
+
(r"pathlib", "Access to pathlib module is not allowed"),
|
|
516
|
+
(r"importlib", "Access to importlib module is not allowed"),
|
|
517
|
+
(r"builtins", "Access to builtins module is not allowed"),
|
|
518
|
+
(r"_thread", "Access to _thread module is not allowed"),
|
|
519
|
+
(r"ctypes", "Access to ctypes module is not allowed"),
|
|
520
|
+
(r"socket", "Access to socket module is not allowed"),
|
|
521
|
+
(r"pickle", "Access to pickle module is not allowed"),
|
|
522
|
+
(r"multiprocessing", "Access to multiprocessing module is not allowed"),
|
|
523
|
+
(r"__\w+__", "Access to dunder attributes may not be allowed")
|
|
524
|
+
]
|
|
525
|
+
|
|
526
|
+
for pattern, message in dangerous_patterns:
|
|
527
|
+
if re.search(pattern, code):
|
|
528
|
+
return message
|
|
529
|
+
|
|
530
|
+
# Check for imports outside of allowed modules
|
|
531
|
+
import_pattern = r"import\s+(\w+)|from\s+(\w+)\s+import"
|
|
532
|
+
for match in re.finditer(import_pattern, code):
|
|
533
|
+
module = match.group(1) or match.group(2)
|
|
534
|
+
if module and module not in self.allowed_modules:
|
|
535
|
+
return f"Import of '{module}' is not allowed, only these modules are permitted: {', '.join(sorted(self.allowed_modules))}"
|
|
536
|
+
|
|
537
|
+
return None
|
|
538
|
+
|
|
539
|
+
def create_wrapper(self, input_data: str, user_script: str) -> str:
|
|
540
|
+
"""Create the wrapper script with proper escaping and sandboxing"""
|
|
541
|
+
# Perform safety checks before creating wrapper
|
|
542
|
+
safety_issue = self.check_for_dangerous_code(user_script)
|
|
543
|
+
if safety_issue:
|
|
544
|
+
# Return a wrapper that will immediately exit with the safety error
|
|
545
|
+
return f'''
|
|
546
|
+
import json
|
|
547
|
+
import sys
|
|
548
|
+
|
|
549
|
+
sys.stdout.write(json.dumps({{
|
|
550
|
+
"error": "Security violation detected: {safety_issue}",
|
|
551
|
+
"stack": []
|
|
552
|
+
}}))
|
|
553
|
+
sys.exit(1)
|
|
554
|
+
'''
|
|
555
|
+
|
|
556
|
+
return f'''
|
|
557
|
+
import json
|
|
558
|
+
import sys
|
|
559
|
+
import traceback
|
|
560
|
+
from datetime import datetime
|
|
561
|
+
import re
|
|
562
|
+
import math
|
|
563
|
+
import statistics
|
|
564
|
+
import collections
|
|
565
|
+
import itertools
|
|
566
|
+
import functools
|
|
567
|
+
|
|
568
|
+
# Resource limiting
|
|
569
|
+
import resource
|
|
570
|
+
import signal
|
|
571
|
+
|
|
572
|
+
# Set resource limits
|
|
573
|
+
def set_resource_limits():
|
|
574
|
+
# 5 seconds CPU time
|
|
575
|
+
resource.setrlimit(resource.RLIMIT_CPU, (5, 5))
|
|
576
|
+
|
|
577
|
+
# 100MB memory limit
|
|
578
|
+
memory_limit = 100 * 1024 * 1024 # 100MB in bytes
|
|
579
|
+
resource.setrlimit(resource.RLIMIT_AS, (memory_limit, memory_limit))
|
|
580
|
+
|
|
581
|
+
# Set timeout handler
|
|
582
|
+
def timeout_handler(signum, frame):
|
|
583
|
+
sys.stderr.write(json.dumps({{
|
|
584
|
+
"error": "Execution timed out (5 seconds)",
|
|
585
|
+
"stack": []
|
|
586
|
+
}}))
|
|
587
|
+
sys.exit(1)
|
|
588
|
+
|
|
589
|
+
signal.signal(signal.SIGALRM, timeout_handler)
|
|
590
|
+
signal.alarm(5) # 5 second timeout
|
|
591
|
+
|
|
592
|
+
try:
|
|
593
|
+
set_resource_limits()
|
|
594
|
+
except Exception as e:
|
|
595
|
+
# Continue if resource limiting is not available (e.g., on Windows)
|
|
596
|
+
pass
|
|
597
|
+
|
|
598
|
+
# Setup basic logging
|
|
599
|
+
logs = []
|
|
600
|
+
|
|
601
|
+
class LogCapture:
|
|
602
|
+
def __init__(self, log_type):
|
|
603
|
+
self.log_type = log_type
|
|
604
|
+
|
|
605
|
+
def write(self, message):
|
|
606
|
+
if message.strip():
|
|
607
|
+
logs.append({{"type": self.log_type, "message": message.strip()}})
|
|
608
|
+
return len(message)
|
|
609
|
+
|
|
610
|
+
def flush(self):
|
|
611
|
+
pass
|
|
612
|
+
|
|
613
|
+
# Custom safer importer
|
|
614
|
+
class RestrictedImporter:
|
|
615
|
+
def __init__(self, allowed_modules):
|
|
616
|
+
self.allowed_modules = allowed_modules
|
|
617
|
+
|
|
618
|
+
def __call__(self, name, *args, **kwargs):
|
|
619
|
+
if name in self.allowed_modules:
|
|
620
|
+
return __import__(name, *args, **kwargs)
|
|
621
|
+
else:
|
|
622
|
+
raise ImportError(f"Import of '{{name}}' is not allowed for security reasons. " +
|
|
623
|
+
f"Allowed modules: {{', '.join(sorted(self.allowed_modules))}}")
|
|
624
|
+
|
|
625
|
+
# Capture stdout and stderr
|
|
626
|
+
original_stdout = sys.stdout
|
|
627
|
+
original_stderr = sys.stderr
|
|
628
|
+
sys.stdout = LogCapture("log")
|
|
629
|
+
sys.stderr = LogCapture("error")
|
|
630
|
+
|
|
631
|
+
# Parse input data
|
|
632
|
+
try:
|
|
633
|
+
input_data = json.loads(r"""{input_data}""")
|
|
634
|
+
except json.JSONDecodeError as e:
|
|
635
|
+
original_stderr.write(json.dumps({{"error": f"Failed to parse input data: {{e}}"}}))
|
|
636
|
+
sys.exit(1)
|
|
637
|
+
|
|
638
|
+
# Create safe environment
|
|
639
|
+
safe_globals = {{
|
|
640
|
+
"__builtins__": {{
|
|
641
|
+
# Safe builtins only
|
|
642
|
+
"abs": abs, "all": all, "any": any, "bool": bool,
|
|
643
|
+
"chr": chr, "dict": dict, "divmod": divmod,
|
|
644
|
+
"enumerate": enumerate, "filter": filter, "float": float,
|
|
645
|
+
"format": format, "frozenset": frozenset, "hash": hash,
|
|
646
|
+
"hex": hex, "int": int, "isinstance": isinstance,
|
|
647
|
+
"issubclass": issubclass, "iter": iter, "len": len,
|
|
648
|
+
"list": list, "map": map, "max": max, "min": min,
|
|
649
|
+
"next": next, "oct": oct, "ord": ord, "pow": pow,
|
|
650
|
+
"print": print, "range": range, "repr": repr,
|
|
651
|
+
"reversed": reversed, "round": round, "set": set,
|
|
652
|
+
"slice": slice, "sorted": sorted, "str": str, "sum": sum,
|
|
653
|
+
"tuple": tuple, "type": type, "zip": zip,
|
|
654
|
+
# Exception types for error handling
|
|
655
|
+
"Exception": Exception, "ValueError": ValueError,
|
|
656
|
+
"TypeError": TypeError, "KeyError": KeyError,
|
|
657
|
+
"IndexError": IndexError,
|
|
658
|
+
# Add a safe import function
|
|
659
|
+
"__import__": RestrictedImporter({{
|
|
660
|
+
"json", "datetime", "math", "statistics", "collections",
|
|
661
|
+
"itertools", "functools", "re", "copy", "decimal",
|
|
662
|
+
"csv", "io", "dataclasses", "typing", "enum"
|
|
663
|
+
}})
|
|
664
|
+
}},
|
|
665
|
+
# Pre-import safe modules
|
|
666
|
+
"json": json,
|
|
667
|
+
"datetime": datetime,
|
|
668
|
+
"math": math,
|
|
669
|
+
"statistics": statistics,
|
|
670
|
+
"collections": collections,
|
|
671
|
+
"itertools": itertools,
|
|
672
|
+
"functools": functools,
|
|
673
|
+
"re": re
|
|
674
|
+
}}
|
|
675
|
+
|
|
676
|
+
safe_locals = {{"input_data": input_data}}
|
|
677
|
+
|
|
678
|
+
# Define transform function from user script in a safe context
|
|
679
|
+
try:
|
|
680
|
+
compiled_code = compile(r"""{user_script}""", "<user_script>", "exec")
|
|
681
|
+
exec(compiled_code, safe_globals, safe_locals)
|
|
682
|
+
|
|
683
|
+
# Validate transform function exists and has correct signature
|
|
684
|
+
if 'transform' not in safe_locals:
|
|
685
|
+
original_stderr.write(json.dumps({{"error": "No transform function defined"}}))
|
|
686
|
+
sys.exit(1)
|
|
687
|
+
|
|
688
|
+
if not callable(safe_locals['transform']):
|
|
689
|
+
original_stderr.write(json.dumps({{"error": "transform must be a function"}}))
|
|
690
|
+
sys.exit(1)
|
|
691
|
+
|
|
692
|
+
transform_fn = safe_locals['transform']
|
|
693
|
+
|
|
694
|
+
except Exception as e:
|
|
695
|
+
original_stderr.write(json.dumps({{
|
|
696
|
+
"error": str(e),
|
|
697
|
+
"stack": traceback.format_exc().split('\\n')
|
|
698
|
+
}}))
|
|
699
|
+
sys.exit(1)
|
|
700
|
+
|
|
701
|
+
# Execute transform with input data
|
|
702
|
+
try:
|
|
703
|
+
# Cancel the alarm if we reach here (we have our own timeout)
|
|
704
|
+
try:
|
|
705
|
+
signal.alarm(0)
|
|
706
|
+
except:
|
|
707
|
+
pass
|
|
708
|
+
|
|
709
|
+
result = transform_fn(input_data)
|
|
710
|
+
|
|
711
|
+
# Basic validation of output (to prevent non-serializable data)
|
|
712
|
+
try:
|
|
713
|
+
json.dumps(result)
|
|
714
|
+
except TypeError as e:
|
|
715
|
+
raise TypeError(f"Transform result is not JSON serializable: {{e}}")
|
|
716
|
+
|
|
717
|
+
# Write result to original stdout
|
|
718
|
+
original_stdout.write(json.dumps({{"result": result, "logs": logs}}))
|
|
719
|
+
|
|
720
|
+
except Exception as e:
|
|
721
|
+
original_stderr.write(json.dumps({{
|
|
722
|
+
"error": str(e),
|
|
723
|
+
"stack": traceback.format_exc().split('\\n')
|
|
724
|
+
}}))
|
|
725
|
+
sys.exit(1)
|
|
726
|
+
finally:
|
|
727
|
+
# Restore stdout and stderr
|
|
728
|
+
sys.stdout = original_stdout
|
|
729
|
+
sys.stderr = original_stderr
|
|
730
|
+
'''
|
|
731
|
+
|
|
732
|
+
def execute(self, program_file: str, input_data: str) -> Tuple[Union[Dict, str], Optional[str]]:
|
|
733
|
+
logger.info(f"Executing Python script: {program_file}")
|
|
734
|
+
stats = Stats()
|
|
735
|
+
|
|
736
|
+
try:
|
|
737
|
+
check_resource_limits(self.modules_dir)
|
|
738
|
+
|
|
739
|
+
with tempfile.TemporaryDirectory() as temp_dir:
|
|
740
|
+
temp_dir = Path(temp_dir)
|
|
741
|
+
|
|
742
|
+
# Read user script
|
|
743
|
+
with open(program_file, 'r') as f:
|
|
744
|
+
user_script = f.read()
|
|
745
|
+
logger.debug("Loaded user Python script: %d characters", len(user_script))
|
|
746
|
+
|
|
747
|
+
# Check for dangerous code
|
|
748
|
+
safety_issue = self.check_for_dangerous_code(user_script)
|
|
749
|
+
if safety_issue:
|
|
750
|
+
logger.warning(f"Security violation detected in script: {safety_issue}")
|
|
751
|
+
return {
|
|
752
|
+
"lam.error": f"Security violation: {safety_issue}",
|
|
753
|
+
"type": "SecurityError"
|
|
754
|
+
}, f"Security violation: {safety_issue}"
|
|
755
|
+
|
|
756
|
+
# Create wrapper script
|
|
757
|
+
wrapper = self.create_wrapper(input_data, user_script)
|
|
758
|
+
script_path = temp_dir / "script.py"
|
|
759
|
+
with open(script_path, 'w') as f:
|
|
760
|
+
f.write(wrapper)
|
|
761
|
+
logger.debug("Generated Python wrapper script: %s", script_path)
|
|
762
|
+
|
|
763
|
+
# Execute with Python in isolated environment
|
|
764
|
+
process = subprocess.Popen(
|
|
765
|
+
[
|
|
766
|
+
sys.executable,
|
|
767
|
+
"-I", # Isolated mode, ignores environment variables/site packages
|
|
768
|
+
str(script_path)
|
|
769
|
+
],
|
|
770
|
+
stdout=subprocess.PIPE,
|
|
771
|
+
stderr=subprocess.PIPE,
|
|
772
|
+
text=True,
|
|
773
|
+
cwd=temp_dir,
|
|
774
|
+
# Prevent access to system environment variables
|
|
775
|
+
env={"PATH": os.environ.get("PATH", "")}
|
|
776
|
+
)
|
|
777
|
+
logger.info("Started Python process PID %d", process.pid)
|
|
778
|
+
|
|
779
|
+
try:
|
|
780
|
+
output, error = process.communicate(timeout=5)
|
|
781
|
+
logger.debug("Process completed with code %d", process.returncode)
|
|
782
|
+
except subprocess.TimeoutExpired as e:
|
|
783
|
+
logger.warning("Process timeout after 5 seconds")
|
|
784
|
+
process.kill()
|
|
785
|
+
return {"lam.error": "Script execution timed out"}, "Execution timed out after 5 seconds"
|
|
786
|
+
|
|
787
|
+
# Handle process errors
|
|
788
|
+
if process.returncode != 0:
|
|
789
|
+
try:
|
|
790
|
+
# Try to parse structured error from stderr
|
|
791
|
+
error_data = json.loads(error.strip())
|
|
792
|
+
error_msg = error_data.get('error', 'Unknown error')
|
|
793
|
+
stack = error_data.get('stack', [])
|
|
794
|
+
|
|
795
|
+
# Format error message
|
|
796
|
+
error_details = {
|
|
797
|
+
"lam.error": error_msg,
|
|
798
|
+
"stack_trace": stack
|
|
799
|
+
}
|
|
800
|
+
return error_details, error_msg
|
|
801
|
+
|
|
802
|
+
except json.JSONDecodeError:
|
|
803
|
+
# Fallback to raw error output
|
|
804
|
+
error_msg = error.strip() or "Unknown error"
|
|
805
|
+
return {"lam.error": error_msg}, error_msg
|
|
806
|
+
|
|
807
|
+
# Handle successful output
|
|
808
|
+
try:
|
|
809
|
+
output_data = json.loads(output)
|
|
810
|
+
|
|
811
|
+
# Process Python logs (if any)
|
|
812
|
+
if 'logs' in output_data:
|
|
813
|
+
for log_entry in output_data.get('logs', []):
|
|
814
|
+
if log_entry['type'] == 'error':
|
|
815
|
+
logger.error("[Python] %s", log_entry['message'])
|
|
816
|
+
else:
|
|
817
|
+
logger.debug("[Python] %s", log_entry['message'])
|
|
818
|
+
|
|
819
|
+
result = output_data.get('result', {})
|
|
820
|
+
return result, None
|
|
821
|
+
|
|
822
|
+
except json.JSONDecodeError as e:
|
|
823
|
+
logger.error("Failed to parse output: %s", str(e))
|
|
824
|
+
return {
|
|
825
|
+
"lam.error": "Invalid JSON output",
|
|
826
|
+
"raw_output": output.strip()
|
|
827
|
+
}, "Output format error"
|
|
828
|
+
|
|
829
|
+
except Exception as e:
|
|
830
|
+
logger.exception("Execution failed")
|
|
831
|
+
return {
|
|
832
|
+
"lam.error": str(e),
|
|
833
|
+
"type": e.__class__.__name__
|
|
834
|
+
}, str(e)
|
|
835
|
+
|
|
444
836
|
def get_engine(engine_type: str, workspace_id: str, flow_id: str, execution_id: str) -> Engine:
|
|
445
837
|
"""Factory function to get the appropriate execution engine"""
|
|
446
838
|
engines = {
|
|
447
839
|
EngineType.JQ.value: JQEngine,
|
|
448
|
-
EngineType.JAVASCRIPT.value: BunEngine
|
|
840
|
+
EngineType.JAVASCRIPT.value: BunEngine,
|
|
841
|
+
EngineType.PYTHON.value: PythonEngine
|
|
449
842
|
}
|
|
450
843
|
|
|
451
844
|
engine_class = engines.get(engine_type)
|
|
@@ -478,10 +871,45 @@ def lam():
|
|
|
478
871
|
"""LAM - Laminar Data Transformation Tool"""
|
|
479
872
|
pass
|
|
480
873
|
|
|
874
|
+
@lam.command()
|
|
875
|
+
def initialize():
|
|
876
|
+
"""Initialize shared modules for supported engines."""
|
|
877
|
+
click.echo("Starting LAM initialization...")
|
|
878
|
+
|
|
879
|
+
engine_classes = [BunEngine, PythonEngine, JQEngine] # add other engines so we dont miss them in the future
|
|
880
|
+
|
|
881
|
+
# Define placeholder IDs for engine instantiation during initialization
|
|
882
|
+
init_workspace_id = "lam_init_workspace"
|
|
883
|
+
init_flow_id = "lam_init_flow"
|
|
884
|
+
init_execution_id = "lam_init_execution"
|
|
885
|
+
|
|
886
|
+
for engine_class in engine_classes:
|
|
887
|
+
engine_name = engine_class.__name__
|
|
888
|
+
click.echo(f"Checking {engine_name} for shared module setup...")
|
|
889
|
+
try:
|
|
890
|
+
# Instantiate engine to access instance methods like _setup_shared_modules
|
|
891
|
+
engine_instance = engine_class(
|
|
892
|
+
workspace_id=init_workspace_id,
|
|
893
|
+
flow_id=init_flow_id,
|
|
894
|
+
execution_id=init_execution_id
|
|
895
|
+
)
|
|
896
|
+
|
|
897
|
+
if hasattr(engine_instance, '_setup_shared_modules') and callable(getattr(engine_instance, '_setup_shared_modules')):
|
|
898
|
+
click.echo(f"Running _setup_shared_modules for {engine_name}...")
|
|
899
|
+
getattr(engine_instance, '_setup_shared_modules')()
|
|
900
|
+
click.echo(f"Successfully initialized shared modules for {engine_name}.")
|
|
901
|
+
else:
|
|
902
|
+
click.echo(f"{engine_name} does not have a _setup_shared_modules method or it's not callable.")
|
|
903
|
+
except Exception as e:
|
|
904
|
+
click.echo(f"Error during initialization of {engine_name}: {e}", err=True)
|
|
905
|
+
logger.error(f"Initialization error for {engine_name}", exc_info=True)
|
|
906
|
+
|
|
907
|
+
click.echo("LAM initialization complete.")
|
|
908
|
+
|
|
481
909
|
@lam.command()
|
|
482
910
|
@click.argument('program_file', type=click.Path(exists=True))
|
|
483
911
|
@click.argument('input', type=str)
|
|
484
|
-
@click.option('--language', type=click.Choice(['jq', 'js']), default='jq',
|
|
912
|
+
@click.option('--language', type=click.Choice(['jq', 'js', 'py']), default='jq',
|
|
485
913
|
help='Script language (default: jq)')
|
|
486
914
|
@click.option('--workspace_id', default="local", help="Workspace ID")
|
|
487
915
|
@click.option('--flow_id', default="local", help="Flow ID")
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|