forked from ElementsProject/lightning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreckless
executable file
·1358 lines (1199 loc) · 52.1 KB
/
reckless
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import sys
import argparse
import copy
import datetime
from enum import Enum
import json
import logging
import os
from pathlib import Path, PosixPath
import shutil
from subprocess import Popen, PIPE, TimeoutExpired, run
import tempfile
import time
import types
from typing import Union
from urllib.parse import urlparse
from urllib.request import urlopen
import venv
logging.basicConfig(
level=logging.DEBUG,
format='[%(asctime)s] %(levelname)s: %(message)s',
handlers=[logging.StreamHandler(stream=sys.stdout)],
)
repos = ['https://github.com/lightningd/plugins']
def py_entry_guesses(name) -> list:
return [name, f'{name}.py', '__init__.py']
def unsupported_entry(name) -> list:
return [f'{name}.go', f'{name}.sh']
def entry_guesses(name: str) -> list:
guesses = []
for inst in INSTALLERS:
for entry in inst.entries:
guesses.append(entry.format(name=name))
return guesses
class Installer:
'''
The identification of a plugin language, compiler or interpreter
availability, and the install procedures.
'''
def __init__(self, name: str, mimetype: str,
exe: Union[str, None] = None,
compiler: Union[str, None] = None,
manager: Union[str, None] = None,
entry: Union[str, None] = None):
self.name = name
self.mimetype = mimetype
self.entries = []
if entry:
self.entries.append(entry)
self.exe = exe # interpreter (if required)
self.compiler = compiler # compiler bin (if required)
self.manager = manager # dependency manager (if required)
self.dependency_file = None
self.dependency_call = None
def __repr__(self):
return (f'<Installer {self.name}: mimetype: {self.mimetype}, '
f'exe: {self.exe}, manager: {self.manager}>')
def executable(self) -> bool:
'''Validate the necessary bins are available to execute the plugin.'''
if self.exe:
if shutil.which(self.exe):
# This should arguably not be checked here.
if self.manager:
if shutil.which(self.manager):
return True
return False
return True
return False
return True
def installable(self) -> bool:
'''Validate the necessary compiler and package manager executables are
available to install. If these are defined, they are considered
mandatory even though the user may have the requisite packages already
installed.'''
if self.compiler and not shutil.which(self.compiler):
return False
if self.manager and not shutil.which(self.manager):
return False
return True
def add_entrypoint(self, entry: str):
assert isinstance(entry, str)
self.entries.append(entry)
def get_entrypoints(self, name: str):
guesses = []
for entry in self.entries:
guesses.append(entry.format(name=name))
return guesses
def add_dependency_file(self, dep: str):
assert isinstance(dep, str)
self.dependency_file = dep
def add_dependency_call(self, call: list):
if self.dependency_call is None:
self.dependency_call = []
self.dependency_call.append(call)
def copy(self):
return copy.deepcopy(self)
class InstInfo:
def __init__(self, name: str, location: str, git_url: str):
self.name = name
self.source_loc = str(location) # Used for 'git clone'
self.git_url = git_url # API access for github repos
self.srctype = Source.get_type(location)
self.entry = None # relative to source_loc or subdir
self.deps = None
self.subdir = None
self.commit = None
def __repr__(self):
return (f'InstInfo({self.name}, {self.source_loc}, {self.git_url}, '
f'{self.entry}, {self.deps}, {self.subdir})')
def get_inst_details(self) -> bool:
"""Search the source_loc for plugin install details.
This may be necessary if a contents api is unavailable.
Extracts entrypoint and dependencies if searchable, otherwise
matches a directory to the plugin name and stops."""
if self.srctype == Source.DIRECTORY:
assert Path(self.source_loc).exists()
assert os.path.isdir(self.source_loc)
target = SourceDir(self.source_loc, srctype=self.srctype)
# Set recursion for how many directories deep we should search
depth = 0
if self.srctype in [Source.DIRECTORY, Source.LOCAL_REPO]:
depth = 5
elif self.srctype == Source.GITHUB_REPO:
depth = 2
def search_dir(self, sub: SourceDir, subdir: bool,
recursion: int) -> Union[SourceDir, None]:
assert isinstance(recursion, int)
# If unable to search deeper, resort to matching directory name
if recursion < 1:
if sub.name.lower() == self.name.lower():
# Partial success (can't check for entrypoint)
self.name = sub.name
return sub
return None
sub.populate()
if sub.name.lower() == self.name.lower():
# Directory matches the name we're trying to install, so check
# for entrypoint and dependencies.
for inst in INSTALLERS:
for g in inst.get_entrypoints(self.name):
found_entry = sub.find(g, ftype=SourceFile)
if found_entry:
break
# FIXME: handle a list of dependencies
found_dep = sub.find(inst.dependency_file,
ftype=SourceFile)
if found_entry:
# Success!
if found_dep:
self.name = sub.name
self.entry = found_entry.name
self.deps = found_dep.name
return sub
logging.debug(f"missing dependency for {self}")
found_entry = None
for file in sub.contents:
if isinstance(file, SourceDir):
success = search_dir(self, file, True, recursion - 1)
if success:
return success
return None
result = search_dir(self, target, False, depth)
if result:
if result != target:
if result.relative:
self.subdir = result.relative
return True
return False
def create_dir(directory: PosixPath) -> bool:
try:
Path(directory).mkdir(parents=False, exist_ok=True)
return True
# Okay if directory already exists
except FileExistsError:
return True
# Parent directory missing
except FileNotFoundError:
return False
def remove_dir(directory: str) -> bool:
try:
shutil.rmtree(directory)
return True
except NotADirectoryError:
print(f"Tried to remove directory {directory} that does not exist.")
except PermissionError:
print(f"Permission denied removing dir: {directory}")
return False
class Source(Enum):
DIRECTORY = 1
LOCAL_REPO = 2
GITHUB_REPO = 3
OTHER_URL = 4
UNKNOWN = 5
@classmethod
def get_type(cls, source: str):
if Path(os.path.realpath(source)).exists():
if os.path.isdir(os.path.realpath(source)):
# returns 0 if git repository
proc = run(['git', '-C', source, 'rev-parse'],
cwd=os.path.realpath(source), stdout=PIPE,
stderr=PIPE, text=True, timeout=5)
if proc.returncode == 0:
return cls(2)
return cls(1)
if 'github.com' in source.lower():
return cls(3)
if 'http://' in source.lower() or 'https://' in source.lower():
return cls(4)
return cls(5)
class SourceDir():
"""Structure to search source contents."""
def __init__(self, location: str, srctype: Source = None, name: str = None,
relative: str = None):
self.location = str(location)
if name:
self.name = name
else:
self.name = Path(location).name
self.contents = []
self.srctype = srctype
self.prepopulated = False
self.relative = relative # location relative to source
def populate(self):
"""populates contents of the directory at least one level"""
if self.prepopulated:
return
if not self.srctype:
self.srctype = Source.get_type(self.location)
# logging.debug(f"populating {self.srctype} {self.location}")
if self.srctype == Source.DIRECTORY:
self.contents = populate_local_dir(self.location)
elif self.srctype == Source.LOCAL_REPO:
self.contents = populate_local_repo(self.location)
elif self.srctype == Source.GITHUB_REPO:
self.contents = populate_github_repo(self.location)
else:
raise Exception("populate method undefined for {self.srctype}")
# Ensure the relative path of the contents is inherited.
for c in self.contents:
if self.relative is None:
c.relative = c.name
else:
c.relative = str(Path(self.relative) / c.name)
def find(self, name: str, ftype: type = None) -> str:
"""Match a SourceFile or SourceDir to the provided name
(case insentive) and return its filename."""
assert isinstance(name, str)
if len(self.contents) == 0:
return None
for c in self.contents:
if ftype and not isinstance(c, ftype):
continue
if c.name.lower() == name.lower():
return c
return None
def __repr__(self):
return f"<SourceDir: {self.name} ({self.location})>"
def __eq__(self, compared):
if isinstance(compared, str):
return self.name == compared
if isinstance(compared, SourceDir):
return (self.name == compared.name and
self.location == compared.location)
return False
class SourceFile():
def __init__(self, location: str):
self.location = str(location)
self.name = Path(location).name
def __repr__(self):
return f"<SourceFile: {self.name} ({self.location})>"
def __eq__(self, compared):
if isinstance(compared, str):
return self.name == compared
if isinstance(compared, SourceFile):
return (self.name == compared.name and
self.location == compared.location)
return False
def populate_local_dir(path: str) -> list:
assert Path(os.path.realpath(path)).exists()
contents = []
for c in os.listdir(path):
fullpath = Path(path) / c
if os.path.isdir(fullpath):
# Inheriting type saves a call to test if it's a git repo
contents.append(SourceDir(fullpath, srctype=Source.DIRECTORY))
else:
contents.append(SourceFile(fullpath))
return contents
def populate_local_repo(path: str) -> list:
assert Path(os.path.realpath(path)).exists()
basedir = SourceDir('base')
def populate_source_path(parent, mypath):
"""`git ls-tree` lists all files with their full path.
This populates all intermediate directories and the file."""
parentdir = parent
if mypath == '.':
logging.debug(' asked to populate root dir')
return
# reverse the parents
pdirs = mypath
revpath = []
child = parentdir
while pdirs.parent.name != '':
revpath.append(pdirs.parent.name)
pdirs = pdirs.parent
for p in reversed(revpath):
child = parentdir.find(p)
if child:
parentdir = child
else:
child = SourceDir(p, srctype=Source.LOCAL_REPO)
child.prepopulated = True
parentdir.contents.append(child)
parentdir = child
newfile = SourceFile(mypath.name)
child.contents.append(newfile)
# FIXME: Pass in tag or commit hash
ver = 'HEAD'
git_call = ['git', '-C', path, 'ls-tree', '--full-tree', '-r',
'--name-only', ver]
proc = run(git_call, stdout=PIPE, stderr=PIPE, text=True, timeout=5)
if proc.returncode != 0:
logging.debug(f'ls-tree of repo {path} failed')
return None
for filepath in proc.stdout.splitlines():
populate_source_path(basedir, Path(filepath))
return basedir.contents
def populate_github_repo(url: str) -> list:
# FIXME: This probably contains leftover cruft.
repo = url.split('/')
while '' in repo:
repo.remove('')
repo_name = None
parsed_url = urlparse(url)
if 'github.com' not in parsed_url.netloc:
return None
if len(parsed_url.path.split('/')) < 2:
return None
start = 1
# Maybe we were passed an api.github.com/repo/<user> url
if 'api' in parsed_url.netloc:
start += 1
repo_user = parsed_url.path.split('/')[start]
repo_name = parsed_url.path.split('/')[start + 1]
# Get details from the github API.
api_url = f'{API_GITHUB_COM}/repos/{repo_user}/{repo_name}/contents/'
git_url = api_url
if "api.github.com" in git_url:
# This lets us redirect to handle blackbox testing
git_url = (API_GITHUB_COM + git_url.split("api.github.com")[-1])
r = urlopen(git_url, timeout=5)
if r.status != 200:
return False
if 'git/tree' in git_url:
tree = json.loads(r.read().decode())['tree']
else:
tree = json.loads(r.read().decode())
contents = []
for sub in tree:
if 'type' in sub and 'name' in sub and 'git_url' in sub:
if sub['type'] == 'dir':
new_sub = SourceDir(sub['git_url'], srctype=Source.GITHUB_REPO,
name=sub['name'])
contents.append(new_sub)
elif sub['type'] == 'file':
new_file = SourceFile(sub['name'])
contents.append(new_file)
return contents
class Config():
"""A generic class for procuring, reading and editing config files"""
def obtain_config(self,
config_path: str,
default_text: str,
warn: bool = False) -> str:
"""Return a config file from the desired location. Create one with
default_text if it cannot be found."""
if isinstance(config_path, type(None)):
raise Exception("Generic config must be passed a config_path.")
assert isinstance(config_path, str)
# FIXME: warn if reckless dir exists, but conf not found
if Path(config_path).exists():
with open(config_path, 'r+') as f:
config_content = f.readlines()
return config_content
print(f'config file not found: {config_path}')
if warn:
confirm = input('press [Y] to create one now.\n').upper() == 'Y'
else:
confirm = True
if not confirm:
sys.exit(1)
parent_path = Path(config_path).parent
# Create up to one parent in the directory tree.
if create_dir(parent_path):
with open(self.conf_fp, 'w') as f:
f.write(default_text)
# FIXME: Handle write failure
return default_text
else:
logging.debug('could not create the parent directory ' +
parent_path)
raise FileNotFoundError('invalid parent directory')
def editConfigFile(self, addline: Union[str, None],
removeline: Union[str, None]):
"""Idempotent function to add and/or remove a single line each."""
remove_these_lines = []
with open(self.conf_fp, 'r') as reckless_conf:
original = reckless_conf.readlines()
empty_lines = []
write_required = False
for n, l in enumerate(original):
if removeline and l.strip() == removeline.strip():
write_required = True
remove_these_lines.append(n)
continue
if l.strip() == '':
empty_lines.append(n)
if n-1 in empty_lines:
# The white space is getting excessive.
remove_these_lines.append(n)
continue
if not addline and not write_required:
return
# No write necessary if addline is already in config.
if addline and not write_required:
for line in original:
if line.strip() == addline.strip():
return
with open(self.conf_fp, 'w') as conf_write:
# no need to write if passed 'None'
line_exists = not bool(addline)
for n, l in enumerate(original):
if n not in remove_these_lines:
if n > 0:
conf_write.write(f'\n{l.strip()}')
else:
conf_write.write(l.strip())
if addline and addline.strip() == l.strip():
# addline is idempotent
line_exists = True
if not line_exists:
conf_write.write(f'\n{addline}')
def __init__(self, path: Union[str, None] = None,
default_text: Union[str, None] = None,
warn: bool = False):
assert path is not None
assert default_text is not None
self.conf_fp = path
self.content = self.obtain_config(self.conf_fp, default_text,
warn=warn)
class RecklessConfig(Config):
"""Reckless config (by default, specific to the bitcoin network only.)
This is inherited by the lightningd config and contains all reckless
maintained plugins."""
def enable_plugin(self, plugin_path: str):
"""Handle persistent plugin loading via config"""
self.editConfigFile(f'plugin={plugin_path}',
f'disable-plugin={plugin_path}')
def disable_plugin(self, plugin_path: str):
"""Handle persistent plugin disabling via config"""
self.editConfigFile(f'disable-plugin={plugin_path}',
f'plugin={plugin_path}')
def __init__(self, path: Union[str, None] = None,
default_text: Union[str, None] = None):
if path is None:
path = Path(LIGHTNING_DIR) / 'reckless' / 'bitcoin-reckless.conf'
if default_text is None:
default_text = (
'# This configuration file is managed by reckless to activate '
'and disable\n# reckless-installed plugins\n\n'
)
Config.__init__(self, path=str(path), default_text=default_text)
self.reckless_dir = Path(path).parent
class LightningBitcoinConfig(Config):
"""lightningd config specific to the bitcoin network. This is inherited by
the main lightningd config and in turn, inherits bitcoin-reckless.conf."""
def __init__(self, path: Union[str, None] = None,
default_text: Union[str, None] = None,
warn: bool = True):
if path is None:
path = Path(LIGHTNING_DIR).joinpath('bitcoin', 'config')
if default_text is None:
default_text = "# This config was autopopulated by reckless\n\n"
Config.__init__(self, path=str(path),
default_text=default_text, warn=warn)
class InferInstall():
"""Once a plugin is installed, we may need its directory and entrypoint"""
def __init__(self, name: str):
reck_contents = os.listdir(RECKLESS_CONFIG.reckless_dir)
reck_contents_lower = {}
for f in reck_contents:
reck_contents_lower.update({f.lower(): f})
def match_name(name) -> str:
for tier in range(0, 10):
# Look for each installers preferred entrypoint format first
for inst in INSTALLERS:
fmt = inst.entries[tier]
if '{name}' in fmt:
pre = fmt.split('{name}')[0]
post = fmt.split('{name}')[-1]
if name.startswith(pre) and name.endswith(post):
return name.lstrip(pre).rstrip(post)
else:
if fmt == name:
return name
return name
name = match_name(name)
if name.lower() in reck_contents_lower.keys():
actual_name = reck_contents_lower[name.lower()]
self.dir = Path(RECKLESS_CONFIG.reckless_dir).joinpath(actual_name)
else:
raise Exception(f"Could not find a reckless directory for {name}")
plug_dir = Path(RECKLESS_CONFIG.reckless_dir).joinpath(actual_name)
for guess in entry_guesses(actual_name):
for content in plug_dir.iterdir():
if content.name == guess:
self.entry = str(content)
self.name = actual_name
return
raise Exception(f'plugin entrypoint not found in {self.dir}')
class InstallationFailure(Exception):
"raised when pip fails to complete dependency installation"
def create_python3_venv(staged_plugin: InstInfo) -> InstInfo:
"Create a virtual environment, install dependencies and test plugin."
env_path = Path('.venv')
env_path_full = Path(staged_plugin.source_loc) / env_path
plugin_path = Path(staged_plugin.source_loc) / 'source'
# subdir should always be None at this point
if staged_plugin.subdir:
logging.warning("cloned plugin contains subdirectory")
plugin_path = plugin_path / staged_plugin.subdir
if shutil.which('poetry') and staged_plugin.deps == 'pyproject.toml':
logging.debug('configuring a python virtual environment (poetry) in '
f'{env_path_full}')
# The virtual environment should be located with the plugin.
# This installs it to .venv instead of in the global location.
mod_poetry_env = os.environ
mod_poetry_env['POETRY_VIRTUALENVS_IN_PROJECT'] = 'true'
# This ensures poetry installs to a new venv even though one may
# already be active (i.e., under CI)
if 'VIRTUAL_ENV' in mod_poetry_env:
del mod_poetry_env['VIRTUAL_ENV']
# to avoid relocating and breaking the venv, symlink pyroject.toml
# to the location of poetry's .venv dir
(Path(staged_plugin.source_loc) / 'pyproject.toml') \
.symlink_to(plugin_path / 'pyproject.toml')
(Path(staged_plugin.source_loc) / 'poetry.lock') \
.symlink_to(plugin_path / 'poetry.lock')
# Avoid redirecting stdout in order to stream progress.
# Timeout excluded as armv7 grpcio build/install can take 1hr.
pip = run(['poetry', 'install', '--no-root'], check=False,
cwd=staged_plugin.source_loc, env=mod_poetry_env)
(Path(staged_plugin.source_loc) / 'pyproject.toml').unlink()
(Path(staged_plugin.source_loc) / 'poetry.lock').unlink()
else:
builder = venv.EnvBuilder(with_pip=True)
builder.create(env_path_full)
logging.debug('configuring a python virtual environment (pip) in '
f'{env_path_full}')
logging.debug(f'virtual environment created in {env_path_full}.')
if staged_plugin.deps == 'pyproject.toml':
pip = run(['bin/pip', 'install', str(plugin_path)],
check=False, cwd=plugin_path)
elif staged_plugin.deps == 'requirements.txt':
pip = run([str(env_path_full / 'bin/pip'), 'install', '-r',
str(plugin_path / 'requirements.txt')],
check=False, cwd=plugin_path)
else:
logging.debug("no python dependency file")
if pip and pip.returncode != 0:
logging.debug("install to virtual environment failed")
print('error encountered installing dependencies')
raise InstallationFailure
staged_plugin.venv = env_path
print('dependencies installed successfully')
return staged_plugin
def create_wrapper(plugin: InstInfo):
'''The wrapper will activate the virtual environment for this plugin and
then run the plugin from within the same process.'''
assert hasattr(plugin, 'venv')
venv_full_path = Path(plugin.source_loc) / plugin.venv
with open(Path(plugin.source_loc) / plugin.entry, 'w') as wrapper:
wrapper.write((f"#!{venv_full_path}/bin/python\n"
"import sys\n"
"import runpy\n\n"
f"if '{plugin.source_loc}/source' not in sys.path:\n"
f" sys.path.append('{plugin.source_loc}/source')\n"
f"if '{plugin.source_loc}' in sys.path:\n"
f" sys.path.remove('{plugin.source_loc}')\n"
f"runpy.run_module(\"{plugin.name}\", "
"{}, \"__main__\")"))
wrapper_file = Path(plugin.source_loc) / plugin.entry
wrapper_file.chmod(0o755)
def install_to_python_virtual_environment(cloned_plugin: InstInfo):
'''Called during install in place of a subprocess.run list'''
# Delete symlink so that a venv wrapper can take it's place
(Path(cloned_plugin.source_loc) / cloned_plugin.entry).unlink()
# The original entrypoint is imported as a python module - ensure
# it has a .py extension. The wrapper can keep the original naming.
entry = Path(cloned_plugin.source_loc) / 'source' / cloned_plugin.entry
entry.rename(entry.with_suffix('.py'))
create_python3_venv(cloned_plugin)
if not hasattr(cloned_plugin, 'venv'):
raise InstallationFailure
logging.debug('virtual environment for cloned plugin: '
f'{cloned_plugin.venv}')
create_wrapper(cloned_plugin)
return cloned_plugin
python3venv = Installer('python3venv', 'text/x-python', exe='python3',
manager='pip', entry='{name}.py')
python3venv.add_entrypoint('{name}')
python3venv.add_entrypoint('__init__.py')
python3venv.add_dependency_file('requirements.txt')
python3venv.dependency_call = install_to_python_virtual_environment
poetryvenv = Installer('poetryvenv', 'text/x-python', exe='python3',
manager='poetry', entry='{name}.py')
poetryvenv.add_entrypoint('{name}')
poetryvenv.add_entrypoint('__init__.py')
poetryvenv.add_dependency_file('pyproject.toml')
poetryvenv.dependency_call = install_to_python_virtual_environment
pyprojectViaPip = Installer('pyprojectViaPip', 'text/x-python', exe='python3',
manager='pip', entry='{name}.py')
pyprojectViaPip.add_entrypoint('{name}')
pyprojectViaPip.add_entrypoint('__init__.py')
pyprojectViaPip.add_dependency_file('pyproject.toml')
pyprojectViaPip.dependency_call = install_to_python_virtual_environment
# Nodejs plugin installer
nodejs = Installer('nodejs', 'application/javascript', exe='node',
manager='npm', entry='{name}.js')
nodejs.add_entrypoint('{name}')
nodejs.add_dependency_call(['npm', 'install', '--omit=dev'])
nodejs.add_dependency_file('package.json')
INSTALLERS = [python3venv, poetryvenv, pyprojectViaPip, nodejs]
def help_alias(targets: list):
if len(targets) == 0:
parser.print_help(sys.stdout)
else:
print('try "reckless {} -h"'.format(' '.join(targets)))
sys.exit(1)
def _source_search(name: str, source: str) -> Union[InstInfo, None]:
"""Identify source type, retrieve contents, and populate InstInfo
if the relevant contents are found."""
root_dir = SourceDir(source)
source = InstInfo(name, root_dir.location, None)
if source.get_inst_details():
return source
return None
def _git_clone(src: InstInfo, dest: Union[PosixPath, str]) -> bool:
print(f'cloning {src.srctype} {src}')
if src.srctype == Source.GITHUB_REPO:
assert 'github.com' in src.source_loc
source = f"{GITHUB_COM}" + src.source_loc.split("github.com")[-1]
elif src.srctype in [Source.LOCAL_REPO, Source.OTHER_URL]:
source = src.source_loc
else:
return False
git = run(['git', 'clone', source, str(dest)], stdout=PIPE, stderr=PIPE,
text=True, check=False, timeout=60)
if git.returncode != 0:
for line in git.stderr:
logging.debug(line)
if Path(dest).exists():
remove_dir(str(dest))
print('Error: Failed to clone repo')
return False
return True
def get_temp_reckless_dir() -> PosixPath:
random_dir = 'reckless-{}'.format(str(hash(os.times()))[-9:])
new_path = Path(tempfile.gettempdir()) / random_dir
return new_path
def add_installation_metadata(installed: InstInfo,
original_request: InstInfo):
"""Document the install request and installation details for use when
updating the plugin."""
install_dir = Path(installed.source_loc)
assert install_dir.is_dir()
data = ('installation date\n'
f'{datetime.date.today().isoformat()}\n'
'installation time\n'
f'{int(time.time())}\n'
'original source\n'
f'{original_request.source_loc}\n'
'requested commit\n'
f'{original_request.commit}\n'
'installed commit\n'
f'{installed.commit}\n')
with open(install_dir / '.metadata', 'w') as metadata:
metadata.write(data)
def _checkout_commit(orig_src: InstInfo,
cloned_src: InstInfo,
cloned_path: PosixPath):
# Check out and verify commit/tag if source was a repository
if orig_src.srctype in [Source.LOCAL_REPO, Source.GITHUB_REPO,
Source.OTHER_URL]:
if orig_src.commit:
logging.debug(f"Checking out {orig_src.commit}")
checkout = Popen(['git', 'checkout', orig_src.commit],
cwd=str(cloned_path),
stdout=PIPE, stderr=PIPE)
checkout.wait()
if checkout.returncode != 0:
print('failed to checkout referenced '
f'commit {orig_src.commit}')
return None
else:
logging.debug("using latest commit of default branch")
# Log the commit we actually used (for installation metadata)
git = run(['git', 'rev-parse', 'HEAD'], cwd=str(cloned_path),
stdout=PIPE, stderr=PIPE, text=True, check=False, timeout=60)
if git.returncode == 0:
head_commit = git.stdout.splitlines()[0]
logging.debug(f'checked out HEAD: {head_commit}')
cloned_src.commit = head_commit
else:
logging.debug(f'unable to collect commit: {git.stderr}')
else:
if orig_src.commit:
logging.warning("unable to checkout commit/tag on non-repository "
"source")
return cloned_path
if cloned_src.subdir is not None:
return Path(cloned_src.source_loc) / cloned_src.subdir
return cloned_path
def _install_plugin(src: InstInfo) -> Union[InstInfo, None]:
"""make sure the repo exists and clone it."""
logging.debug(f'Install requested from {src}.')
if RECKLESS_CONFIG is None:
print('error: reckless install directory unavailable')
sys.exit(2)
# Use a unique directory for each cloned repo.
tmp_path = get_temp_reckless_dir()
if not create_dir(tmp_path):
logging.debug(f'failed to create {tmp_path}')
return None
clone_path = tmp_path / 'clone'
if not create_dir(tmp_path):
logging.debug(f'failed to create {clone_path}')
return None
# we rename the original repo here.
plugin_path = clone_path / src.name
inst_path = Path(RECKLESS_CONFIG.reckless_dir) / src.name
if Path(clone_path).exists():
logging.debug(f'{clone_path} already exists - deleting')
shutil.rmtree(clone_path)
if src.srctype == Source.DIRECTORY:
logging.debug(("copying local directory contents from"
f" {src.source_loc}"))
create_dir(clone_path)
shutil.copytree(src.source_loc, plugin_path)
elif src.srctype in [Source.LOCAL_REPO, Source.GITHUB_REPO,
Source.OTHER_URL]:
# clone git repository to /tmp/reckless-...
if not _git_clone(src, plugin_path):
return None
# FIXME: Validate path was cloned successfully.
# Depending on how we accessed the original source, there may be install
# details missing. Searching the cloned repo makes sure we have it.
cloned_src = _source_search(src.name, str(clone_path))
logging.debug(f'cloned_src: {cloned_src}')
if not cloned_src:
logging.debug('failed to find plugin after cloning repo.')
return None
# If a specific commit or tag was requested, check it out now.
plugin_path = _checkout_commit(src, cloned_src, plugin_path)
if not plugin_path:
return None
# Find a suitable installer
INSTALLER = None
for inst_method in INSTALLERS:
if not (inst_method.installable() and inst_method.executable()):
continue
if inst_method.dependency_file is not None:
if inst_method.dependency_file not in os.listdir(plugin_path):
continue
logging.debug(f"using installer {inst_method.name}")
INSTALLER = inst_method
break
if not INSTALLER:
logging.debug('Could not find a suitable installer method.')
return None
if not cloned_src.entry:
# The plugin entrypoint may not be discernable prior to cloning.
# Need to search the newly cloned directory, not the original
cloned_src.source_loc = plugin_path
# Relocate plugin to a staging directory prior to testing
staging_path = inst_path / 'source'
shutil.copytree(str(plugin_path), staging_path)
staged_src = cloned_src
# Because the source files are copied to a 'source' directory, the
# get_inst_details function no longer works. (dir must match plugin name)
# Set these manually instead.
staged_src.source_loc = str(staging_path.parent)
staged_src.srctype = Source.DIRECTORY
staged_src.subdir = None
# Create symlink in staging tree to redirect to the plugins entrypoint
Path(staging_path.parent / cloned_src.entry).\
symlink_to(staging_path / cloned_src.entry)
# try it out
if INSTALLER.dependency_call:
if isinstance(INSTALLER.dependency_call, types.FunctionType):
try:
staged_src = INSTALLER.dependency_call(staged_src)
except InstallationFailure:
return None
else:
for call in INSTALLER.dependency_call:
logging.debug(f"Install: invoking '{' '.join(call)}'")
if logging.root.level < logging.WARNING:
pip = Popen(call, cwd=staging_path, text=True)
else:
pip = Popen(call, cwd=staging_path, stdout=PIPE,
stderr=PIPE, text=True)
pip.wait()
# FIXME: handle output of multiple calls
if pip.returncode == 0:
print('dependencies installed successfully')
else:
print('error encountered installing dependencies')
if pip.stdout:
logging.debug(pip.stdout.read())
remove_dir(clone_path)
remove_dir(inst_path)
return None
test_log = []
try:
test = run([Path(staged_src.source_loc).joinpath(staged_src.entry)],
cwd=str(staging_path), stdout=PIPE, stderr=PIPE,
text=True, timeout=10)
for line in test.stderr.splitlines():
test_log.append(line)
returncode = test.returncode
except TimeoutExpired:
# If the plugin is still running, it's assumed to be okay.
returncode = 0
if returncode != 0:
logging.debug("plugin testing error:")
for line in test_log:
logging.debug(f' {line}')
print('plugin testing failed')
remove_dir(clone_path)
remove_dir(inst_path)
return None
add_installation_metadata(staged_src, src)
print(f'plugin installed: {inst_path}')
remove_dir(clone_path)
return staged_src
def install(plugin_name: str):
"""downloads plugin from source repos, installs and activates plugin"""
assert isinstance(plugin_name, str)
# Specify a tag or commit to checkout by adding @<tag> to plugin name
if '@' in plugin_name:
logging.debug("testing for a commit/tag in plugin name")
name, commit = plugin_name.split('@', 1)
else:
name = plugin_name
commit = None
logging.debug(f"Searching for {name}")
src = search(name)
if src:
src.commit = commit
logging.debug(f'Retrieving {src.name} from {src.source_loc}')
installed = _install_plugin(src)
if not installed:
print('installation aborted')
sys.exit(1)
# Match case of the containing directory
for dirname in os.listdir(RECKLESS_CONFIG.reckless_dir):
if dirname.lower() == installed.name.lower():
inst_path = Path(RECKLESS_CONFIG.reckless_dir)
inst_path = inst_path / dirname / installed.entry
RECKLESS_CONFIG.enable_plugin(inst_path)
enable(installed.name)
return
print(('dynamic activation failed: '
f'{installed.name} not found in reckless directory'))
sys.exit(1)
def uninstall(plugin_name: str):
"""disables plugin and deletes the plugin's reckless dir"""
assert isinstance(plugin_name, str)