simple-task-manager 1.5.4__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 [yyyy] [name of copyright owner]
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,88 @@
1
+ Metadata-Version: 2.1
2
+ Name: simple_task_manager
3
+ Version: 1.5.4
4
+ Summary: Simple task manager to handle execution of tasks in AWS or docker.
5
+ Home-page: https://github.com/Fran-4c4/staskmgr
6
+ Author: Francisco R. Moreno Santana
7
+ Author-email: franrms@gmail.com
8
+ License: Apache License 2.0
9
+ Project-URL: Bug Tracker, https://github.com/Fran-4c4/staskmgr/issues
10
+ Project-URL: Source Code, https://github.com/Fran-4c4/staskmgr
11
+ Classifier: Programming Language :: Python :: 3.7
12
+ Classifier: Programming Language :: Python :: 3.8
13
+ Classifier: Programming Language :: Python :: 3.9
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Topic :: System :: Distributed Computing
18
+ Classifier: Operating System :: OS Independent
19
+ Requires-Python: >=3.7
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Requires-Dist: SQLAlchemy<2.0.0,>=1.4.39
23
+ Requires-Dist: python-dotenv
24
+ Requires-Dist: psycopg2==2.9.1; sys_platform == "linux" and python_version >= "3.7" and python_version < "3.8"
25
+ Requires-Dist: psycopg2>=2.9.1; sys_platform == "linux" and python_version >= "3.8"
26
+ Requires-Dist: psycopg2-binary==2.9.6; sys_platform == "win32" and python_version >= "3.7" and python_version < "3.8"
27
+ Requires-Dist: psycopg2-binary>=2.9.6; sys_platform == "win32" and python_version >= "3.8"
28
+
29
+ # Simple Task Manager (STMGR)
30
+
31
+ This is a simple task manager to start processes on AWS/Docker or other platforms. The app includes classes to manage tasks on AWS, but you can implement additional handlers dynamically.
32
+
33
+ You only need to create a class to handle the task that you want to start and register it in a database (DDBB). Below, I’ll compare STMGR with Celery (since it’s widely used) to explain the key differences and help you make an informed choice. Another good choice is Dramatiq. For a simple comparison between STMGR and Celery check
34
+
35
+ ## Installation
36
+ This project can be installed using pip:
37
+
38
+ ```python
39
+ pip install -i https://test.pypi.org/simple/ simple-task-manager
40
+
41
+ ```
42
+ Or it can be installed directly from git:
43
+ pip install git+https://github.com/Fran-4c4/staskmgr
44
+
45
+
46
+ ## Usage
47
+ - First you need to configure the minimum parameters in order to run tasks. See
48
+ - Second include
49
+
50
+
51
+
52
+ Bienvenido al **Simple Task Manager**. Para obtener más detalles sobre la configuración, el uso y las preguntas frecuentes, consulta los siguientes documentos:
53
+
54
+ - [Configuration](./docs/configuration.md)
55
+ - [FAQ](./docs/faq.md)
56
+
57
+ More info in github [GitHub](https://github.com/Fran-4c4/staskmgr).
58
+
59
+
60
+ ---
61
+
62
+ # Adding handlers
63
+ In order to manage other types you need to create a class and an entry in DDBB or in your appconfig.json in the section **task_handlers**. When the task is retrieved from DDBB it will look the handler.
64
+
65
+ ```JSON
66
+ {...
67
+ ,"task_handlers":{
68
+ "TestTaskHandler":{
69
+ "name": "Test task",
70
+ "module": "TestTaskHandler",
71
+ "class": "TestTaskHandler",
72
+ "path": "path_to/task_handlers" //Folder
73
+ }
74
+ }
75
+ ```
76
+
77
+ # DDBB configuration
78
+ You need a DDBB with 2 tables:
79
+ - tmgr_tasks: Info with the task
80
+ - tmgr_tasks_dep: Info with task dependencies needed by task to be exceuted.
81
+ See table creation in config\ddbb_script.sql
82
+
83
+ # Test in local
84
+ Install using pip in your project using
85
+ pip install "path_to_dist/dist/Simple_Task_Manager-0.1.0-py3-none-any.whl"
86
+
87
+ ## License
88
+ licensed under Apache License 2.0
@@ -0,0 +1,32 @@
1
+ task_handlers/__init__.py,sha256=TrgcfRll-WF3Nh6TTmWzSmghEqz6NBYQHGoE9h8cSk4,35
2
+ task_handlers/docker_task_handler.py,sha256=2NgiV2ivsTx1Ih6vkV57DiVdiT63Ji0EOyNM0J-KxHg,2882
3
+ task_handlers/ecs_task_handler.py,sha256=IQTW9j94SQwdd57mYDYZeq3BFkk42fNbf3_Qxlf-C10,7310
4
+ task_handlers/test_task_handler.py,sha256=gNVcEmfYdWqChEeLVUybgY_sh20yg57Oah8M3m8j958,983
5
+ tmgr/__init__.py,sha256=9Pi_DQuuS8xrQRlIUCFFKH_nAH3c1_j_XySum1ne6N8,717
6
+ tmgr/configuration_helper.py,sha256=NBa5aqBcFGURbG1E9BqN-_BSaPA3uJoDAErJ_1b7VTM,2013
7
+ tmgr/db_base.py,sha256=PXX4Dggz--bvR3o1E6H0wj0XXnnNN6AmYa4iJWWj5y4,3474
8
+ tmgr/db_mgr.py,sha256=U_ev3K4yf8RPOGm4l6wmQjxQDZ93CYpbtVDlVTqzUPo,1928
9
+ tmgr/dbhelper.py,sha256=VNQFfLrdih_wOIUVswMidgmdpPsLSgw3XWPLW2yTTpM,1850
10
+ tmgr/env_loader.py,sha256=ro1qD5hfkd_36-sorqPFua4bUT0Lbz_IespODJ2tz1U,919
11
+ tmgr/global_config.py,sha256=7Kruni62mn9F8ly8Hq566VEGm3nYHUTG9RmTdSfC2-w,280
12
+ tmgr/periodic_task.py,sha256=KcooMSh-aqKeBsEyylC27906IgVUoeE5aTW-rGQAj8g,1517
13
+ tmgr/task_db.py,sha256=stfzR9A-VthxR7JKwkZeoxfoGw50FLEZBwP52P4DXw0,12261
14
+ tmgr/task_handler_interface.py,sha256=EF3CwgfVlAx9OIe2aaYybjVPSVpO0PHnpc3zcpIB2R0,631
15
+ tmgr/task_loader.py,sha256=IHS7jz_cLpnM0Ey6U-RPoNvPOgejJBOp7cmgeuH8xoY,4283
16
+ tmgr/tmgr.py,sha256=CPr3iH9dGwxPiQNe_sM1ew0Hr5s9b1BR5BMJlpUzoyk,10611
17
+ tmgr/enums/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
18
+ tmgr/enums/enum_base.py,sha256=oRoKkxwNfmlCoJBQeVD5UtwequyUzZ21CovbFytb8nw,212
19
+ tmgr/enums/task_status_enum.py,sha256=B0YVl5wiNxJBwW5KcGD9AnGZCJMjE679xQj-rxXrytk,368
20
+ tmgr/log_handlers/__init__.py,sha256=2iEgl6RsREzcj4ZW6fqGdG7heirXvYjujNbNYdoYqoI,22
21
+ tmgr/log_handlers/origin_filter.py,sha256=uu8cFjg6-yAzzsbx7A8LHmPdBLPYM-Qi358B2-BYEs0,604
22
+ tmgr/log_handlers/postgres_handler.py,sha256=mMY8cjkGbv25CKhbEFvlz2zrLi_ZWmwSCQr-AliHTTk,1865
23
+ tmgr/log_handlers/sqllite_handler.py,sha256=YxUn9z78yPobt4RzhL_WTd-nuBcfAZXfW2SIGDIk9Ag,1306
24
+ tmgr/model/__init__.py,sha256=Z_cozyUpUNLhI_40ZWbswnfJ3oWmMqdJK1bdt4n_ARc,22
25
+ tmgr/model/base_manager.py,sha256=b_01lPziOeN-09AvavsxKeZxqWFnFSq9BMCciQjHOHQ,579
26
+ tmgr/model/task.py,sha256=VIlVOOFar4nQOge_RUQG6mVeNtvf-xXSrhJiHozKvW4,1979
27
+ tmgr/model/task_dep.py,sha256=V1FO_-rzIkpKKzs7uK39nAsZe1_gaSp5KUePZkulLLI,721
28
+ simple_task_manager-1.5.4.dist-info/LICENSE,sha256=HrhfyXIkWY2tGFK11kg7vPCqhgh5DcxleloqdhrpyMY,11558
29
+ simple_task_manager-1.5.4.dist-info/METADATA,sha256=pPcuOrR77DlQDbYkSNSYuBdBpgDtgiPH7HmCH1XL-CM,3531
30
+ simple_task_manager-1.5.4.dist-info/WHEEL,sha256=GV9aMThwP_4oNCtvEC2ec3qUYutgWeAzklro_0m4WJQ,91
31
+ simple_task_manager-1.5.4.dist-info/top_level.txt,sha256=XrHJzFDbEBOk_y1hOoOKaVH2Hohswn6PW2TjMjqaboI,19
32
+ simple_task_manager-1.5.4.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (75.1.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ task_handlers
2
+ tmgr
@@ -0,0 +1,2 @@
1
+ """folder with task handlers
2
+ """
@@ -0,0 +1,75 @@
1
+ import docker
2
+
3
+ import logging
4
+ from taskmgr.tmgr.task_handler_interface import TaskHandlerInterface
5
+
6
+ class DockerTaskHandler(TaskHandlerInterface):
7
+ """Class to handle running Docker containers as tasks."""
8
+
9
+ task_data=None
10
+
11
+ def __init__(self):
12
+ self.log = logging.getLogger(__name__)
13
+ self.task_data=None
14
+
15
+ """Initialize DockerTaskRunner with the task definition.
16
+
17
+ Args:
18
+ task_definition (dict): The task definition that contains the Docker configuration.
19
+ """
20
+ self.image = None
21
+ self.name = None
22
+ self.environment = None
23
+ self.volumes = None
24
+ self.command = None
25
+ self.client = docker.from_env()
26
+
27
+ def config(self):
28
+ """config class
29
+ """
30
+ self.image = self.task_data.get('image')
31
+ self.name = self.task_data.get('name', None)
32
+ self.environment = self.task_data.get('environment', {})
33
+ self.volumes = self.task_data.get('volumes', {})
34
+ self.command = self.task_data.get('command', None)
35
+ self.client = docker.from_env()
36
+
37
+ def run_task(self, **kwargs):
38
+ """Run the Docker container task."""
39
+ try:
40
+ task_definition=kwargs.get("task_definition")
41
+ if task_definition is None:
42
+ raise Exception ("ECSTaskHandler: Task definition is None. Please check definition data.")
43
+
44
+ self.task_data=task_definition
45
+
46
+ self.config()
47
+ print(f"Running Docker container with image: {self.image}")
48
+
49
+ # Ejecutar el contenedor Docker
50
+ container = self.client.containers.run(
51
+ self.image,
52
+ name=self.name,
53
+ environment=self.environment,
54
+ volumes=self.volumes,
55
+ command=self.command,
56
+ detach=True # Detach mode, so the container runs in the background
57
+ )
58
+
59
+ print(f"Container {container.short_id} is running.")
60
+
61
+ # Esperar a que el contenedor termine y obtener el log de salida
62
+ result = container.wait()
63
+ logs = container.logs().decode('utf-8')
64
+ print(f"Container logs: {logs}")
65
+
66
+ container.remove() # Opcional: eliminar el contenedor después de la ejecución
67
+
68
+ return {"status": "COMPLETED", "logs": logs, "exit_code": result['StatusCode']}
69
+
70
+ except docker.errors.ContainerError as e:
71
+ return {"status": "ERROR", "message": str(e)}
72
+ except docker.errors.ImageNotFound as e:
73
+ return {"status": "ERROR", "message": f"Image not found: {self.image}"}
74
+ except Exception as e:
75
+ return {"status": "ERROR", "message": str(e)}
@@ -0,0 +1,192 @@
1
+ from typing import Dict
2
+ import boto3
3
+ import json
4
+ import logging
5
+ import time
6
+
7
+ from tmgr.task_handler_interface import TaskHandlerInterface
8
+
9
+ class ECSTaskHandler(TaskHandlerInterface):
10
+ """handles ECS task. Can start a fargate task or an EC2 task
11
+
12
+
13
+ """
14
+ client=None
15
+ task_data=None
16
+
17
+ def __init__(self):
18
+ self.log = logging.getLogger(__name__)
19
+ self.client = None
20
+ self.task_data=None
21
+ self.launchType = None
22
+ self.networkMode = None
23
+ self.auto_scaling_group_wait_time=60
24
+
25
+ def config(self):
26
+ """config class
27
+ """
28
+
29
+ self.aws_region = self.task_data['region']
30
+ self.aws_subnets = self.task_data['subnets']
31
+ self.aws_security_groups = self.task_data['security_groups']
32
+ self.aws_cluster_name = self.task_data['cluster_name']
33
+ self.aws_task_definition = self.task_data['task_definition']
34
+ self.aws_task_container_name = self.task_data['task_container_name']
35
+
36
+ # for autoscaling group
37
+ self.auto_scaling_group_name=self.task_data.get('auto_scaling_group_name')
38
+ self.auto_scaling_group_wait_time=self.task_data.get('auto_scaling_group_wait_time',60)
39
+ self.auto_scaling_group_DesiredCapacity=self.task_data.get('auto_scaling_group_DesiredCapacity',1)
40
+
41
+ self.launchType = self.task_data['launchType']
42
+ self.networkMode = self.task_data['networkMode']
43
+
44
+ self.client = boto3.client("ecs", region_name=self.aws_region)
45
+
46
+ self.platformVersion = None
47
+ self.networkConfiguration = None
48
+
49
+ if self.launchType == 'FARGATE':
50
+ self.platformVersion = 'LATEST'
51
+
52
+ if self.networkMode == 'awsvpc':
53
+ self.networkConfiguration={
54
+ 'awsvpcConfiguration': {
55
+ 'subnets': self.aws_subnets,
56
+ 'securityGroups': self.aws_security_groups,
57
+ 'assignPublicIp': 'ENABLED'
58
+ }
59
+ }
60
+
61
+ def run_task(self, **kwargs)->bool:
62
+ """Launch a task in a ECS cluster for fargate type
63
+
64
+ Args:
65
+ aws_task_cmd (list): Command list
66
+
67
+ Returns:
68
+ bool: Launch Result. True=Success | False=Failure
69
+ """
70
+ task_definition=kwargs.get("task_definition")
71
+ if task_definition is None:
72
+ raise Exception ("ECSTaskHandler: Task definition is None. Please check definition data.")
73
+
74
+ self.task_data=task_definition
75
+
76
+ self.config()
77
+ if self.launchType == 'FARGATE':
78
+ self.run_fargate_task()
79
+ elif self.launchType == 'EC2':
80
+ self.run_ec2_task()
81
+
82
+
83
+ def run_ec2_task(self, **kwargs)->bool:
84
+ """Launch a task in a ECS cluster for EC2 type
85
+
86
+ Args:
87
+ aws_task_cmd (list): Command list
88
+
89
+ Returns:
90
+ bool: Launch Result. True=Success | False=Failure
91
+ """
92
+ if self.client:
93
+ attempts = 0
94
+ max_attempts = 10
95
+ response=None
96
+ aws_task_cmd = []
97
+ id_process=self.task_data.get("task_id_task",None)
98
+ if id_process:
99
+ aws_task_cmd = ['--idprocess', str(id_process)]
100
+ def run_task():
101
+ try:
102
+ response = self.client.run_task(
103
+ taskDefinition=self.aws_task_definition,
104
+ launchType=self.launchType,
105
+ cluster=self.aws_cluster_name,
106
+ overrides={
107
+ 'containerOverrides': [
108
+ {
109
+ 'name': self.aws_task_container_name,
110
+ 'command': aws_task_cmd
111
+ },
112
+ ]
113
+ }
114
+ )
115
+ return response
116
+ except Exception as e:
117
+ autoscaling_client = boto3.client('autoscaling', region_name=self.aws_region)
118
+ if "No Container Instances were found in your cluster" in str(e):
119
+ print("No Container Instances were found in your cluster, increasing ASG(Auto scaling group)...")
120
+ autoscaling_client.set_desired_capacity(
121
+ AutoScalingGroupName=self.auto_scaling_group_name,
122
+ DesiredCapacity=self.auto_scaling_group_DesiredCapacity,
123
+ HonorCooldown=False
124
+ )
125
+ return None
126
+ else:
127
+ raise e
128
+
129
+
130
+ while response is None and attempts < max_attempts:
131
+ response = run_task()
132
+ if response is None:
133
+ attempts += 1
134
+ print(f"Increasing autoscaling group, waiting... Try {attempts}/{max_attempts}")
135
+ time.sleep(self.auto_scaling_group_wait_time) # Esperar un tiempo antes de volver a intentar
136
+
137
+
138
+
139
+ self.log.info(json.dumps(response, indent=4, default=str))
140
+ if response and 'failures' in response and len(response['failures']) == 0:
141
+ return True
142
+ else:
143
+ raise Exception("There is an error throwing the task")
144
+ else:
145
+ raise Exception("There is an error throwing the task. Task client is not loaded ")
146
+
147
+
148
+
149
+
150
+ def run_fargate_task(self, **kwargs)->bool:
151
+ """Launch a task in a ECS cluster for fargate type
152
+
153
+ Args:
154
+ aws_task_cmd (list): Command list
155
+
156
+ Returns:
157
+ bool: Launch Result. True=Success | False=Failure
158
+ """
159
+
160
+ if self.client:
161
+ aws_task_cmd = []
162
+ id_process=self.task_data.get("task_id_task",None)
163
+ if id_process:
164
+ aws_task_cmd = ['--idprocess', str(id_process)]
165
+
166
+
167
+ response = self.client.run_task(
168
+ taskDefinition=self.aws_task_definition,
169
+ launchType=self.launchType,
170
+ cluster=self.aws_cluster_name,
171
+ platformVersion=self.platformVersion,
172
+ count=1,
173
+ networkConfiguration=self.networkConfiguration,
174
+ overrides={
175
+ 'containerOverrides': [
176
+ {
177
+ 'name': self.aws_task_container_name,
178
+ 'command': aws_task_cmd
179
+ },
180
+ ]
181
+ }
182
+ )
183
+
184
+ self.log.info(json.dumps(response, indent=4, default=str))
185
+ if response and 'failures' in response and len(response['failures']) == 0:
186
+ return True
187
+ else:
188
+ raise Exception("There is an error throwing the task")
189
+ else:
190
+ raise Exception("There is an error throwing the task. Task client is not loaded ")
191
+
192
+
@@ -0,0 +1,34 @@
1
+
2
+ import logging
3
+
4
+ from taskmgr.tmgr.task_handler_interface import TaskHandlerInterface
5
+
6
+ class TestTaskHandler(TaskHandlerInterface):
7
+ """sample task handler
8
+ """
9
+
10
+ task_data=None
11
+
12
+ def __init__(self, **kwargs):
13
+ self.log = logging.getLogger(__name__)
14
+ self.task_data=None
15
+
16
+
17
+ def config(self):
18
+ """config class
19
+ """
20
+ print(f"Config test task with params: {self.task_data}")
21
+ pass
22
+
23
+
24
+ def run_task(self, **kwargs):
25
+ task_definition=kwargs.get("task_definition")
26
+ if task_definition is None:
27
+ raise Exception ("Task definition is None. Please check definition data.")
28
+ else:
29
+ print(f"Executing test task with task_definition: {task_definition}")
30
+
31
+ self.task_data=task_definition
32
+ self.config() #or we can pass the data here
33
+ print(f"Executing test task with params: {kwargs}")
34
+
tmgr/__init__.py ADDED
@@ -0,0 +1,19 @@
1
+ """Simple task manager"""
2
+ __name__ = 'simple_task_manager'
3
+ __version__ = '1.5.4'
4
+ __author__ = 'Francisco R. Moreno Santana'
5
+ __contact__ = 'franrms@gmail.com'
6
+ __homepage__ = 'https://github.com/Fran-4c4/staskmgr'
7
+ __docformat__ = 'text/markdown'
8
+ __keywords__ = 'task job queue distributed messaging actor'
9
+ __description__ ='Simple task manager to handle execution of tasks in AWS or docker.'
10
+ __bug_tracker__ = "https://github.com/Fran-4c4/staskmgr/issues"
11
+ __source_code__ = "https://github.com/Fran-4c4/staskmgr"
12
+
13
+
14
+ from .tmgr import *
15
+ from .task_handler_interface import *
16
+ #
17
+ #_startTime is used as the base when calculating the relative time of events
18
+ #
19
+ _startTime = time.time()