mkpipe 0.1.2__tar.gz

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.
mkpipe-0.1.2/LICENSE ADDED
@@ -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 2023-2024 Metin Karakus
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 @@
1
+ include mkpipe_core/jars/*
mkpipe-0.1.2/PKG-INFO ADDED
@@ -0,0 +1,11 @@
1
+ Metadata-Version: 2.1
2
+ Name: mkpipe
3
+ Version: 0.1.2
4
+ Summary: Core ETL pipeline framework for mkpipe.
5
+ Author: Metin Karakus
6
+ Author-email: metin_karakus@yahoo.com
7
+ License: Apache License 2.0
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: Apache Software License
10
+ Requires-Python: >=3.8
11
+ License-File: LICENSE
mkpipe-0.1.2/README.md ADDED
@@ -0,0 +1,59 @@
1
+ # MkPipe
2
+
3
+ **MkPipe** is a modular, open-source ETL (Extract, Transform, Load) tool that allows you to integrate various data sources and sinks easily. It is designed to be extensible with a plugin-based architecture that supports extractors, transformers, and loaders.
4
+
5
+ ## Features
6
+
7
+ - Extract data from multiple sources (e.g., PostgreSQL, MongoDB).
8
+ - Transform data using custom Python logic and Apache Spark.
9
+ - Load data into various sinks (e.g., ClickHouse, PostgreSQL, Parquet).
10
+ - Plugin-based architecture that supports future extensions.
11
+ - Cloud-native architecture, can be deployed on Kubernetes and other environments.
12
+
13
+ ## Installation
14
+
15
+ You can install the core package and extractors using pip:
16
+
17
+ ### Install the core package:
18
+ ```bash
19
+ pip install mkpipe
20
+ ```
21
+
22
+ ### Install the Postgres extractor:
23
+ ```bash
24
+ pip install mkpipe-extractor-postgres
25
+ ```
26
+
27
+ ### Install additional extractors or loaders as needed:
28
+ You can find or contribute new extractors and loaders in the future.
29
+
30
+ ## Usage
31
+
32
+ To run the ETL process, use the following command:
33
+
34
+ ```py
35
+ from mkpipe_core.plugins.registry import EXTRACTORS
36
+
37
+ def test_postgres_extractor():
38
+ postgres_extractor = EXTRACTORS.get("postgres")
39
+ if not postgres_extractor:
40
+ print("Postgres extractor not found!")
41
+ return
42
+ instance = postgres_extractor()
43
+ instance.extract()
44
+
45
+ if __name__ == "__main__":
46
+ test_postgres_extractor()
47
+
48
+ ```
49
+
50
+ Where `elt.yaml` is your configuration file that specifies the extractors, transformers, and loaders.
51
+
52
+ ## Documentation
53
+
54
+ For more detailed documentation, please visit the [GitHub repository](https://github.com/m-karakus/mkpipe).
55
+
56
+ ## License
57
+
58
+ This project is licensed under the Apache 2.0 License - see the [LICENSE](LICENSE) file for details.
59
+
@@ -0,0 +1 @@
1
+ from .main import main as run
@@ -0,0 +1,63 @@
1
+ import yaml
2
+ from pathlib import Path
3
+
4
+ ROOT_DIR = Path(__file__).parent.resolve()
5
+
6
+ timezone = 'UTC'
7
+ spark_driver_memory = '4g'
8
+ spark_executor_memory = '3g'
9
+ partitions_count = 2
10
+ default_iterate_max_loop = 1_000
11
+ default_iterate_batch_size = 500_000
12
+
13
+
14
+ def update_globals(config):
15
+ """Update global variables based on the provided config dictionary."""
16
+ global_vars = globals()
17
+ for key, value in config.items():
18
+ if key in global_vars: # Update only if the key exists in the globals
19
+ global_vars[key] = value
20
+
21
+
22
+ def load_config(config_file):
23
+ config_path = Path(config_file).resolve()
24
+ if not config_path.exists():
25
+ raise FileNotFoundError(f'Configuration file not found: {config_path}')
26
+
27
+ global ROOT_DIR
28
+ ROOT_DIR = config_path.parent
29
+
30
+ with config_path.open('r') as f:
31
+ data = yaml.safe_load(f)
32
+ ENV = data.get(
33
+ 'default_environment', 'prod'
34
+ ) # Default to 'prod' if not specified
35
+ env_config = data.get(ENV, {})
36
+
37
+ # Extract settings under the 'settings' key
38
+ settings = env_config.get('settings', {})
39
+ update_globals(settings)
40
+
41
+ return env_config
42
+
43
+
44
+ def get_config_value(keys, file_name):
45
+ """
46
+ Retrieve a specific configuration value using a list of keys.
47
+
48
+ Args:
49
+ keys (list): List of keys to retrieve the value (e.g., ['paths', 'bucket_name']).
50
+ file_name (str, optional): Path to the configuration file. Defaults to None.
51
+
52
+ Returns:
53
+ The value corresponding to the keys or None if the path is invalid.
54
+ """
55
+ config = load_config(file_name)
56
+
57
+ value = config
58
+ for key in keys:
59
+ if isinstance(value, dict) and key in value:
60
+ value = value[key]
61
+ else:
62
+ return None
63
+ return value
@@ -0,0 +1,118 @@
1
+ import os
2
+ import time
3
+ from .config import load_config, get_config_value, timezone
4
+ from .run_coordinators import get_coordinator
5
+
6
+ from .utils import Logger, InputTask
7
+
8
+ os.environ['TZ'] = timezone
9
+ time.tzset()
10
+
11
+
12
+ # Function to manage priority levels and reset if necessary
13
+ def get_priority(pipeline_name, priority, custom_priority):
14
+ """Adjust priority based on pipeline name or reset if necessary."""
15
+ if custom_priority:
16
+ return custom_priority
17
+ priority -= 1
18
+ return 200 if priority < 1 else priority
19
+
20
+
21
+ def main(config_file_name: str, pipeline_name_set=None, table_name_set=None):
22
+ logger = Logger(config_file_name)
23
+ logger.log({'file_name': config_file_name})
24
+
25
+ DATA = load_config(config_file=config_file_name)
26
+ run_coordinator = get_config_value(
27
+ ['settings', 'run_coordinator'], file_name=config_file_name
28
+ )
29
+
30
+ # Validate that pipeline_name_set and table_name_set are sets
31
+ if pipeline_name_set and not isinstance(pipeline_name_set, set):
32
+ raise TypeError('pipeline_name_set must be a set')
33
+ if table_name_set and not isinstance(table_name_set, set):
34
+ raise TypeError('table_name_set must be a set')
35
+
36
+ jobs = DATA['jobs']
37
+
38
+ # Filter jobs based on pipeline_name_set if provided
39
+ if pipeline_name_set:
40
+ jobs = [job for job in jobs if job['name'] in pipeline_name_set]
41
+
42
+ # Initialize the priority counter starting from 200
43
+ priority = 200
44
+
45
+ # Create a list to hold all tasks for the chord
46
+ task_group = []
47
+
48
+ # Iterate over the filtered jobs
49
+ for job in jobs:
50
+ pipeline_name = job['name']
51
+ extract_task = job['extract_task']
52
+ load_task = job['load_task']
53
+ custom_priority = job.get('priority', None)
54
+
55
+ print(f'Running pipeline: {pipeline_name}')
56
+
57
+ # Loader Configuration
58
+ try:
59
+ loader_conf = DATA['loaders'][load_task]['config']
60
+ loader_variant = DATA['loaders'][load_task]['variant']
61
+ connection_params = DATA['connections'][loader_conf['connection_ref']]
62
+ loader_conf['connection_params'] = connection_params
63
+
64
+ except KeyError as e:
65
+ logger.log(
66
+ {
67
+ 'error': f'Loader configuration issue: {str(e)}',
68
+ 'loader_task': load_task,
69
+ }
70
+ )
71
+ continue # Skip this job if there is an error
72
+
73
+ # Extractor Configuration
74
+ try:
75
+ extractor_conf = DATA['extractors'][extract_task]['config']
76
+ extractor_variant = DATA['extractors'][extract_task]['variant']
77
+ connection_params = DATA['connections'][extractor_conf['connection_ref']]
78
+ extractor_conf['connection_params'] = connection_params
79
+ except KeyError as e:
80
+ logger.log(
81
+ {
82
+ 'error': f'Extractor configuration issue: {str(e)}',
83
+ 'extract_task': extract_task,
84
+ }
85
+ )
86
+ continue # Skip this job if there is an error
87
+
88
+ # Loop through each table in the extractor's configuration
89
+ for table in extractor_conf.get('tables', []):
90
+ # Skip this table if it's not in the provided set
91
+ if table_name_set and table['name'] not in table_name_set:
92
+ continue
93
+
94
+ # Copy the extractor config for the current table
95
+ current_table_conf = extractor_conf.copy()
96
+ current_table_conf['table'] = table # Add the specific table
97
+ current_table_conf.pop('tables', None)
98
+
99
+ # Get the adjusted priority level for the current pipeline
100
+ priority = get_priority(pipeline_name, priority, custom_priority)
101
+
102
+ task = InputTask(
103
+ extractor_variant=extractor_variant,
104
+ current_table_conf=current_table_conf,
105
+ loader_variant=loader_variant,
106
+ loader_conf=loader_conf,
107
+ priority=custom_priority,
108
+ )
109
+
110
+ # Add the extraction task to the chord group, using kwargs
111
+ task_group.append(task)
112
+
113
+ if not task_group:
114
+ logger.log({'warning': 'No tasks were scheduled to run.'})
115
+ return
116
+
117
+ coordinator = get_coordinator(run_coordinator)(task_group)
118
+ coordinator.run()
@@ -0,0 +1,3 @@
1
+ from .registry import EXTRACTORS, LOADERS, get_extractor, get_loader
2
+
3
+ __all__ = (get_extractor, get_loader)
@@ -0,0 +1,35 @@
1
+ import importlib.metadata
2
+
3
+
4
+ def discover_plugins(group):
5
+ """
6
+ Discover plugins registered under a specific entry point group.
7
+ :param group: Entry point group name (e.g., 'mkpipe.extractors')
8
+ :return: Dictionary of plugin names and their corresponding classes
9
+ """
10
+ try:
11
+ entry_points = importlib.metadata.entry_points(group=group)
12
+ return {ep.name: ep.load() for ep in entry_points}
13
+ except Exception as e:
14
+ print(f'Error discovering plugins: {e}')
15
+ return {}
16
+
17
+
18
+ # Example usage
19
+ EXTRACTOR_GROUP = 'mkpipe.extractors'
20
+ LOADER_GROUP = 'mkpipe.loaders'
21
+
22
+ EXTRACTORS = discover_plugins(EXTRACTOR_GROUP)
23
+ LOADERS = discover_plugins(LOADER_GROUP)
24
+
25
+
26
+ def get_loader(variant):
27
+ if variant not in LOADERS:
28
+ raise ValueError(f'Unsupported loader type: {variant}')
29
+ return LOADERS.get(variant)
30
+
31
+
32
+ def get_extractor(variant):
33
+ if variant not in EXTRACTORS:
34
+ raise ValueError(f'Unsupported extractor type: {variant}')
35
+ return EXTRACTORS.get(variant)
@@ -0,0 +1,3 @@
1
+ from .registry import get_coordinator
2
+
3
+ __all__ = get_coordinator
@@ -0,0 +1,163 @@
1
+ # celery --app mkpipe.run_coordinators.coordinator_celery.CoordinatorCelery.app worker --loglevel=info --concurrency=4
2
+ from celery import Celery, chord
3
+ from kombu import Queue
4
+ from dotenv import load_dotenv
5
+ import os
6
+ import datetime
7
+ from ..plugins import get_extractor, get_loader
8
+
9
+
10
+ class CoordinatorCelery:
11
+ def __init__(self, task_group):
12
+ self.task_group = task_group
13
+ self.app = self.initialize_celery()
14
+ self.register_tasks()
15
+
16
+ def initialize_celery(self):
17
+ # Load environment variables
18
+ dotenv_path = os.path.join(os.path.dirname(__file__), '..', '.env')
19
+ load_dotenv(dotenv_path)
20
+
21
+ # Celery app configuration
22
+ broker_user = os.getenv('RABBITMQ_DEFAULT_USER', 'guest')
23
+ broker_pass = os.getenv('RABBITMQ_DEFAULT_PASS', 'guest')
24
+ broker_host = os.getenv('BROKER_HOST', 'rabbitmq')
25
+ broker_port = os.getenv('BROKER_PORT', '5672')
26
+
27
+ CELERY_BROKER_URL = (
28
+ f'amqp://{broker_user}:{broker_pass}@{broker_host}:{broker_port}//'
29
+ )
30
+ CELERY_BACKEND_URL = os.getenv('CELERY_BACKEND_URL', 'rpc://')
31
+
32
+ app = Celery('celery_app')
33
+ app.conf.update(
34
+ broker_url=CELERY_BROKER_URL,
35
+ result_backend=CELERY_BACKEND_URL,
36
+ task_acks_late=True,
37
+ worker_prefetch_multiplier=1,
38
+ task_queues=(
39
+ Queue(
40
+ 'mkpipe_queue',
41
+ exchange='mkpipe_exchange',
42
+ routing_key='mkpipe',
43
+ queue_arguments={'x-max-priority': 255},
44
+ ),
45
+ ),
46
+ task_routes={
47
+ 'elt.celery_app.extract_data': {'queue': 'mkpipe_queue'},
48
+ 'elt.celery_app.load_data': {'queue': 'mkpipe_queue'},
49
+ },
50
+ task_default_queue='mkpipe_queue',
51
+ task_default_exchange='mkpipe_exchange',
52
+ task_default_routing_key='mkpipe',
53
+ # Retry settings
54
+ task_retry_limit=3, # Maximum retries
55
+ task_retry_backoff=True, # Enable exponential backoff
56
+ task_retry_backoff_jitter=True, # Adds slight randomness
57
+ result_expires=3600, # Result expiration time in seconds
58
+ result_chord_retry_interval=60,
59
+ broker_connection_retry_on_startup=True,
60
+ worker_direct=True,
61
+ )
62
+ return app
63
+
64
+ def register_tasks(self):
65
+ """Register tasks dynamically after app initialization."""
66
+
67
+ @self.app.task(
68
+ bind=True,
69
+ max_retries=3,
70
+ retry_backoff=True,
71
+ retry_backoff_jitter=True,
72
+ track_started=True,
73
+ )
74
+ def extract_data(self_task, **kwargs):
75
+ extractor_variant = kwargs['extractor_variant']
76
+ current_table_conf = kwargs['current_table_conf']
77
+ loader_variant = kwargs['loader_variant']
78
+ loader_conf = kwargs['loader_conf']
79
+
80
+ extractor = get_extractor(extractor_variant)(current_table_conf)
81
+ data = extractor.extract()
82
+
83
+ if data:
84
+ self_task.request.app.send_task(
85
+ 'load_data',
86
+ kwargs={
87
+ 'loader_variant': loader_variant,
88
+ 'loader_conf': loader_conf,
89
+ 'data': data,
90
+ },
91
+ priority=201,
92
+ queue='mkpipe_queue',
93
+ exchange='mkpipe_exchange',
94
+ routing_key='mkpipe',
95
+ )
96
+
97
+ print('Extracted data successfully!')
98
+ return True
99
+
100
+ @self.app.task(
101
+ bind=True,
102
+ max_retries=3,
103
+ retry_backoff=True,
104
+ retry_backoff_jitter=True,
105
+ track_started=True,
106
+ )
107
+ def load_data(self_task, **kwargs):
108
+ loader_variant = kwargs['loader_variant']
109
+ loader_conf = kwargs['loader_conf']
110
+ data = kwargs['data']
111
+
112
+ loader = get_loader(loader_variant)(loader_conf)
113
+ elt_start_time = datetime.datetime.now()
114
+ loader.load(data, elt_start_time)
115
+
116
+ print('Loaded data successfully!')
117
+ return True
118
+
119
+ @self.app.task
120
+ def on_all_tasks_completed(results):
121
+ print(f'All tasks completed with results: {results}')
122
+
123
+ if all(results):
124
+ print('Both extraction and loading tasks succeeded.')
125
+ else:
126
+ print('One or more tasks failed. DBT not triggered.')
127
+
128
+ return 'All tasks completed!' if all(results) else 'Some tasks failed!'
129
+
130
+ # Assign tasks to the class instance
131
+ self.extract_data = extract_data
132
+ self.load_data = load_data
133
+ self.on_all_tasks_completed = on_all_tasks_completed
134
+
135
+ def run_parallel_tasks(self, task_group):
136
+ chord(
137
+ task_group,
138
+ body=self.on_all_tasks_completed.s().set(
139
+ queue='mkpipe_queue',
140
+ exchange='mkpipe_exchange',
141
+ routing_key='mkpipe',
142
+ ),
143
+ ).apply_async()
144
+
145
+ def run(self):
146
+ celery_task_group = []
147
+ for task in self.task_group:
148
+ celery_task_group.append(
149
+ self.extract_data.s(
150
+ extractor_variant=task.extractor_variant,
151
+ current_table_conf=task.current_table_conf,
152
+ loader_variant=task.loader_variant,
153
+ loader_conf=task.loader_conf,
154
+ ).set(
155
+ priority=task.priority,
156
+ queue='mkpipe_queue',
157
+ exchange='mkpipe_exchange',
158
+ routing_key='mkpipe',
159
+ )
160
+ )
161
+
162
+ if celery_task_group:
163
+ self.run_parallel_tasks(celery_task_group)
@@ -0,0 +1,38 @@
1
+ import datetime
2
+ from ..plugins import get_extractor, get_loader
3
+
4
+
5
+ class CoordinatorSingle:
6
+ def __init__(self, task_group):
7
+ self.task_group = task_group
8
+
9
+ def load_data(self, task):
10
+ # Initialize loader instance
11
+ loader = get_loader(task.loader_variant)(task.loader_conf)
12
+
13
+ # Record the start time of the loading process
14
+ elt_start_time = datetime.datetime.now()
15
+
16
+ # Load the extracted data with the start time
17
+ loader.load(task.data, elt_start_time)
18
+
19
+ print('Loaded data successfully!')
20
+ return True # Return True to indicate success
21
+
22
+ def extract_data(self, task):
23
+ # Initialize extractor and loader instances
24
+ extractor = get_extractor(task.extractor_variant)(task.current_table_conf)
25
+
26
+ # Perform the data extraction
27
+ task.data = extractor.extract()
28
+ print('Extracted data successfully!')
29
+
30
+ if task.data:
31
+ # Schedule the data loading as a separate task
32
+ self.load_data(task)
33
+
34
+ return True # Return True to indicate success
35
+
36
+ def run(self):
37
+ for task in self.task_group:
38
+ self.extract_data(task)
@@ -0,0 +1,29 @@
1
+ from .coordinator_single import CoordinatorSingle
2
+ from .coordinator_celery import CoordinatorCelery
3
+
4
+
5
+ RUN_COORDINATORS = {}
6
+
7
+
8
+ def register_coordinator(variant):
9
+ def decorator(fn):
10
+ RUN_COORDINATORS[variant] = fn
11
+ return fn
12
+
13
+ return decorator
14
+
15
+
16
+ @register_coordinator('single')
17
+ def coordinator_single(conf):
18
+ return CoordinatorSingle(conf)
19
+
20
+
21
+ @register_coordinator('celery')
22
+ def coordinator_celery(conf):
23
+ return CoordinatorCelery(conf)
24
+
25
+
26
+ def get_coordinator(variant):
27
+ if variant not in RUN_COORDINATORS:
28
+ raise ValueError(f'Unsupported coordinator type: {variant}')
29
+ return RUN_COORDINATORS.get(variant)
@@ -0,0 +1,9 @@
1
+ from .logger import Logger
2
+ from .logger import log_container
3
+ from .base_class import InputTask
4
+
5
+ __all__ = (
6
+ Logger,
7
+ log_container,
8
+ InputTask,
9
+ )
@@ -0,0 +1,11 @@
1
+ from pydantic import BaseModel
2
+ from typing import Optional
3
+
4
+
5
+ class InputTask(BaseModel):
6
+ extractor_variant: str
7
+ current_table_conf: dict
8
+ loader_variant: str
9
+ loader_conf: dict
10
+ priority: Optional[int] = None
11
+ data: Optional[dict] = None
@@ -0,0 +1,184 @@
1
+ import json
2
+ import traceback
3
+ import os
4
+ import logging
5
+ import time
6
+ import logging.handlers
7
+ from dagster import get_dagster_logger
8
+ from ..config import ROOT_DIR
9
+
10
+ path = os.path.abspath(os.path.join(ROOT_DIR, 'logs'))
11
+ # path = ROOT_DIR / "logs"
12
+ # path.mkdir(exist_ok=True) # Create the directory if it doesn't exist
13
+
14
+ LOG_LEVEL = os.getenv('LOG_LEVEL', 'INFO').upper()
15
+
16
+
17
+ log_levels = {
18
+ 'debug': logging.DEBUG,
19
+ 'info': logging.INFO,
20
+ 'warning': logging.WARNING,
21
+ 'error': logging.ERROR,
22
+ 'critical': logging.CRITICAL,
23
+ }
24
+
25
+ default_log_level = log_levels.get(LOG_LEVEL.lower())
26
+
27
+
28
+ class Logger:
29
+ def __init__(self, name) -> None:
30
+ """
31
+ Custom Usage:
32
+ logger = Logger()
33
+ msg = 'This is a log message'
34
+ logger.log(msg, log_level="error")
35
+ or
36
+ logger.error("This is an error message")
37
+ """
38
+ self.logger = logging.getLogger(name)
39
+ self.dagster_logger = get_dagster_logger()
40
+ if not self.logger.handlers:
41
+ # create the handlers and call logger.addHandler(logging_handler)
42
+ self.logger = logging.getLogger(name)
43
+ # self.logger.setLevel(logging.DEBUG)
44
+ self.logger.setLevel(default_log_level)
45
+
46
+ # Create a formatter
47
+ # https://docs.python.org/3/library/logging.html#logrecord-attributes
48
+
49
+ frmt = """{"timestamp" : "%(asctime)s", "levelno" : "%(levelno)s", "level" : "%(levelname)s", "message" : %(message)s, "function" : "%(name)s" }"""
50
+ json_formatter = logging.Formatter(frmt)
51
+ json_formatter.converter = time.gmtime # set timezone as gmtime
52
+
53
+ frmt = '%(asctime)s | %(levelno)s | %(levelname)s | %(name)s | %(message)s'
54
+ string_formatter = logging.Formatter(frmt)
55
+ string_formatter.converter = time.gmtime # set timezone as gmtime
56
+
57
+ # Create a file handler
58
+ # Fetch the pod name (e.g., celery-consumer-66894599cd-85dvr)
59
+ pod_name = os.getenv('HOSTNAME', 'unknown_pod')
60
+
61
+ # date = datetime.today().strftime('%Y%m%d')
62
+ if not os.path.exists(path):
63
+ os.makedirs(path)
64
+ file_path = os.path.abspath(
65
+ os.path.join(
66
+ path, f'{pod_name}_log.log'
67
+ ) # Use pod name for unique log file
68
+ )
69
+
70
+ # use very short interval for this example, typical 'when' would be 'midnight' and no explicit interval
71
+ fh = logging.handlers.TimedRotatingFileHandler(
72
+ file_path, when='midnight', backupCount=7
73
+ )
74
+ # fh = logging.handlers.TimedRotatingFileHandler(file_path, when="midnight", backupCount=7)
75
+ # fh = logging.FileHandler(file_path, mode='a', encoding='utf8')
76
+
77
+ fh.setLevel(default_log_level)
78
+ # fh.setFormatter(json_formatter)
79
+ fh.setFormatter(string_formatter)
80
+
81
+ # Create a console handler (optional)
82
+ ch = logging.StreamHandler()
83
+ # ch.setLevel(logging.ERROR)
84
+ ch.setLevel(default_log_level)
85
+ ch.setFormatter(json_formatter)
86
+
87
+ # Add handlers to the logger
88
+ self.logger.addHandler(fh)
89
+ # self.logger.addHandler(ch)
90
+
91
+ def message_formatter(self, message):
92
+ # msg = json.dumps(str(message))
93
+ msg = json.dumps(message, sort_keys=True, indent=2, separators=(',', ': '))
94
+ return msg
95
+
96
+ def log(self, message, log_level='info'):
97
+ msg = self.message_formatter(message)
98
+
99
+ logger = self.logger
100
+ if log_level == 'debug':
101
+ logger.debug(msg)
102
+ self.dagster_logger.debug(msg)
103
+ elif log_level == 'info':
104
+ logger.info(msg)
105
+ self.dagster_logger.info(msg)
106
+ elif log_level == 'warning':
107
+ logger.warning(msg)
108
+ self.dagster_logger.warning(msg)
109
+ elif log_level == 'error':
110
+ logger.error(msg)
111
+ self.dagster_logger.error(msg)
112
+ elif log_level == 'critical':
113
+ logger.critical(msg)
114
+ self.dagster_logger.critical(msg)
115
+ else:
116
+ logger.exception(msg)
117
+ self.dagster_logger.exception(msg)
118
+ return
119
+
120
+ def debug(self, message):
121
+ msg = self.message_formatter(message)
122
+ self.logger.debug(msg)
123
+ self.dagster_logger.debug(msg)
124
+ return
125
+
126
+ def info(self, message):
127
+ msg = self.message_formatter(message)
128
+ self.logger.info(msg)
129
+ self.dagster_logger.info(msg)
130
+ return
131
+
132
+ def warning(self, message):
133
+ msg = self.message_formatter(message)
134
+ self.logger.warning(msg)
135
+ self.dagster_logger.warning(msg)
136
+ return
137
+
138
+ def error(self, message):
139
+ msg = self.message_formatter(message)
140
+ self.logger.error(msg)
141
+ self.dagster_logger.error(msg)
142
+ return
143
+
144
+ def critical(self, message):
145
+ msg = self.message_formatter(message)
146
+ self.logger.critical(msg)
147
+ self.dagster_logger.critical(msg)
148
+ return
149
+
150
+ def shutdown(self):
151
+ logging.shutdown()
152
+
153
+
154
+ def log_container(name):
155
+ def inner(func):
156
+ def wrapper(*args, **kwargs):
157
+ # Log some messages
158
+ logger = Logger(name)
159
+
160
+ try:
161
+ # send start message
162
+ # message = f'Started function: {func.__name__}'
163
+ # logger.log(message)
164
+ # start_time = time.time()
165
+
166
+ # call the function
167
+ result = func(*args, **kwargs)
168
+
169
+ # run_time = time.time() - start_time
170
+ # message = (
171
+ # f'Ended function: {func.__name__}. Time Duration(sec): {run_time} '
172
+ # )
173
+ # logger.log(message)
174
+
175
+ return result
176
+
177
+ except Exception as e:
178
+ message = str(e) + str(traceback.format_exc()).replace('\n', ' ')
179
+ logger.log(message, log_level='error')
180
+ raise
181
+
182
+ return wrapper
183
+
184
+ return inner
@@ -0,0 +1,11 @@
1
+ Metadata-Version: 2.1
2
+ Name: mkpipe
3
+ Version: 0.1.2
4
+ Summary: Core ETL pipeline framework for mkpipe.
5
+ Author: Metin Karakus
6
+ Author-email: metin_karakus@yahoo.com
7
+ License: Apache License 2.0
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: Apache Software License
10
+ Requires-Python: >=3.8
11
+ License-File: LICENSE
@@ -0,0 +1,21 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ README.md
4
+ setup.py
5
+ mkpipe/__init__.py
6
+ mkpipe/config.py
7
+ mkpipe/main.py
8
+ mkpipe.egg-info/PKG-INFO
9
+ mkpipe.egg-info/SOURCES.txt
10
+ mkpipe.egg-info/dependency_links.txt
11
+ mkpipe.egg-info/top_level.txt
12
+ mkpipe/plugins/__init__.py
13
+ mkpipe/plugins/registry.py
14
+ mkpipe/run_coordinators/__init__.py
15
+ mkpipe/run_coordinators/coordinator_celery.py
16
+ mkpipe/run_coordinators/coordinator_single.py
17
+ mkpipe/run_coordinators/registry.py
18
+ mkpipe/utils/__init__.py
19
+ mkpipe/utils/base_class.py
20
+ mkpipe/utils/logger.py
21
+ tests/test_core.py
@@ -0,0 +1 @@
1
+ mkpipe
mkpipe-0.1.2/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
mkpipe-0.1.2/setup.py ADDED
@@ -0,0 +1,23 @@
1
+ from setuptools import setup, find_packages
2
+
3
+ setup(
4
+ name='mkpipe',
5
+ version='0.1.2',
6
+ license='Apache License 2.0',
7
+ packages=find_packages(exclude=['tests', 'scripts']),
8
+ install_requires=[],
9
+ include_package_data=True,
10
+ entry_points={
11
+ 'mkpipe.extractors': [],
12
+ 'mkpipe.loaders': [],
13
+ 'mkpipe.transformers': [],
14
+ },
15
+ description='Core ETL pipeline framework for mkpipe.',
16
+ author='Metin Karakus',
17
+ author_email='metin_karakus@yahoo.com',
18
+ classifiers=[
19
+ 'Programming Language :: Python :: 3',
20
+ 'License :: OSI Approved :: Apache Software License',
21
+ ],
22
+ python_requires='>=3.8',
23
+ )
File without changes