drekar-launch 0.1.2__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.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2011-2020 Wason Technology, LLC
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,141 @@
1
+ Metadata-Version: 2.1
2
+ Name: drekar-launch
3
+ Version: 0.1.2
4
+ Summary: A simple launcher for Robotics applications
5
+ Author-email: John Wason <wason@wasontech.com>
6
+ License: Apache-2.0
7
+ Requires-Python: >=3.8
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE.txt
10
+ Requires-Dist: pyyaml
11
+ Requires-Dist: appdirs
12
+ Requires-Dist: drekar-launch-process
13
+ Requires-Dist: jinja2
14
+ Provides-Extra: test
15
+ Requires-Dist: pytest ; extra == 'test'
16
+ Requires-Dist: pywin32 ; (platform_system == "Windows") and extra == 'test'
17
+
18
+ # Drekar Launch
19
+
20
+ `drekar-launch` is a simple tool to launch and manage multiple processes. It is based on the process management code
21
+ extracted from the `pyri-core` module, part of the PyRI Open-Source Teach Pendant
22
+
23
+ `drekar-launch` has a similar goal to `roslaunch`, but
24
+ designed to be simpler and independent of ROS. It also has improvements in handling Windows process management
25
+ using Windows Job Objects. Yaml files are used to configure the processes to launch.
26
+
27
+ `drekar-launch` will show a minimal GUI windows when the `--gui` is specified. This window shows same basic
28
+ information, and has a "Stop All" button that will shut down all tasks. This GUI is useful if `drekar-launch` is
29
+ started interactively by the user rather than running as a background service.
30
+
31
+ See also `drekar-launch-process`, a companion library that contains utility functions to use within processes
32
+ hosted by `drekar-launch`. The functions `wait_exit()` and `wait_exit_callback()` assist in receiving shutdown
33
+ signals in a reliable cross-platform manner.
34
+
35
+ See `drekar-launch-process`: https://github.com/johnwason/drekar-launch-process
36
+
37
+ ## Installation
38
+
39
+ ```
40
+ python -m pip install --user drekar-launch
41
+ ```
42
+
43
+ On Ubuntu, it may be necessary to replace `python` with `python3`.
44
+
45
+ ## Usage
46
+
47
+ Yaml files are used to configure the processes to launch. The following is an example of a `drekar-launch.yaml`
48
+ file that launches two Python servers.
49
+
50
+ ```yaml
51
+ name: example_http_servers
52
+ tasks:
53
+ - name: http_server_1
54
+ program: python.exe
55
+ args: example_http_server.py 8100 Server1
56
+ cwd: .
57
+ - name: http_server_2
58
+ program: python.exe
59
+ args:
60
+ - example_http_server.py
61
+ - 8101
62
+ - Hello from Server2!
63
+ start-delay: 1
64
+ ```
65
+
66
+ The `example_http_server.py` program uses `drekar-launch-process` to wait for the shutdown signal.
67
+
68
+ In this example, the `name` field is the name of the launch group. The `tasks` section contains a list of tasks to
69
+ launch. The following fields are used to configure the launch of each task:
70
+
71
+ * `name`: The name of the process
72
+ * `program`: The program to execute
73
+ * `args`: The command line arguments to pass to `program`
74
+ * `cwd` (optional): The working directory to run the program. Defaults to current directory.
75
+ * `start-delay` (optional): Delay the start of the program by specified seconds
76
+ * `restart` (optional): If true, process will be restarted if it exits
77
+ * `restart-backoff` (optional): Delay in seconds before restarting after exit
78
+ * `quit-on-terminate` (optional): If `true`, all processes will exit if the process exits
79
+ * `tags` (optional): Unused
80
+ * `environment` (optional): Key/value pairs to add to environment
81
+ * `env-file` (optional): File of environmental variable to override the environment
82
+
83
+ `drekar-launch` by default will load `drekar-launch.yaml` in the current directory. To run with default settings,
84
+ simply call `drekar-launch`.
85
+
86
+ ```
87
+ drekar-launch
88
+ ```
89
+
90
+ In some cases, it may be necessary to use `python` to launch. The `drekar-launch` executable may not be installed
91
+ to `PATH`.
92
+
93
+ ```
94
+ python -m drekar_launch
95
+ ```
96
+
97
+ `drekar-launch` accepts the following optional command line arguments:
98
+
99
+ * `--config=`: Specify an alternative configuration file
100
+ * `--config-js=`: Specify an alternative configuration file that uses Jinja2 templates
101
+ * `--cwd=`: Set the default working directory for processes
102
+ * `--name=`: Override the name of the launch group
103
+ * `--quiet`: Flag to suppress outputting to the terminal
104
+ * `--gui`: Show a simple GUI to stop the tasks
105
+
106
+ Drekar Launch saves the output to log files located in the following locations:
107
+
108
+ * Windows: `%LOCALAPPDATA%\drekar-launch\drekar-launch\Logs`
109
+ * Linux: `$HOME/.cache/SuperApp/log`
110
+ * Mac OS: `$HOME//Library/Logs/drekar-launch`
111
+
112
+ Logs should be periodically cleaned if too much disk space is used.
113
+
114
+ *TODO: Add automatic log cleaning.*
115
+
116
+ Jinja2 Templates can be used to generate configurations that fill in values at runtime or even include other
117
+ templates. See the Jinja2 documentation (https://jinja.palletsprojects.com/) for more information on using templates.
118
+
119
+ Four variables are available in the template:
120
+
121
+ * `configpath`: Absolute path to the configuration file
122
+ * `configdir`: Directory containing the configuration file
123
+ * `env`: Environmental variables
124
+ * `platform`: Current platform of the system as returned by `sys.platform`. Typically `win32`, `linux`, or `darwin` (Mac OS)
125
+ * `vars`: Extra variables passed on the command line. Use `--var-name=value`, where `name` and `value` are replaced with specific values.
126
+
127
+ For example, if `CONDA_PREFIX` needs to be used:
128
+
129
+ ```yaml
130
+ name: example_http_servers
131
+ tasks:
132
+ - name: http_server_1
133
+ program: {{ env["CONDA_PREFIX"] }}/python.exe
134
+ args: {{ configdir }}/example_http_server.py 8100 Server1
135
+ cwd: {{ env["CONDA_PREFIX"] }}
136
+ ```
137
+
138
+
139
+ ## License
140
+
141
+ Apache 2.0
@@ -0,0 +1,7 @@
1
+ drekar_launch.py,sha256=JrvyCd5geZVJ082Lnt1QwmQTwFnmaI1HD4UC9bw9cjg,31054
2
+ drekar_launch-0.1.2.dist-info/LICENSE.txt,sha256=Tl1tRxWGtrUEp-8aQr9k8kNBVeVc0FnOcSY8m7eKPfc,11554
3
+ drekar_launch-0.1.2.dist-info/METADATA,sha256=j5H51YeoJD3GvLpSbXSctPUaL-1BrqE8dr25AtTG3xw,5450
4
+ drekar_launch-0.1.2.dist-info/WHEEL,sha256=pkctZYzUS4AYVn6dJ-7367OJZivF2e8RA9b_ZBjif18,92
5
+ drekar_launch-0.1.2.dist-info/entry_points.txt,sha256=6tYJlxAt1he_nlcz1XIWGuG25TY3CHKXlLz3IdOMG6I,53
6
+ drekar_launch-0.1.2.dist-info/top_level.txt,sha256=RgrbC56bqzVppX9z-Js4DoCjJWX2O9yw1dDjzoqILfY,14
7
+ drekar_launch-0.1.2.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.40.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ drekar-launch = drekar_launch:main
@@ -0,0 +1 @@
1
+ drekar_launch
drekar_launch.py ADDED
@@ -0,0 +1,785 @@
1
+ import argparse
2
+ from contextlib import suppress
3
+ from ctypes import ArgumentError
4
+ import asyncio
5
+ import gc
6
+ import importlib
7
+ import shutil
8
+ import yaml
9
+ from typing import NamedTuple, List, Dict
10
+ from enum import Enum
11
+ import threading
12
+ import traceback
13
+ import appdirs
14
+ from pathlib import Path
15
+ import sys
16
+ from datetime import datetime
17
+ import os
18
+ import time
19
+ import signal
20
+ import subprocess
21
+ import jinja2
22
+ import drekar_launch_process
23
+
24
+
25
+ class DrekarTask(NamedTuple):
26
+ name: str
27
+ program: str
28
+ cwd: str
29
+ args: List[str]
30
+ restart: bool
31
+ restart_backoff: float
32
+ tags: List[str]
33
+ environment: Dict[str,str]
34
+ start_delay: float
35
+ quit_on_terminate: bool
36
+
37
+ # Based on MS Windows service states
38
+ class ProcessState(Enum):
39
+ STOPPED = 0x1
40
+ START_PENDING = 0x2
41
+ STOP_PENDING = 0x3
42
+ RUNNING = 0x4
43
+ CONTINUE_PENDING = 0x5
44
+ PAUSE_PENDING = 0x6
45
+ PAUSED = 0x7
46
+
47
+ class DrekarProcess:
48
+ def __init__(self, parent, task_launch, log_dir, loop):
49
+ self.parent = parent
50
+ self.task_launch = task_launch
51
+ self.log_dir = log_dir
52
+ self.loop = loop
53
+ self._keep_going = True
54
+ self._process = None
55
+ self._term_attempts = 0
56
+ self.screen = parent.screen
57
+ self.exit_status = -1
58
+
59
+ async def run(self):
60
+ s = self.task_launch
61
+ stdout_log_fname = self.log_dir.joinpath(f"{s.name}.log")
62
+ stderr_log_fname = self.log_dir.joinpath(f"{s.name}.stderr.log")
63
+ with open(stdout_log_fname,"w") as stdout_log, open(stderr_log_fname,"w") as stderr_log:
64
+ if s.start_delay > 0:
65
+ stderr_log.write(f"Delaying starting {s.name} for {s.start_delay} seconds...\n")
66
+ with suppress(asyncio.TimeoutError):
67
+ await asyncio.wait_for(self.parent.exit_event.wait(),timeout=s.start_delay)
68
+ if not self._keep_going:
69
+ return
70
+ while self._keep_going:
71
+ try:
72
+ self.parent.process_state_changed(s.name,ProcessState.START_PENDING)
73
+ stderr_log.write(f"Starting process {s.name}...\n")
74
+ python_exe = sys.executable
75
+ self._process = await create_subprocess_exec(s.program, s.args, s.environment, s.cwd)
76
+ # print(f"process pid: {self._process.pid}")
77
+ stderr_log.write(f"Process {s.name} started\n\n")
78
+ self.parent.process_state_changed(s.name,ProcessState.RUNNING)
79
+ stdout_read_task = asyncio.ensure_future(self._process.stdout.readline())
80
+ stderr_read_task = asyncio.ensure_future(self._process.stderr.readline())
81
+ while True: #self._keep_going:
82
+ wait_tasks = list(filter(lambda x: x is not None, [stdout_read_task, stderr_read_task]))
83
+ if len(wait_tasks) == 0:
84
+ break
85
+ done, pending = await asyncio.wait(wait_tasks,return_when=asyncio.FIRST_COMPLETED)
86
+ if stderr_read_task in done:
87
+ stderr_line = await stderr_read_task
88
+ if len(stderr_line) == 0:
89
+ stderr_read_task = None
90
+ else:
91
+ stderr_log.write(stderr_line.decode("utf-8"))
92
+ stderr_log.flush()
93
+ stderr_read_task = asyncio.ensure_future(self._process.stderr.readline())
94
+ if self.screen:
95
+ print(f"[{self.task_launch.name}] " + stderr_line.decode("utf-8"),end="",file=sys.stderr)
96
+ if stdout_read_task in done:
97
+ stdout_line = await stdout_read_task
98
+ if len(stdout_line) == 0:
99
+ stdout_read_task = None
100
+ else:
101
+ stdout_log.write(stdout_line.decode("utf-8"))
102
+ stdout_log.flush()
103
+ stdout_read_task = asyncio.ensure_future(self._process.stdout.readline())
104
+ if self.screen:
105
+ print(f"[{self.task_launch.name}] " + stdout_line.decode("utf-8"),end="",file=sys.stdout)
106
+ if stdout_read_task is None and stderr_read_task is None:
107
+ break
108
+ await self._process.wait()
109
+ self.exit_status = self._process.get_exit_status()
110
+ if self.exit_status != 0:
111
+ stderr_log.write(f"Process {s.name} exited with status {self.exit_status}\n")
112
+ if self.screen:
113
+ print(f"[{self.task_launch.name}] Process {s.name} exited with status {self.exit_status}",file=sys.stderr)
114
+ self.parent.process_state_changed(s.name,ProcessState.STOPPED)
115
+ except:
116
+ self._process = None
117
+ self.parent.process_state_changed(s.name,ProcessState.STOPPED)
118
+ traceback.print_exc()
119
+ stderr_log.write(f"\nProcess {s.name} error:\n")
120
+ stderr_log.write(traceback.format_exc())
121
+ self._process = None
122
+ if s.quit_on_terminate:
123
+ self.parent.exit_event.set()
124
+ break
125
+ if not s.restart:
126
+ break
127
+ if self._keep_going:
128
+ await self.exit_event.wait(s.restart_backoff)
129
+
130
+ @property
131
+ def process_state(self):
132
+ pass
133
+
134
+ @property
135
+ def stopped(self):
136
+ return self._process == None
137
+
138
+ def close(self):
139
+ self._keep_going = False
140
+ if self._process:
141
+ self._process.send_term(self._term_attempts)
142
+ self._term_attempts += 1
143
+
144
+ def kill(self):
145
+ p = self._process
146
+ if p is None:
147
+ return
148
+ try:
149
+ self._process.kill()
150
+ except:
151
+ traceback.print_exc()
152
+
153
+ class DrekarCore:
154
+ def __init__(self, name, task_launches, exit_event, log_dir, screen, loop):
155
+ self.name = name
156
+ self.task_launches = dict()
157
+ self._closed = False
158
+ for s in task_launches:
159
+ self.task_launches[s.name] = s
160
+ self.log_dir = log_dir
161
+ self.loop = loop
162
+ self.screen=screen
163
+
164
+ self._subprocesses = dict()
165
+ self._lock = threading.RLock()
166
+ self.exit_event = exit_event
167
+
168
+ def _do_start(self,s):
169
+ p = DrekarProcess(self, s, self.log_dir, self.loop)
170
+ self._subprocesses[s.name] = p
171
+ self.loop.create_task(p.run())
172
+
173
+ def start_all(self):
174
+ with self._lock:
175
+ for name,s in self.task_launches.items():
176
+ if name not in self._subprocesses:
177
+ self._do_start(s)
178
+
179
+ def start(self, name):
180
+ with self._lock:
181
+ if self._closed:
182
+ assert False, "Already closed"
183
+ try:
184
+ s = self.task_launches[name]
185
+ except KeyError:
186
+ raise ArgumentError(f"Invalid service requested: {name}")
187
+ if name not in self._subprocesses:
188
+ self._do_start(s)
189
+
190
+ def process_state_changed(self, process_name, state):
191
+ print(f"Process changed {process_name} {state}")
192
+ if self._closed:
193
+ if state == ProcessState.STOPPED:
194
+ with self._lock:
195
+ if process_name in self._subprocesses:
196
+ del self._subprocesses[process_name]
197
+
198
+ def check_deps_status(self, deps):
199
+ return True
200
+
201
+ def close(self):
202
+ with self._lock:
203
+ if self._closed:
204
+ return
205
+ self._closed = True
206
+
207
+ for p in self._subprocesses.values():
208
+ try:
209
+ p.close()
210
+ except Exception:
211
+ traceback.print_exc()
212
+ pass
213
+
214
+ async def wait_all_closed(self):
215
+ try:
216
+ t1 = time.time()
217
+ t_last_sent_close = 0
218
+ while True:
219
+ t_diff = time.time() - t1
220
+ if t_diff > 15:
221
+ break
222
+ running_count = 0
223
+ with self._lock:
224
+ for p in self._subprocesses.values():
225
+ if not p.stopped:
226
+ running_count += 1
227
+ if running_count == 0:
228
+ break
229
+ await asyncio.sleep(0.1)
230
+ if t_diff > t_last_sent_close + 1:
231
+ t_last_sent_close = t_diff
232
+ with self._lock:
233
+ for p in self._subprocesses.values():
234
+ if not p.stopped:
235
+ try:
236
+ p.close()
237
+ except Exception:
238
+ traceback.print_exc()
239
+ pass
240
+
241
+ running_count = 0
242
+ with self._lock:
243
+ for p in self._subprocesses.values():
244
+ if not p.stopped:
245
+ running_count += 1
246
+ try:
247
+ p.kill()
248
+ except Exception:
249
+ traceback.print_exc()
250
+
251
+ if running_count != 0:
252
+ print("Sending processes still running SIGKILL")
253
+ time.sleep(2)
254
+
255
+ #self._loop.stop()
256
+ except:
257
+ traceback.print_exc()
258
+
259
+ def get_exit_status(self):
260
+ exit_status = 0
261
+ with self._lock:
262
+ for p in self._subprocesses.values():
263
+ if p.exit_status != 0:
264
+ exit_status = p.exit_status
265
+ return exit_status
266
+
267
+
268
+ async def create_subprocess_exec(process, args, env, cwd):
269
+ if sys.platform == "win32":
270
+ job_handle = subprocess_impl_win32.win32_create_job_object()
271
+
272
+ process = await asyncio.create_subprocess_exec(process,*args, \
273
+ stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.PIPE,\
274
+ env=env, cwd=cwd, creationflags=subprocess_impl_win32.CREATE_SUSPENDED \
275
+ | subprocess.CREATE_NEW_PROCESS_GROUP
276
+ ,close_fds=True)
277
+
278
+ subprocess_impl_win32.win32_attach_job_and_resume_process(process, job_handle)
279
+
280
+ return DrekarSubprocessImpl(process,job_handle)
281
+
282
+ else:
283
+ #TODO: Use "start_new_session=True" arg for new process
284
+ process = await asyncio.create_subprocess_exec(process,*args, \
285
+ stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.PIPE,\
286
+ env=env, cwd=cwd, close_fds=True, start_new_session=True )
287
+ return DrekarSubprocessImpl(process)
288
+
289
+
290
+ class DrekarSubprocessImpl:
291
+ def __init__(self, asyncio_subprocess, job_handle = None):
292
+ self._process = asyncio_subprocess
293
+ self._job_handle = job_handle
294
+ # TODO: Linux
295
+
296
+ @property
297
+ def process(self):
298
+ return self._process
299
+
300
+ @property
301
+ def stdout(self):
302
+ return self._process.stdout
303
+
304
+ @property
305
+ def stderr(self):
306
+ return self._process.stderr
307
+
308
+ @property
309
+ def pid(self):
310
+ return self._process.pid
311
+
312
+ def wait(self):
313
+ return self._process.wait()
314
+
315
+ def kill(self):
316
+ self._process.kill()
317
+
318
+ def send_term(self, attempt_count):
319
+ if sys.platform == "win32":
320
+ if attempt_count > 3:
321
+ subprocess_impl_win32._win32_send_ctrl_c_event(self._process.pid)
322
+ else:
323
+ subprocess_impl_win32.win32_send_job_wm_close(self._job_handle)
324
+ else:
325
+ import signal
326
+ pid = self._process.pid
327
+ pgid = os.getpgid(pid)
328
+ os.killpg(pgid, signal.SIGINT)
329
+
330
+ def close(self):
331
+ if sys.platform == "win32":
332
+ subprocess_impl_win32.win32_close_job_object(self._job_handle)
333
+ else:
334
+ try:
335
+ self._process.kill()
336
+ except Exception:
337
+ pass
338
+
339
+ def get_exit_status(self):
340
+ return self._process.returncode
341
+
342
+
343
+ if sys.platform == "win32":
344
+ import ctypes.wintypes
345
+ class _JOBOBJECT_BASIC_LIMIT_INFORMATION(ctypes.Structure):
346
+ _fields_ = [
347
+ ('PerProcessUserTimeLimit', ctypes.wintypes.LARGE_INTEGER),
348
+ ('PerJobUserTimeLimit', ctypes.wintypes.LARGE_INTEGER),
349
+ ('LimitFlags', ctypes.wintypes.DWORD),
350
+ ('MinimumWorkingSetSize', ctypes.c_size_t),
351
+ ('MaximumWorkingSetSize', ctypes.c_size_t),
352
+ ('ActiveProcessLimit', ctypes.wintypes.DWORD),
353
+ ('Affinity', ctypes.POINTER(ctypes.c_ulong)),
354
+ ('PriorityClass', ctypes.wintypes.DWORD),
355
+ ('SchedulingClass', ctypes.wintypes.DWORD)
356
+ ]
357
+
358
+ class _IO_COUNTERS(ctypes.Structure):
359
+ _fields_ = [
360
+ ('ReadOperationCount',ctypes.c_ulonglong),
361
+ ('WriteOperationCount',ctypes.c_ulonglong),
362
+ ('OtherOperationCount',ctypes.c_ulonglong),
363
+ ('ReadTransferCount',ctypes.c_ulonglong),
364
+ ('WriteTransferCount',ctypes.c_ulonglong),
365
+ ('OtherTransferCount',ctypes.c_ulonglong),
366
+ ]
367
+
368
+ class _JOBOBJECT_EXTENDED_LIMIT_INFORMATION(ctypes.Structure):
369
+ _fields_ = [
370
+ ('BasicLimitInformation',_JOBOBJECT_BASIC_LIMIT_INFORMATION),
371
+ ('IoInfo', _IO_COUNTERS),
372
+ ('ProcessMemoryLimit', ctypes.c_size_t),
373
+ ('JobMemoryLimit', ctypes.c_size_t),
374
+ ('PeakProcessMemoryUsed', ctypes.c_size_t),
375
+ ('PeakJobMemoryUsed', ctypes.c_size_t)
376
+ ]
377
+
378
+ class _THREADENTRY32(ctypes.Structure):
379
+ _fields_ = [
380
+ ("dwSize", ctypes.c_ulong),
381
+ ("cntUsage", ctypes.c_ulong),
382
+ ("th32ThreadID", ctypes.c_ulong),
383
+ ("th32OwnerProcessID", ctypes.c_ulong),
384
+ ("tpBasePri", ctypes.c_ulong),
385
+ ("tpDeltaPri", ctypes.c_ulong),
386
+ ("dwFlags", ctypes.c_ulong)
387
+ ]
388
+
389
+ class _JOBOBJECT_BASIC_PROCESS_ID_LIST(ctypes.Structure):
390
+ _fields_ = [
391
+ ("NumberOfAssignedProcesses", ctypes.wintypes.DWORD),
392
+ ("NumberOfProcessIdsInList", ctypes.wintypes.DWORD),
393
+ ("ProcessIdList", ctypes.c_size_t*16384)
394
+ ]
395
+ class subprocess_impl_win32:
396
+
397
+ WNDENUMPROC = ctypes.WINFUNCTYPE(ctypes.wintypes.BOOL,ctypes.wintypes.HWND,ctypes.wintypes.LPARAM)
398
+
399
+
400
+ JobObjectBasicLimitInformation = 2
401
+ JobObjectBasicProcessIdList = 3
402
+ JobObjectExtendedLimitInformation = 9
403
+ JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x00002000
404
+ PROCESS_SET_QUOTA = 0x0100
405
+ PROCESS_TERMINATE = 0x0001
406
+ CREATE_SUSPENDED = 0x00000004
407
+
408
+ TH32CS_SNAPTHREAD = 0x00000004
409
+ THREAD_SUSPEND_RESUME = 0x0002
410
+
411
+ HWND_MESSAGE = ctypes.wintypes.HWND(-3)
412
+ WM_CLOSE = 16
413
+
414
+ def win32_create_job_object():
415
+ job = ctypes.windll.kernel32.CreateJobObjectW(None, None)
416
+ job_limits = _JOBOBJECT_EXTENDED_LIMIT_INFORMATION()
417
+ res = ctypes.windll.kernel32.QueryInformationJobObject(job, subprocess_impl_win32.JobObjectExtendedLimitInformation, ctypes.pointer(job_limits), ctypes.sizeof(job_limits), None)
418
+ assert "Internal error, could not query win32 job object information"
419
+ job_limits.BasicLimitInformation.LimitFlags |= subprocess_impl_win32.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
420
+ res = ctypes.windll.kernel32.SetInformationJobObject(job, subprocess_impl_win32.JobObjectExtendedLimitInformation, ctypes.pointer(job_limits), ctypes.sizeof(job_limits))
421
+ assert res, "Internal error, could not set win32 job object information"
422
+ #current_process = ctypes.windll.kernel32.OpenProcess(PROCESS_SET_QUOTA | PROCESS_TERMINATE, False, ctypes.windll.kernel32.GetCurrentProcessId())
423
+ #res = ctypes.windll.kernel32.AssignProcessToJobObject(job, current_process)
424
+ #assert res, "Internal error, could not assign win32 process to job"
425
+ return job
426
+
427
+ def win32_attach_job_and_resume_process(asyncio_process, job):
428
+
429
+ h = ctypes.windll.kernel32.OpenProcess(subprocess_impl_win32.PROCESS_SET_QUOTA | subprocess_impl_win32.PROCESS_TERMINATE, False, asyncio_process.pid)
430
+ res = ctypes.windll.kernel32.AssignProcessToJobObject(job, h)
431
+ assert res, "Internal error, could not assign win32 process to job"
432
+ ctypes.windll.kernel32.CloseHandle(h)
433
+
434
+ subprocess_impl_win32.win32_resume_process(asyncio_process.pid)
435
+
436
+ def win32_close_job_object(handle):
437
+ if handle is None:
438
+ return
439
+ ctypes.windll.kernel32.CloseHandle(handle)
440
+
441
+ def win32_get_thread_ids(pid):
442
+
443
+ thread_ids = []
444
+
445
+ hThreadSnap = ctypes.windll.kernel32.CreateToolhelp32Snapshot(subprocess_impl_win32.TH32CS_SNAPTHREAD, pid)
446
+ try:
447
+ te32 = _THREADENTRY32()
448
+ te32.dwSize = ctypes.sizeof(_THREADENTRY32)
449
+ if ctypes.windll.kernel32.Thread32First(hThreadSnap, ctypes.byref(te32)) == 0:
450
+ pass
451
+
452
+ else:
453
+ while True:
454
+ if pid == te32.th32OwnerProcessID:
455
+ thread_ids.append(te32.th32ThreadID)
456
+
457
+ if ctypes.windll.kernel32.Thread32Next(hThreadSnap, ctypes.byref(te32)) == 0:
458
+ break
459
+ finally:
460
+ ctypes.windll.kernel32.CloseHandle(hThreadSnap)
461
+ return sorted(thread_ids)
462
+
463
+ def win32_resume_process(pid):
464
+ thread_ids = subprocess_impl_win32.win32_get_thread_ids(pid)
465
+ for thread_id in thread_ids:
466
+ thread_h = ctypes.windll.kernel32.OpenThread(subprocess_impl_win32.THREAD_SUSPEND_RESUME, False, thread_id)
467
+ ctypes.windll.kernel32.ResumeThread(thread_h)
468
+ ctypes.windll.kernel32.CloseHandle(thread_h)
469
+
470
+ def win32_send_job_wm_close(job):
471
+ win32_thread_info = _JOBOBJECT_BASIC_PROCESS_ID_LIST()
472
+ res = ctypes.windll.kernel32.QueryInformationJobObject(job, subprocess_impl_win32.JobObjectBasicProcessIdList, ctypes.pointer(win32_thread_info), ctypes.sizeof(win32_thread_info), None)
473
+ if not res:
474
+ return
475
+ pids = []
476
+ for i in range(win32_thread_info.NumberOfProcessIdsInList):
477
+ pids.append(win32_thread_info.ProcessIdList[i])
478
+
479
+ subprocess_impl_win32.win32_send_pid_wm_close(pids)
480
+
481
+ def win32_send_pid_wm_close(pid):
482
+ subprocess_impl_win32._win32_send_wm_close_hwnd_message(pid)
483
+ subprocess_impl_win32._win32_send_ctrl_c_event(pid)
484
+
485
+
486
+ def _win32_find_message_hwnds(pids):
487
+ if not isinstance(pids, list):
488
+ pids = [pids]
489
+ hWnd_child_after = 0
490
+ hwnds = []
491
+
492
+ while True:
493
+ hWnd = ctypes.windll.user32.FindWindowExW(subprocess_impl_win32.HWND_MESSAGE, hWnd_child_after, None, None)
494
+ # print(hWnd)
495
+ if hWnd == 0:
496
+ break
497
+ process_id = ctypes.wintypes.DWORD()
498
+ ctypes.windll.user32.GetWindowThreadProcessId(hWnd,ctypes.byref(process_id))
499
+ if process_id.value in pids:
500
+ hwnds.append(hWnd)
501
+ #ctypes.windll.user32.PostMessageW(hWnd,subprocess_impl_win32.WM_CLOSE,0,0)
502
+ hWnd_child_after = hWnd
503
+ return hwnds
504
+
505
+ def _win32_find_main_hwnds(pids):
506
+ if not isinstance(pids, list):
507
+ pids = [pids]
508
+
509
+ hwnds = []
510
+
511
+ # Create list of top level windows
512
+
513
+ def worker(hWnd, lParam):
514
+ process_id = ctypes.wintypes.DWORD()
515
+ ctypes.windll.user32.GetWindowThreadProcessId(hWnd,ctypes.byref(process_id))
516
+ if lParam == process_id.value:
517
+ hwnds.append(hWnd)
518
+ return True
519
+
520
+ cb_worker = subprocess_impl_win32.WNDENUMPROC(worker)
521
+ if not ctypes.windll.user32.EnumWindows(cb_worker, pids[0]):
522
+ return hwnds
523
+
524
+ # Filter out windows that are children of other windows
525
+ hwnds = [hWnd for hWnd in hwnds if not ctypes.windll.user32.GetParent(hWnd)]
526
+ return hwnds
527
+
528
+ def _win32_send_wm_close_hwnd_message(pid):
529
+ # check for main window first, then send to message windows
530
+ hwnds = subprocess_impl_win32._win32_find_main_hwnds(pid)
531
+ if not hwnds:
532
+ hwnds = subprocess_impl_win32._win32_find_message_hwnds(pid)
533
+ for hWnd in hwnds:
534
+ ctypes.windll.user32.PostMessageW(hWnd,subprocess_impl_win32.WM_CLOSE,0,0)
535
+
536
+ def _win32_send_ctrl_c_event(pid):
537
+ if isinstance(pid, list):
538
+ for p in pid:
539
+ subprocess_impl_win32._win32_send_ctrl_c_event(p)
540
+ return
541
+ ctypes.windll.kernel32.GenerateConsoleCtrlEvent(0,pid)
542
+
543
+ def parse_task_launch_from_yaml(yaml_dict, cwd):
544
+ # parse yaml_dict into DrekarTask tuple
545
+ name = yaml_dict["name"]
546
+ program = yaml_dict["program"]
547
+ cwd = yaml_dict.get("cwd", cwd)
548
+ args = yaml_dict.get("args", None)
549
+ if args is None:
550
+ args = []
551
+ else:
552
+ if isinstance(args,str):
553
+ args = args.split()
554
+ if isinstance(args,bool) or isinstance(args,int) or isinstance(args,float):
555
+ # Corner case where args is another yaml type
556
+ args = [str(args)]
557
+ else:
558
+ assert isinstance(args,list), "process args must be a string or list"
559
+ args = [str(a) for a in args]
560
+ restart = yaml_dict.get("restart", False)
561
+ restart_backoff = yaml_dict.get("restart-backoff", 5)
562
+ tags = yaml_dict.get("tags", [])
563
+ env = os.environ.copy()
564
+ env.update(yaml_dict.get("environment", {}))
565
+ start_delay = yaml_dict.get("start-delay", 0)
566
+ quit_on_terminate = yaml_dict.get("quit-on-terminate", False)
567
+
568
+ if "env-file" in yaml_dict:
569
+ env_file = yaml_dict["env-file"]
570
+ with open(env_file, "r") as f:
571
+ env = dict()
572
+ env_line = f.readline()
573
+ while env_line:
574
+ env_line = env_line.strip()
575
+ if env_line:
576
+ # handle comments
577
+ if env_line[0] == "#":
578
+ # remove trailing comment
579
+ env_line = env_line.split("#", 1)[0]
580
+ env_line_split = env_line.split("=", 1)
581
+ if len(env_line_split) == 2:
582
+ env[env_line_split[0]] = env_line_split[1]
583
+ env_line = f.readline()
584
+
585
+ if(Path(program).name == program):
586
+ program = shutil.which(program, path=env["PATH"])
587
+ if program is None:
588
+ raise Exception("Could not find program: {}".format(program))
589
+
590
+ return DrekarTask(
591
+ name=name,
592
+ program=program,
593
+ cwd=cwd,
594
+ args=args,
595
+ restart=restart,
596
+ restart_backoff=restart_backoff,
597
+ tags=tags,
598
+ environment=env,
599
+ start_delay=start_delay,
600
+ quit_on_terminate=quit_on_terminate,
601
+ )
602
+
603
+
604
+
605
+
606
+ def parse_task_launches_from_yaml(f, cwd):
607
+ yaml_dict = yaml.safe_load(f)
608
+ return parse_task_launches_from_yaml_dict(yaml_dict, cwd)
609
+
610
+ def parse_task_launches_from_yaml_dict(yaml_dict, cwd):
611
+ yaml_tasks = yaml_dict["tasks"]
612
+ name = yaml_dict.get("name",None)
613
+ task_launches = []
614
+ for t in yaml_tasks:
615
+ task_launches.append(parse_task_launch_from_yaml(t, cwd))
616
+ return name, task_launches
617
+
618
+
619
+ class DrekarGui:
620
+
621
+ def __init__(self, name, core, exit_event):
622
+ self.name = name
623
+ self.core = core
624
+ self.log_dir = core.log_dir
625
+ self.exit_event = exit_event
626
+ self.root = None
627
+
628
+ def _create_root(self):
629
+ tk = importlib.import_module("tkinter")
630
+
631
+ root = tk.Tk()
632
+ root.title(self.name + " Drekar Launch")
633
+ root.geometry("600x200")
634
+
635
+ root.protocol("WM_DELETE_WINDOW", self._set_exit_event)
636
+
637
+ # Create a window that displays status of tasks and has a "Stop All" button
638
+ # that sets the exit_event
639
+
640
+ label = tk.Label(root, fg = "black", justify=tk.LEFT, wraplength=600)
641
+ # Fill window with label
642
+ label.grid(row=0, column=0, sticky=tk.NSEW)
643
+ # label.grid(row=0, column=0)
644
+ label.config(text=f"Running Launch:\n{self.name}\n\nLog Directory:\n{self.log_dir}\n\nPress \"Stop All\" to exit\n")
645
+
646
+ button = tk.Button(root, text="Stop All", command=self._set_exit_event, width=50, height=2)
647
+ button.grid(row=1, column=0, sticky=tk.S)
648
+
649
+ root.bind("<<exit>>", self._close)
650
+
651
+ self.root = root
652
+
653
+ def _set_exit_event(self):
654
+ self.core.loop.call_soon_threadsafe(self.exit_event.set)
655
+
656
+ def start(self):
657
+ # run in thread
658
+ self._thread = threading.Thread(target=self._run)
659
+ # self._thread.daemon = True
660
+ self._thread.start()
661
+
662
+ def _run(self):
663
+ self._create_root()
664
+ self.root.mainloop()
665
+ self.root.quit()
666
+ self.root.tk.quit()
667
+ # self.root.tk.destroy()
668
+ self.root = None
669
+ time.sleep(1)
670
+
671
+ def _close(self, *args):
672
+ self.root.destroy()
673
+
674
+
675
+ def close(self):
676
+ self.root.event_generate("<<exit>>")
677
+ self._thread.join()
678
+
679
+ def parse_task_launches_from_jinja2_config(config, config_fname, cwd, extra_process_args):
680
+
681
+ config_absolute_path = os.path.abspath(config_fname)
682
+ config_dir = os.path.dirname(config_absolute_path)
683
+ config_text = config.read()
684
+
685
+ jinja2_env = jinja2.Environment(
686
+ loader=jinja2.FileSystemLoader(config_dir),
687
+ undefined=jinja2.StrictUndefined,
688
+ trim_blocks=True,
689
+ lstrip_blocks=True,
690
+ )
691
+
692
+ # create vars from extract args starting with --var-
693
+ vars = dict()
694
+ for a in extra_process_args:
695
+ if a.startswith("--var-"):
696
+ var_name = a.split("=",1)[0][6:]
697
+ var_value = a.split("=",1)[1]
698
+ vars[var_name] = var_value
699
+
700
+ extra_args = {
701
+ "configdir": config_dir,
702
+ "configpath": config_absolute_path,
703
+ "env": os.environ,
704
+ "vars": vars,
705
+ "platform": sys.platform
706
+ }
707
+
708
+ config_text = jinja2_env.from_string(config_text).render(**extra_args)
709
+ yaml_dict = yaml.safe_load(config_text)
710
+ name, task_launches = parse_task_launches_from_yaml_dict(yaml_dict, cwd)
711
+
712
+ return name, task_launches
713
+
714
+ def main():
715
+ try:
716
+ parser = argparse.ArgumentParser("PyRI Core Launcher")
717
+ parser.add_argument("--config", type=str, default=None, help="Configuration file")
718
+ parser.add_argument("--config-j2", type=str, default=None, help="Configuration file (jinja2 template)")
719
+ parser.add_argument("--cwd", type=str, default=".", help="Working directory")
720
+ parser.add_argument("--name", type=str, default=None, help="Name of the launch")
721
+ parser.add_argument("--quiet", action="store_true", help="Echo output to screen")
722
+ parser.add_argument("--gui", action="store_true", help="Run GUI")
723
+
724
+ parser_results, remaining_args = parser.parse_known_args()
725
+
726
+
727
+ # check that both config and config-j2 are not specified
728
+ if parser_results.config is not None and parser_results.config_j2 is not None:
729
+ raise Exception("Only one of --config or --config-j2 can be specified")
730
+
731
+ # check that config or config-j2 is specified
732
+ if parser_results.config_j2 is not None:
733
+ with open(parser_results.config_j2, "r") as f:
734
+ name, task_launch = parse_task_launches_from_jinja2_config(f, parser_results.config_j2, parser_results.cwd, remaining_args)
735
+ elif parser_results.config is not None:
736
+ with open (parser_results.config, "r") as f:
737
+ name, task_launch = parse_task_launches_from_yaml(f, parser_results.cwd)
738
+ else:
739
+ # use default config drekar-launch.yaml
740
+ with open("drekar-launch.yaml", "r") as f:
741
+ name, task_launch = parse_task_launches_from_yaml(f, parser_results.cwd)
742
+
743
+ name = parser_results.name if parser_results.name is not None else name
744
+ if name is None:
745
+ name = "drekar-launch"
746
+
747
+ timestamp = datetime.now().strftime("-%Y-%m-%d--%H-%M-%S")
748
+ log_dir = Path(appdirs.user_log_dir(appname="drekar-launch")).joinpath(name).joinpath(name + timestamp)
749
+ log_dir.mkdir(parents=True, exist_ok=True)
750
+ loop = asyncio.get_event_loop()
751
+
752
+ exit_event = asyncio.Event()
753
+ core = DrekarCore(parser_results.name, task_launch, exit_event, log_dir, not parser_results.quiet, loop)
754
+ gui = None
755
+ if parser_results.gui:
756
+ gui = DrekarGui(name, core, exit_event)
757
+ gui.start()
758
+ loop.call_soon(lambda: core.start_all())
759
+ def ctrl_c_pressed():
760
+ loop.call_soon_threadsafe(lambda: exit_event.set())
761
+ loop.call_soon_threadsafe(lambda: core.close())
762
+ drekar_launch_process.wait_exit_callback(ctrl_c_pressed)
763
+ print("Press Ctrl-C to exit")
764
+ loop.run_until_complete(exit_event.wait())
765
+ print("Exit received, closing")
766
+ core.close()
767
+ loop.run_until_complete(core.wait_all_closed())
768
+ #pending = asyncio.all_tasks(loop)
769
+ # pending = asyncio.all_tasks()
770
+ #loop.run_until_complete(asyncio.gather(*pending))
771
+ if gui is not None:
772
+ gui.close()
773
+ print("Exiting!")
774
+ exit_status = core.get_exit_status()
775
+ if exit_status != 0:
776
+ print(f"Exit status: {exit_status}")
777
+ sys.exit(exit_status)
778
+ except Exception:
779
+ traceback.print_exc()
780
+ raise
781
+
782
+
783
+
784
+ if __name__ == "__main__":
785
+ main()