gcl-looper 0.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
gcl_looper/__init__.py ADDED
File without changes
File without changes
@@ -0,0 +1,34 @@
1
+ # Copyright 2025 Genesis Corporation.
2
+ #
3
+ # All Rights Reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License"); you may
6
+ # not use this file except in compliance with the License. You may obtain
7
+ # a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13
+ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14
+ # License for the specific language governing permissions and limitations
15
+ # under the License.
16
+ from __future__ import annotations
17
+
18
+ import sys
19
+ import logging
20
+
21
+ from gcl_looper.services.oslo import launchpad
22
+
23
+ LOG = logging.getLogger(__name__)
24
+
25
+
26
+ def main():
27
+ launchpad_svc = launchpad.LaunchpadService.from_cmd_line(sys.argv[1:])
28
+ launchpad_svc.start()
29
+
30
+ LOG.info("Bye!!!")
31
+
32
+
33
+ if __name__ == "__main__":
34
+ main()
@@ -0,0 +1,18 @@
1
+ # Copyright 2025 Genesis Corporation.
2
+ #
3
+ # All Rights Reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License"); you may
6
+ # not use this file except in compliance with the License. You may obtain
7
+ # a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13
+ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14
+ # License for the specific language governing permissions and limitations
15
+ # under the License.
16
+
17
+ GLOBAL_SERVICE_NAME = "gcl_looper"
18
+ EP_GCL_LOOPER_SERVICES = "gcl_looper.launchpad.services"
File without changes
@@ -0,0 +1,99 @@
1
+ # Copyright 2025 George Melikov <mail@gmelikov.ru>
2
+ #
3
+ # All Rights Reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License"); you may
6
+ # not use this file except in compliance with the License. You may obtain
7
+ # a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13
+ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14
+ # License for the specific language governing permissions and limitations
15
+ # under the License.
16
+
17
+ import abc
18
+ import logging
19
+ import signal
20
+
21
+ LOG = logging.getLogger(__name__)
22
+
23
+
24
+ class AbstractService(abc.ABC):
25
+ __mp_downgrade_user__ = None
26
+
27
+ def __init__(self):
28
+ super(AbstractService, self).__init__()
29
+ self._setups = []
30
+ self._finishes = []
31
+ self._should_subscribe_signals = True
32
+
33
+ @property
34
+ def should_subscribe_signals(self):
35
+ return self._should_subscribe_signals
36
+
37
+ @should_subscribe_signals.setter
38
+ def should_subscribe_signals(self, value):
39
+ LOG.info("Set should_subscribe_signals=%r", value)
40
+ self._should_subscribe_signals = value
41
+
42
+ def start(self):
43
+ """Infinite loop itself"""
44
+ try:
45
+ self._setup()
46
+ if self.should_subscribe_signals:
47
+ self._subscribe_signals(self._get_sig_handlers())
48
+ LOG.info("Start loop")
49
+ self._loop()
50
+ LOG.info("Loop finished.")
51
+ finally:
52
+ self._finish()
53
+
54
+ @abc.abstractmethod
55
+ def _loop(self):
56
+ """Implement your loop logic here"""
57
+ raise NotImplementedError()
58
+
59
+ @abc.abstractmethod
60
+ def stop(self):
61
+ """Implement stop logic here"""
62
+ raise NotImplementedError()
63
+
64
+ def add_setup(self, setup_func):
65
+ self._setups.append(setup_func)
66
+
67
+ def _setup(self):
68
+ LOG.info("Setup loop")
69
+ for setup_func in self._setups:
70
+ setup_func()
71
+
72
+ def add_finishes(self, finish_func):
73
+ self._finishes.append(finish_func)
74
+
75
+ def _finish(self):
76
+ LOG.info("Finish loop")
77
+ for finish_func in self._finishes:
78
+ finish_func()
79
+ pass
80
+
81
+ def _get_sig_handlers(self):
82
+ def stop_callback(s, frame):
83
+ self.stop()
84
+
85
+ base_handlers = {
86
+ signal.SIGINT: stop_callback,
87
+ signal.SIGTERM: stop_callback,
88
+ }
89
+
90
+ return base_handlers
91
+
92
+ def _subscribe_signals(self, handlers):
93
+ # TODO(g.melikov): implement `handlers` validation
94
+
95
+ # default handlers
96
+ handlers.setdefault(signal.SIGCHLD, signal.SIG_DFL)
97
+
98
+ for sig, handl in handlers.items():
99
+ signal.signal(sig, handl)
@@ -0,0 +1,82 @@
1
+ # Copyright 2025 George Melikov <mail@gmelikov.ru>
2
+ #
3
+ # All Rights Reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License"); you may
6
+ # not use this file except in compliance with the License. You may obtain
7
+ # a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13
+ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14
+ # License for the specific language governing permissions and limitations
15
+ # under the License.
16
+
17
+ import abc
18
+ import logging
19
+ import time
20
+
21
+ from gcl_looper.services import base
22
+
23
+ LOG = logging.getLogger(__name__)
24
+
25
+
26
+ class BasicService(base.AbstractService):
27
+ __log_iteration__ = True
28
+
29
+ def __init__(self, iter_min_period=1, iter_pause=0.1):
30
+ super(BasicService, self).__init__()
31
+ self._enabled = False
32
+ self._iter_min_period = iter_min_period
33
+ self._iter_pause = iter_pause
34
+ self._iteration_number = 0
35
+
36
+ def _loop_iteration(self):
37
+ iteration = self._iteration_number
38
+ if self.__log_iteration__:
39
+ LOG.debug(
40
+ "Iteration #%d started for %s",
41
+ iteration,
42
+ self.__class__.__name__,
43
+ )
44
+ try:
45
+ self._iteration()
46
+ if self.__log_iteration__:
47
+ LOG.debug(
48
+ "Iteration #%d finished for %s",
49
+ iteration,
50
+ self.__class__.__name__,
51
+ )
52
+ except Exception:
53
+ LOG.exception(
54
+ "Unexpected error during iteration #%d for %s",
55
+ iteration,
56
+ self.__class__.__name__,
57
+ )
58
+ finally:
59
+ self._iteration_number += 1
60
+
61
+ def _loop(self):
62
+ self._enabled = True
63
+ next_iteration_time = 0
64
+ while self._enabled:
65
+ current_time = time.monotonic()
66
+
67
+ if current_time >= next_iteration_time:
68
+ next_iteration_time = current_time + self._iter_min_period
69
+ self._loop_iteration()
70
+
71
+ time_to_sleep = next_iteration_time - time.monotonic()
72
+ if time_to_sleep > 0 or self._iter_pause > 0:
73
+ time.sleep(max(time_to_sleep, self._iter_pause))
74
+
75
+ @abc.abstractmethod
76
+ def _iteration(self):
77
+ """Implement your logic per one iteration here"""
78
+ raise NotImplementedError()
79
+
80
+ def stop(self):
81
+ LOG.info("Stop service")
82
+ self._enabled = False
@@ -0,0 +1,74 @@
1
+ # Copyright 2025 George Melikov <mail@gmelikov.ru>
2
+ #
3
+ # All Rights Reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License"); you may
6
+ # not use this file except in compliance with the License. You may obtain
7
+ # a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13
+ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14
+ # License for the specific language governing permissions and limitations
15
+ # under the License.
16
+
17
+ import logging
18
+ import os
19
+ import signal
20
+
21
+ import bjoern
22
+
23
+ from gcl_looper.services import base
24
+
25
+ LOG = logging.getLogger(__name__)
26
+
27
+
28
+ class BjoernService(base.AbstractService):
29
+ """Bjoern has it's own eventloop, so we don't need to loop explicitly"""
30
+
31
+ __mp_downgrade_user__ = "nobody"
32
+
33
+ def __init__(self, wsgi_app, host, port, bjoern_kwargs=None):
34
+ super(BjoernService, self).__init__()
35
+ self._wsgi_app = wsgi_app
36
+ self._host = host
37
+ self._port = port
38
+ self._bjoern_kwargs = bjoern_kwargs or {}
39
+ self._bjoern_kwargs.setdefault("reuse_port", False)
40
+ self.should_subscribe_signals = True
41
+
42
+ def _setup(self):
43
+ bjoern.listen(
44
+ wsgi_app=self._wsgi_app,
45
+ host=self._host,
46
+ port=self._port,
47
+ **self._bjoern_kwargs,
48
+ )
49
+ return super()._setup()
50
+
51
+ def _exit_gracefully(self, signum, frame):
52
+ # TODO(g.melikov): bjoern may have problems with exit on signals:
53
+ # - signals mangling with multiprocess
54
+ # - even if bjoern got our signal - it may not return before new
55
+ # client try to connect...
56
+ # - bjoern doesn't have graceful stop, beware!
57
+ if bjoern._default_instance:
58
+ sock, wsgi_app = bjoern._default_instance
59
+ sock.close()
60
+ os.kill(os.getpid(), signal.SIGINT)
61
+
62
+ def _subscribe_signals(self, handlers):
63
+ signal.signal(signal.SIGTERM, self._exit_gracefully)
64
+
65
+ def _loop(self):
66
+ LOG.info("Bjoern server: %s:%s", self._host, self._port)
67
+ try:
68
+ bjoern.run()
69
+ except KeyboardInterrupt:
70
+ # Just a clean stop on Ctrl+C...
71
+ pass
72
+
73
+ def stop(self):
74
+ raise NotImplementedError()
@@ -0,0 +1,116 @@
1
+ # Copyright 2025 George Melikov <mail@gmelikov.ru>
2
+ #
3
+ # All Rights Reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License"); you may
6
+ # not use this file except in compliance with the License. You may obtain
7
+ # a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13
+ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14
+ # License for the specific language governing permissions and limitations
15
+ # under the License.
16
+
17
+ import multiprocessing
18
+ import logging
19
+ import threading
20
+
21
+ from gcl_looper.services import base
22
+ from gcl_looper.services import basic
23
+ from gcl_looper import utils
24
+
25
+ LOG = logging.getLogger(__name__)
26
+
27
+
28
+ class BasicHubService(basic.BasicService):
29
+ __log_iteration__ = False
30
+
31
+ def __init__(self, *args, **kwargs):
32
+ super().__init__(*args, **kwargs)
33
+
34
+ self._services = []
35
+ self._instances = {}
36
+
37
+ def add_service(self, service):
38
+ """Add a service to the list of services to start."""
39
+ if isinstance(service, base.AbstractService):
40
+ self._services.append(service)
41
+ else:
42
+ raise ValueError("Service must implement the AbstractService interface.")
43
+
44
+ def _iteration(self):
45
+ raise NotImplementedError()
46
+
47
+ def _setup(self):
48
+ raise NotImplementedError()
49
+
50
+ def _stop_instance(self, service, instance):
51
+ raise NotImplementedError()
52
+
53
+ def stop(self):
54
+ raise NotImplementedError()
55
+
56
+
57
+ class ProcessHubService(BasicHubService):
58
+ _instance_class = multiprocessing.get_context("fork").Process
59
+
60
+ def add_service(self, service):
61
+ if service.__mp_downgrade_user__:
62
+ service.add_setup(
63
+ lambda: utils.downgrade_user_group_privileges(
64
+ service.__mp_downgrade_user__
65
+ )
66
+ )
67
+ super().add_service(service)
68
+
69
+ def _iteration(self):
70
+ for instance in self._instances.values():
71
+ if not instance.is_alive():
72
+ LOG.error(
73
+ "Child service(pid:%i) is not running, let's stop",
74
+ instance.pid,
75
+ )
76
+ self.stop()
77
+ return
78
+
79
+ def _setup(self):
80
+ for service in self._services:
81
+ instance = self._instance_class(target=service.start)
82
+ self._instances[service] = instance
83
+ instance.start()
84
+
85
+ def _stop_instance(self, service, instance):
86
+ LOG.info("Stop child service(pid:%i)", instance.pid)
87
+ try:
88
+ instance.terminate()
89
+ except OSError: # Process doesn't exist
90
+ LOG.exception("Failed to terminate child service, pid:%i", instance.pid)
91
+
92
+ def stop(self):
93
+ LOG.info("Stop service")
94
+ self._enabled = False
95
+ # Stop all managed services
96
+ for service, instance in self._instances.items():
97
+ self._stop_instance(service, instance)
98
+ for instance in self._instances.values():
99
+ instance.join()
100
+
101
+
102
+ class ThreadHubService(ProcessHubService):
103
+ _instance_class = threading.Thread
104
+
105
+ def add_service(self, service):
106
+ super(ProcessHubService, self).add_service(service)
107
+
108
+ def _setup(self):
109
+ # Threads can't hangle signals so we need to disable them
110
+ for service in self._services:
111
+ service.should_subscribe_signals = False
112
+ super()._setup()
113
+
114
+ def _stop_instance(self, service, instance):
115
+ LOG.info("Stop child service(native_id:%i)", instance.native_id)
116
+ service.stop()
File without changes
@@ -0,0 +1,47 @@
1
+ # Copyright 2025 Genesis Corporation.
2
+ #
3
+ # All Rights Reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License"); you may
6
+ # not use this file except in compliance with the License. You may obtain
7
+ # a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13
+ # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14
+ # License for the specific language governing permissions and limitations
15
+ # under the License.
16
+ from __future__ import annotations
17
+
18
+ import typing as tp
19
+
20
+ from oslo_config import cfg
21
+
22
+
23
+ class OsloConfigurableService:
24
+ @classmethod
25
+ def svc_get_config_opts(cls) -> tp.Collection[cfg.Opt] | None:
26
+ """Return Oslo config options for the service.
27
+
28
+ If None is returned, the service will attempt to load from
29
+ the config file directly via `svc_from_config`.
30
+
31
+ Example:
32
+
33
+ def svc_get_config_opts(cls):
34
+ return [
35
+ cfg.StrOpt(
36
+ "name",
37
+ default="set_agent",
38
+ help="Name for the service",
39
+ ),
40
+ ]
41
+ """
42
+ return None
43
+
44
+ @classmethod
45
+ def svc_from_config(cls, config_file: str) -> "OsloConfigurableService":
46
+ """Create service instance from config file."""
47
+ return cls()