Skip to content

Commit 7f5d028

Browse files
committed
incorporate suggestions
1 parent bd916c1 commit 7f5d028

File tree

8 files changed

+62
-56
lines changed

8 files changed

+62
-56
lines changed
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
apiVersion: v2
22
name: simln
3-
description: A Helm chart to deploy simln
3+
description: A Helm chart to deploy SimLN
44
version: 0.1.0
55
appVersion: "0.1.0"

resources/plugins/simln/charts/simln/files/sim.json

Lines changed: 0 additions & 16 deletions
This file was deleted.

resources/plugins/simln/charts/simln/templates/configmap.yaml

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,6 @@ kind: ConfigMap
33
metadata:
44
name: {{ include "mychart.fullname" . }}-data
55
data:
6-
sim.json: |
7-
{{ .Files.Get "files/sim.json" | nindent 4 }}
86
tls.cert: |
97
-----BEGIN CERTIFICATE-----
108
MIIB8TCCAZagAwIBAgIUJDsR6mmY+TaO9pCfjtotlbOkzJMwCgYIKoZIzj0EAwIw
@@ -19,11 +17,5 @@ data:
1917
IQDPofN0fEl5gTwCYhk3nZbjMqJhZ8BsSJ6K8XRhxr7zbwIhAPsgQCFOqUWg632O
2018
NEO53OQ6CIqnpxSskjsFNH4ZBQOE
2119
-----END CERTIFICATE-----
22-
tls.key: |
23-
-----BEGIN EC PRIVATE KEY-----
24-
MHcCAQEEIIcFtWTLQv5JaRRxdkPKkO98OrvgeztbZ7h8Ev/4UbE4oAoGCCqGSM49
25-
AwEHoUQDQgAEBVltIvaTlAQI/3FFatTqVflZuZdRJ0SmRMSJrFLPtp0fxE7hmteS
26-
t6gjQriy90fP8j9OJXBNAjt915kLY4zVvg==
27-
-----END EC PRIVATE KEY-----
2820
admin.macaroon.hex: |
2921
0201036c6e6402f801030a1062beabbf2a614b112128afa0c0b4fdd61201301a160a0761646472657373120472656164120577726974651a130a04696e666f120472656164120577726974651a170a08696e766f69636573120472656164120577726974651a210a086d616361726f6f6e120867656e6572617465120472656164120577726974651a160a076d657373616765120472656164120577726974651a170a086f6666636861696e120472656164120577726974651a160a076f6e636861696e120472656164120577726974651a140a057065657273120472656164120577726974651a180a067369676e6572120867656e657261746512047265616400000620b17be53e367290871681055d0de15587f6d1cd47d1248fe2662ae27f62cfbdc6

resources/plugins/simln/charts/simln/templates/pod.yaml

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,16 +7,20 @@ metadata:
77
mission: {{ .Values.name }}
88
spec:
99
initContainers:
10-
- name: "init-container"
10+
- name: "init"
1111
image: "busybox"
1212
command:
1313
- "sh"
1414
- "-c"
1515
args:
1616
- >
17-
cp /configmap/* /working;
18-
cd /working;
19-
cat admin.macaroon.hex | xxd -r -p > admin.macaroon
17+
cp /configmap/* /working &&
18+
cd /working &&
19+
cat admin.macaroon.hex | xxd -r -p > admin.macaroon &&
20+
while [ ! -f /working/sim.json ]; do
21+
echo "Waiting for /working/sim.json to exist..."
22+
sleep 1
23+
done
2024
volumeMounts:
2125
- name: {{ .Values.workingVolume.name }}
2226
mountPath: {{ .Values.workingVolume.mountPath }}

resources/plugins/simln/simln.py

Lines changed: 35 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import json
22
import logging
3-
import random
3+
import time
44
from pathlib import Path
55
from subprocess import run
66
from time import sleep
@@ -17,7 +17,9 @@
1717
get_default_namespace,
1818
get_mission,
1919
get_static_client,
20+
wait_for_init,
2021
wait_for_pod,
22+
write_file_to_container,
2123
)
2224
from warnet.plugins import get_plugins_directory_or
2325
from warnet.process import run_command
@@ -63,7 +65,7 @@ def warnet_register_plugin(register_command):
6365

6466

6567
# The group function name is then used in decorators to create commands. These commands are
66-
# available to users when the access your plugin from the command line in Warnet.
68+
# available to users when they access your plugin from the command line in Warnet.
6769
@simln.command()
6870
def run_demo():
6971
"""Run the SimLN Plugin demo"""
@@ -128,22 +130,40 @@ def get_example_activity():
128130

129131
def _launch_activity(activity: list[dict], user_dir: Optional[str] = None) -> str:
130132
"""Launch a SimLN chart which includes the `activity`"""
131-
random_digits = "".join(random.choices("0123456789", k=10))
132133
plugin_dir = get_plugins_directory_or(user_dir)
133-
_generate_nodes_file(activity, plugin_dir / Path("simln/charts/simln/files/sim.json"))
134-
command = f"helm upgrade --install simln-{random_digits} {plugin_dir}/simln/charts/simln"
135-
log.info(f"generate activity: {command}")
134+
135+
timestamp = int(time.time())
136+
name = f"simln-{timestamp}"
137+
138+
command = f"helm upgrade --install {timestamp} {plugin_dir}/simln/charts/simln"
136139
run_command(command)
137-
return f"simln-simln-{random_digits}"
140+
141+
activity_json = _generate_activity_json(activity)
142+
wait_for_init(name, namespace=get_default_namespace(), quiet=True)
143+
if write_file_to_container(
144+
name,
145+
"init",
146+
"/working/sim.json",
147+
activity_json,
148+
namespace=get_default_namespace(),
149+
quiet=True,
150+
):
151+
return name
152+
else:
153+
raise SimLNError(f"Could not write sim.json to the init container: {name}")
138154

139155

140156
# Take note of how click expects us to explicitly declare command line arguments.
141157
@simln.command()
142158
@click.argument("activity", type=str)
143159
@click.pass_context
144160
def launch_activity(ctx, activity: str):
145-
"""Takes a SimLN Activity which is a JSON list of objects."""
146-
parsed_activity = json.loads(activity)
161+
"""Deploys a SimLN Activity which is a JSON list of objects"""
162+
try:
163+
parsed_activity = json.loads(activity)
164+
except json.JSONDecodeError:
165+
log.error("Invalid JSON input for activity.")
166+
raise click.BadArgumentUsage("Activity must be a valid JSON string.") from None
147167
user_dir = ctx.obj.get(USER_DIR_TAG)
148168
print(_launch_activity(parsed_activity, user_dir))
149169

@@ -283,7 +303,7 @@ def warnet(cmd: str = "--help"):
283303
return proc.stdout.decode()
284304

285305

286-
def _generate_nodes_file(activity: list[dict], output_file: Path = Path("nodes.json")):
306+
def _generate_activity_json(activity: list[dict]) -> str:
287307
nodes = []
288308

289309
for i in get_mission(LIGHTNING_MISSION):
@@ -298,8 +318,7 @@ def _generate_nodes_file(activity: list[dict], output_file: Path = Path("nodes.j
298318

299319
data = {"nodes": nodes, "activity": activity}
300320

301-
with open(output_file, "w") as f:
302-
json.dump(data, f, indent=2)
321+
return json.dumps(data, indent=2)
303322

304323

305324
def manual_open_channels():
@@ -342,7 +361,7 @@ def wait_for_two_txs():
342361
warnet("bitcoin rpc tank-0000 -generate 10")
343362

344363

345-
def _rpc(pod, method: str, params: tuple[str, ...]) -> str:
364+
def _sh(pod, method: str, params: tuple[str, ...]) -> str:
346365
namespace = get_default_namespace()
347366

348367
sclient = get_static_client()
@@ -356,7 +375,7 @@ def _rpc(pod, method: str, params: tuple[str, ...]) -> str:
356375
sclient.connect_get_namespaced_pod_exec,
357376
pod,
358377
namespace,
359-
container="simln",
378+
container=CONTAINER,
360379
command=cmd,
361380
stderr=True,
362381
stdin=False,
@@ -383,6 +402,6 @@ def _rpc(pod, method: str, params: tuple[str, ...]) -> str:
383402
@click.argument("pod", type=str)
384403
@click.argument("method", type=str)
385404
@click.argument("params", type=str, nargs=-1) # this will capture all remaining arguments
386-
def rpc(pod: str, method: str, params: tuple[str, ...]):
405+
def sh(pod: str, method: str, params: tuple[str, ...]):
387406
"""Run commands on a pod"""
388-
print(_rpc(pod, method, params))
407+
print(_sh(pod, method, params))

src/warnet/k8s.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -319,7 +319,7 @@ def wait_for_pod_ready(name, namespace, timeout=300):
319319
return False
320320

321321

322-
def wait_for_init(pod_name, timeout=300, namespace: Optional[str] = None):
322+
def wait_for_init(pod_name, timeout=300, namespace: Optional[str] = None, quiet: bool = False):
323323
namespace = get_default_namespace_or(namespace)
324324
sclient = get_static_client()
325325
w = watch.Watch()
@@ -332,10 +332,12 @@ def wait_for_init(pod_name, timeout=300, namespace: Optional[str] = None):
332332
continue
333333
for init_container_status in pod.status.init_container_statuses:
334334
if init_container_status.state.running:
335-
print(f"initContainer in pod {pod_name} ({namespace}) is ready")
335+
if not quiet:
336+
print(f"initContainer in pod {pod_name} ({namespace}) is ready")
336337
w.stop()
337338
return True
338-
print(f"Timeout waiting for initContainer in {pod_name} ({namespace})to be ready.")
339+
if not quiet:
340+
print(f"Timeout waiting for initContainer in {pod_name} ({namespace}) to be ready.")
339341
return False
340342

341343

@@ -389,7 +391,7 @@ def wait_for_pod(pod_name, timeout_seconds=10, namespace: Optional[str] = None):
389391

390392

391393
def write_file_to_container(
392-
pod_name, container_name, dst_path, data, namespace: Optional[str] = None
394+
pod_name, container_name, dst_path, data, namespace: Optional[str] = None, quiet: bool = False
393395
):
394396
namespace = get_default_namespace_or(namespace)
395397
sclient = get_static_client()
@@ -421,7 +423,8 @@ def write_file_to_container(
421423
stdout=True,
422424
tty=False,
423425
)
424-
print(f"Successfully copied data to {pod_name}({container_name}):{dst_path}")
426+
if not quiet:
427+
print(f"Successfully copied data to {pod_name}({container_name}):{dst_path}")
425428
return True
426429
except Exception as e:
427430
print(f"Failed to copy data to {pod_name}({container_name}):{dst_path}:\n{e}")

src/warnet/plugins.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,12 @@ def plugins():
3737
pass
3838

3939

40+
@plugins.command()
41+
def run(plugin: str):
42+
"""Run a file"""
43+
pass
44+
45+
4046
@plugins.command()
4147
@click.pass_context
4248
def ls(ctx):

test/simln_test.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,6 @@
1515

1616
lightning_selector = "mission=lightning"
1717

18-
UP = "\033[A"
19-
DOWN = "\033[B"
20-
ENTER = "\n"
21-
2218

2319
class SimLNTest(TestBase):
2420
def __init__(self):
@@ -72,6 +68,7 @@ def run_activity(self):
7268
activity_result = run_command(cmd)
7369
activity = json.loads(activity_result)
7470
pod_result = run_command(f"warnet plugins simln launch-activity '{json.dumps(activity)}'")
71+
self.log.info(f"launched activity: {pod_result}")
7572
partial_func = partial(self.found_results_remotely, pod_result.strip())
7673
self.wait_for_predicate(partial_func)
7774
self.log.info("Successfully ran activity")
@@ -82,6 +79,7 @@ def run_activity_with_user_dir(self):
8279
activity_result = run_command(cmd)
8380
activity = json.loads(activity_result)
8481
pod_result = run_command(f"warnet plugins simln launch-activity '{json.dumps(activity)}'")
82+
self.log.info(f"launched activity: {pod_result}")
8583
partial_func = partial(self.found_results_remotely, pod_result.strip())
8684
self.wait_for_predicate(partial_func)
8785
run_command("cd ../")
@@ -107,10 +105,10 @@ def found_results_remotely(self, pod: Optional[str] = None) -> bool:
107105
pod_names = ast.literal_eval(pod_names_literal)
108106
pod = pod_names[0]
109107
self.log.info(f"Checking for results file in {pod}")
110-
results_file = run_command(f"warnet plugins simln rpc {pod} ls /working/results").strip()
108+
results_file = run_command(f"warnet plugins simln sh {pod} ls /working/results").strip()
111109
self.log.info(f"Results file: {results_file}")
112110
results = run_command(
113-
f"warnet plugins simln rpc {pod} cat /working/results/{results_file}"
111+
f"warnet plugins simln sh {pod} cat /working/results/{results_file}"
114112
).strip()
115113
self.log.info(results)
116114
return results.find("Success") > 0

0 commit comments

Comments
 (0)