garf-executors 0.2.3__py3-none-any.whl → 1.1.3__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.
Files changed (49) hide show
  1. garf/executors/__init__.py +25 -0
  2. garf/executors/api_executor.py +228 -0
  3. garf/executors/bq_executor.py +179 -0
  4. garf/executors/config.py +52 -0
  5. garf/executors/entrypoints/__init__.py +0 -0
  6. garf/executors/entrypoints/cli.py +164 -0
  7. {garf_executors → garf/executors}/entrypoints/grpc_server.py +22 -9
  8. garf/executors/entrypoints/server.py +174 -0
  9. garf/executors/entrypoints/tracer.py +82 -0
  10. garf/executors/entrypoints/utils.py +140 -0
  11. garf/executors/exceptions.py +17 -0
  12. garf/executors/execution_context.py +117 -0
  13. garf/executors/executor.py +124 -0
  14. garf/executors/fetchers.py +128 -0
  15. garf/executors/garf_pb2.py +51 -0
  16. {garf_executors → garf/executors}/garf_pb2_grpc.py +45 -2
  17. garf/executors/query_processor.py +79 -0
  18. garf/executors/setup.py +58 -0
  19. garf/executors/sql_executor.py +144 -0
  20. garf/executors/telemetry.py +20 -0
  21. garf/executors/workflows/__init__.py +0 -0
  22. garf/executors/workflows/gcp_workflow.yaml +49 -0
  23. garf/executors/workflows/workflow.py +164 -0
  24. garf/executors/workflows/workflow_runner.py +172 -0
  25. garf_executors/__init__.py +9 -44
  26. garf_executors/api_executor.py +9 -121
  27. garf_executors/bq_executor.py +9 -161
  28. garf_executors/config.py +9 -37
  29. garf_executors/entrypoints/__init__.py +25 -0
  30. garf_executors/entrypoints/cli.py +9 -148
  31. garf_executors/entrypoints/grcp_server.py +25 -0
  32. garf_executors/entrypoints/server.py +9 -102
  33. garf_executors/entrypoints/tracer.py +8 -40
  34. garf_executors/entrypoints/utils.py +9 -124
  35. garf_executors/exceptions.py +11 -3
  36. garf_executors/execution_context.py +9 -100
  37. garf_executors/executor.py +9 -108
  38. garf_executors/fetchers.py +9 -63
  39. garf_executors/sql_executor.py +9 -125
  40. garf_executors/telemetry.py +10 -5
  41. garf_executors/workflow.py +8 -79
  42. {garf_executors-0.2.3.dist-info → garf_executors-1.1.3.dist-info}/METADATA +18 -5
  43. garf_executors-1.1.3.dist-info/RECORD +46 -0
  44. {garf_executors-0.2.3.dist-info → garf_executors-1.1.3.dist-info}/WHEEL +1 -1
  45. garf_executors-1.1.3.dist-info/entry_points.txt +2 -0
  46. {garf_executors-0.2.3.dist-info → garf_executors-1.1.3.dist-info}/top_level.txt +1 -0
  47. garf_executors/garf_pb2.py +0 -45
  48. garf_executors-0.2.3.dist-info/RECORD +0 -24
  49. garf_executors-0.2.3.dist-info/entry_points.txt +0 -2
@@ -0,0 +1,25 @@
1
+ # Copyright 2025 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # https://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Executors to fetch data from various APIs."""
15
+
16
+ from __future__ import annotations
17
+
18
+ from garf.executors.api_executor import ApiExecutionContext, ApiQueryExecutor
19
+
20
+ __all__ = [
21
+ 'ApiQueryExecutor',
22
+ 'ApiExecutionContext',
23
+ ]
24
+
25
+ __version__ = '1.1.3'
@@ -0,0 +1,228 @@
1
+ # Copyright 2024 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # https://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Module for executing Garf queries and writing them to local/remote.
15
+
16
+ ApiQueryExecutor performs fetching data from API in a form of
17
+ GarfReport and saving it to local/remote storage.
18
+ """
19
+ # pylint: disable=C0330, g-bad-import-order, g-multiple-import
20
+
21
+ from __future__ import annotations
22
+
23
+ import logging
24
+ import pathlib
25
+
26
+ from garf.core import report_fetcher, simulator
27
+ from garf.executors import (
28
+ exceptions,
29
+ execution_context,
30
+ executor,
31
+ fetchers,
32
+ query_processor,
33
+ )
34
+ from garf.executors.telemetry import tracer
35
+ from opentelemetry import metrics, trace
36
+
37
+ logger = logging.getLogger(__name__)
38
+ meter = metrics.get_meter('garf.executors')
39
+
40
+ api_counter = meter.create_counter(
41
+ 'garf_api_execute_total',
42
+ unit='1',
43
+ description='Counts number of API executions',
44
+ )
45
+
46
+
47
+ class ApiExecutionContext(execution_context.ExecutionContext):
48
+ """Common context for executing one or more queries."""
49
+
50
+ writer: str | list[str] = 'console'
51
+
52
+
53
+ class ApiQueryExecutor(executor.Executor):
54
+ """Gets data from API and writes them to local/remote storage.
55
+
56
+ Attributes:
57
+ api_client: a client used for connecting to API.
58
+ """
59
+
60
+ def __init__(
61
+ self,
62
+ fetcher: report_fetcher.ApiReportFetcher,
63
+ report_simulator: simulator.ApiReportSimulator | None = None,
64
+ ) -> None:
65
+ """Initializes ApiQueryExecutor.
66
+
67
+ Args:
68
+ fetcher: Instantiated report fetcher.
69
+ report_simulator: Instantiated simulator.
70
+ """
71
+ self.fetcher = fetcher
72
+ self.simulator = report_simulator
73
+ super().__init__(
74
+ preprocessors=self.fetcher.preprocessors,
75
+ postprocessors=self.fetcher.postprocessors,
76
+ )
77
+
78
+ @classmethod
79
+ def from_fetcher_alias(
80
+ cls,
81
+ source: str,
82
+ fetcher_parameters: dict[str, str] | None = None,
83
+ enable_cache: bool = False,
84
+ cache_ttl_seconds: int = 3600,
85
+ ) -> ApiQueryExecutor:
86
+ if not fetcher_parameters:
87
+ fetcher_parameters = {}
88
+ concrete_api_fetcher = fetchers.get_report_fetcher(source)
89
+ return ApiQueryExecutor(
90
+ fetcher=concrete_api_fetcher(
91
+ **fetcher_parameters,
92
+ enable_cache=enable_cache,
93
+ cache_ttl_seconds=cache_ttl_seconds,
94
+ )
95
+ )
96
+
97
+ @tracer.start_as_current_span('api.execute')
98
+ def execute(
99
+ self,
100
+ query: str,
101
+ title: str,
102
+ context: ApiExecutionContext,
103
+ ) -> str:
104
+ """Reads query, extract results and stores them in a specified location.
105
+
106
+ Args:
107
+ query: Location of the query.
108
+ title: Name of the query.
109
+ context: Query execution context.
110
+
111
+ Returns:
112
+ Result of writing the report.
113
+
114
+ Raises:
115
+ GarfExecutorError: When failed to execute query.
116
+ """
117
+ if self.simulator:
118
+ return self.simulate(query=query, title=title, context=context)
119
+ context = query_processor.process_gquery(context)
120
+ span = trace.get_current_span()
121
+ span.set_attribute('fetcher.class', self.fetcher.__class__.__name__)
122
+ span.set_attribute(
123
+ 'api.client.class', self.fetcher.api_client.__class__.__name__
124
+ )
125
+ try:
126
+ span.set_attribute('query.title', title)
127
+ span.set_attribute('query.text', query)
128
+ logger.debug('starting query %s', query)
129
+ title = pathlib.Path(title).name.split('.')[0]
130
+ api_counter.add(
131
+ 1, {'api.client.class': self.fetcher.api_client.__class__.__name__}
132
+ )
133
+ results = self.fetcher.fetch(
134
+ query_specification=query,
135
+ args=context.query_parameters,
136
+ title=title,
137
+ **context.fetcher_parameters,
138
+ )
139
+ writer_clients = context.writer_clients
140
+ if not writer_clients:
141
+ logger.warning('No writers configured, skipping write operation')
142
+ return None
143
+ writing_results = []
144
+ for writer_client in writer_clients:
145
+ logger.debug(
146
+ 'Start writing data for query %s via %s writer',
147
+ title,
148
+ type(writer_client),
149
+ )
150
+ result = writer_client.write(results, title)
151
+ logger.debug(
152
+ 'Finish writing data for query %s via %s writer',
153
+ title,
154
+ type(writer_client),
155
+ )
156
+ writing_results.append(result)
157
+ logger.info('%s executed successfully', title)
158
+ # Return the last writer's result for backward compatibility
159
+ return writing_results[-1] if writing_results else None
160
+ except Exception as e:
161
+ logger.error('%s generated an exception: %s', title, str(e))
162
+ raise exceptions.GarfExecutorError(
163
+ '%s generated an exception: %s', title, str(e)
164
+ ) from e
165
+
166
+ @tracer.start_as_current_span('api.simulate')
167
+ def simulate(
168
+ self,
169
+ query: str,
170
+ title: str,
171
+ context: ApiExecutionContext,
172
+ ) -> str:
173
+ """Reads query, simulates results and stores them in a specified location.
174
+
175
+ Args:
176
+ query: Location of the query.
177
+ title: Name of the query.
178
+ context: Query execution context.
179
+
180
+ Returns:
181
+ Result of writing the report.
182
+
183
+ Raises:
184
+ GarfExecutorError: When failed to execute query.
185
+ """
186
+ context = query_processor.process_gquery(context)
187
+ span = trace.get_current_span()
188
+ span.set_attribute('fetcher.class', self.fetcher.__class__.__name__)
189
+ span.set_attribute(
190
+ 'api.client.class', self.fetcher.api_client.__class__.__name__
191
+ )
192
+ try:
193
+ span.set_attribute('query.title', title)
194
+ span.set_attribute('query.text', query)
195
+ logger.debug('starting query %s', query)
196
+ title = pathlib.Path(title).name.split('.')[0]
197
+ results = self.simulator.simulate(
198
+ query_specification=query,
199
+ args=context.query_parameters,
200
+ title=title,
201
+ **context.fetcher_parameters,
202
+ )
203
+ writer_clients = context.writer_clients
204
+ if not writer_clients:
205
+ logger.warning('No writers configured, skipping write operation')
206
+ return None
207
+ writing_results = []
208
+ for writer_client in writer_clients:
209
+ logger.debug(
210
+ 'Start writing data for query %s via %s writer',
211
+ title,
212
+ type(writer_client),
213
+ )
214
+ result = writer_client.write(results, title)
215
+ logger.debug(
216
+ 'Finish writing data for query %s via %s writer',
217
+ title,
218
+ type(writer_client),
219
+ )
220
+ writing_results.append(result)
221
+ logger.info('%s executed successfully', title)
222
+ # Return the last writer's result for backward compatibility
223
+ return writing_results[-1] if writing_results else None
224
+ except Exception as e:
225
+ logger.error('%s generated an exception: %s', title, str(e))
226
+ raise exceptions.GarfExecutorError(
227
+ '%s generated an exception: %s', title, str(e)
228
+ ) from e
@@ -0,0 +1,179 @@
1
+ # Copyright 2024 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # https://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Executes queries in BigQuery."""
15
+
16
+ from __future__ import annotations
17
+
18
+ import contextlib
19
+ import os
20
+
21
+ try:
22
+ from google.cloud import bigquery # type: ignore
23
+ except ImportError as e:
24
+ raise ImportError(
25
+ 'Please install garf-executors with BigQuery support '
26
+ '- `pip install garf-executors[bq]`'
27
+ ) from e
28
+
29
+ import logging
30
+
31
+ from garf.core import query_editor, report
32
+ from garf.executors import exceptions, execution_context, executor
33
+ from garf.executors.telemetry import tracer
34
+ from google.cloud import exceptions as google_cloud_exceptions
35
+ from opentelemetry import trace
36
+
37
+ logger = logging.getLogger(__name__)
38
+
39
+
40
+ class BigQueryExecutorError(exceptions.GarfExecutorError):
41
+ """Error when BigQueryExecutor fails to run query."""
42
+
43
+
44
+ class BigQueryExecutor(executor.Executor, query_editor.TemplateProcessorMixin):
45
+ """Handles query execution in BigQuery.
46
+
47
+ Attributes:
48
+ project_id: Google Cloud project id.
49
+ location: BigQuery dataset location.
50
+ client: BigQuery client.
51
+ """
52
+
53
+ def __init__(
54
+ self,
55
+ project_id: str | None = os.getenv('GOOGLE_CLOUD_PROJECT'),
56
+ location: str | None = None,
57
+ **kwargs: str,
58
+ ) -> None:
59
+ """Initializes BigQueryExecutor.
60
+
61
+ Args:
62
+ project_id: Google Cloud project id.
63
+ location: BigQuery dataset location.
64
+ """
65
+ if not project_id:
66
+ raise BigQueryExecutorError(
67
+ 'project_id is required. Either provide it as project_id parameter '
68
+ 'or GOOGLE_CLOUD_PROJECT env variable.'
69
+ )
70
+ self.project_id = project_id
71
+ self.location = location
72
+ super().__init__()
73
+
74
+ @property
75
+ def client(self) -> bigquery.Client:
76
+ """Instantiates bigquery client."""
77
+ return bigquery.Client(self.project_id)
78
+
79
+ @tracer.start_as_current_span('bq.execute')
80
+ def execute(
81
+ self,
82
+ query: str,
83
+ title: str,
84
+ context: execution_context.ExecutionContext = (
85
+ execution_context.ExecutionContext()
86
+ ),
87
+ ) -> report.GarfReport:
88
+ """Executes query in BigQuery.
89
+
90
+ Args:
91
+ query: Location of the query.
92
+ title: Name of the query.
93
+ context: Query execution context.
94
+
95
+ Returns:
96
+ Report with data if query returns some data otherwise empty Report.
97
+ """
98
+ span = trace.get_current_span()
99
+ span.set_attribute('query.title', title)
100
+ span.set_attribute('query.text', query)
101
+ logger.info('Executing script: %s', title)
102
+ query_text = self.replace_params_template(query, context.query_parameters)
103
+ self.create_datasets(context.query_parameters.macro)
104
+ job = self.client.query(query_text)
105
+ try:
106
+ result = job.result()
107
+ except google_cloud_exceptions.GoogleCloudError as e:
108
+ raise BigQueryExecutorError(
109
+ f'Failed to execute query {title}: Reason: {e}'
110
+ ) from e
111
+ logger.debug('%s launched successfully', title)
112
+ if result.total_rows:
113
+ results = report.GarfReport.from_pandas(result.to_dataframe())
114
+ else:
115
+ results = report.GarfReport()
116
+ if context.writer and results:
117
+ writer_clients = context.writer_clients
118
+ if not writer_clients:
119
+ logger.warning('No writers configured, skipping write operation')
120
+ else:
121
+ writing_results = []
122
+ for writer_client in writer_clients:
123
+ logger.debug(
124
+ 'Start writing data for query %s via %s writer',
125
+ title,
126
+ type(writer_client),
127
+ )
128
+ writing_result = writer_client.write(results, title)
129
+ logger.debug(
130
+ 'Finish writing data for query %s via %s writer',
131
+ title,
132
+ type(writer_client),
133
+ )
134
+ writing_results.append(writing_result)
135
+ # Return the last writer's result for backward compatibility
136
+ logger.info('%s executed successfully', title)
137
+ return writing_results[-1] if writing_results else None
138
+ logger.info('%s executed successfully', title)
139
+ span.set_attribute('execute.num_results', len(results))
140
+ return results
141
+
142
+ @tracer.start_as_current_span('bq.create_datasets')
143
+ def create_datasets(self, macros: dict | None) -> None:
144
+ """Creates datasets in BQ based on values in a dict.
145
+
146
+ If dict contains keys with 'dataset' in them, then values for such keys
147
+ are treated as dataset names.
148
+
149
+ Args:
150
+ macros: Mapping containing data for query execution.
151
+ """
152
+ if macros and (datasets := extract_datasets(macros)):
153
+ for dataset in datasets:
154
+ dataset_id = f'{self.project_id}.{dataset}'
155
+ try:
156
+ self.client.get_dataset(dataset_id)
157
+ except google_cloud_exceptions.NotFound:
158
+ bq_dataset = bigquery.Dataset(dataset_id)
159
+ bq_dataset.location = self.location
160
+ with contextlib.suppress(google_cloud_exceptions.Conflict):
161
+ self.client.create_dataset(bq_dataset, timeout=30)
162
+ logger.info('Created new dataset %s', dataset_id)
163
+
164
+
165
+ def extract_datasets(macros: dict | None) -> list[str]:
166
+ """Finds dataset-related keys based on values in a dict.
167
+
168
+ If dict contains keys with 'dataset' in them, then values for such keys
169
+ are treated as dataset names.
170
+
171
+ Args:
172
+ macros: Mapping containing data for query execution.
173
+
174
+ Returns:
175
+ Possible names of datasets.
176
+ """
177
+ if not macros:
178
+ return []
179
+ return [value for macro, value in macros.items() if 'dataset' in macro]
@@ -0,0 +1,52 @@
1
+ # Copyright 2025 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # https://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # pylint: disable=C0330, g-bad-import-order, g-multiple-import
16
+
17
+ """Stores mapping between API aliases and their execution context."""
18
+
19
+ from __future__ import annotations
20
+
21
+ import os
22
+ import pathlib
23
+
24
+ import pydantic
25
+ import smart_open
26
+ import yaml
27
+ from garf.executors.execution_context import ExecutionContext
28
+
29
+
30
+ class Config(pydantic.BaseModel):
31
+ """Stores necessary parameters for one or multiple API sources.
32
+
33
+ Attributes:
34
+ source: Mapping between API source alias and execution parameters.
35
+ """
36
+
37
+ sources: dict[str, ExecutionContext]
38
+
39
+ @classmethod
40
+ def from_file(cls, path: str | pathlib.Path | os.PathLike[str]) -> Config:
41
+ """Builds config from local or remote yaml file."""
42
+ with smart_open.open(path, 'r', encoding='utf-8') as f:
43
+ data = yaml.safe_load(f)
44
+ return Config(sources=data)
45
+
46
+ def save(self, path: str | pathlib.Path | os.PathLike[str]) -> str:
47
+ """Saves config to local or remote yaml file."""
48
+ with smart_open.open(path, 'w', encoding='utf-8') as f:
49
+ yaml.dump(
50
+ self.model_dump(exclude_none=True).get('sources'), f, encoding='utf-8'
51
+ )
52
+ return f'Config is saved to {str(path)}'
File without changes
@@ -0,0 +1,164 @@
1
+ # Copyright 2025 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # https://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ """Module for defining `garf` CLI utility.
15
+
16
+ `garf` allows to execute queries and store results in local/remote
17
+ storage.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import argparse
23
+ import logging
24
+ import pathlib
25
+ import sys
26
+
27
+ import garf.executors
28
+ from garf.executors import config, exceptions, setup
29
+ from garf.executors.entrypoints import utils
30
+ from garf.executors.entrypoints.tracer import (
31
+ initialize_meter,
32
+ initialize_tracer,
33
+ )
34
+ from garf.executors.telemetry import tracer
35
+ from garf.executors.workflows import workflow, workflow_runner
36
+ from garf.io import reader
37
+ from opentelemetry import trace
38
+
39
+ initialize_tracer()
40
+ meter_provider = initialize_meter()
41
+
42
+
43
+ @tracer.start_as_current_span('garf.entrypoints.cli')
44
+ def main():
45
+ parser = argparse.ArgumentParser()
46
+ parser.add_argument('query', nargs='*')
47
+ parser.add_argument('-c', '--config', dest='config', default=None)
48
+ parser.add_argument('-w', '--workflow', dest='workflow', default=None)
49
+ parser.add_argument('--source', dest='source', default=None)
50
+ parser.add_argument('--output', dest='output', default='console')
51
+ parser.add_argument('--input', dest='input', default='file')
52
+ parser.add_argument('--log', '--loglevel', dest='loglevel', default='info')
53
+ parser.add_argument('--logger', dest='logger', default='local')
54
+ parser.add_argument('--log-name', dest='log_name', default='garf')
55
+ parser.add_argument(
56
+ '--parallel-queries', dest='parallel_queries', action='store_true'
57
+ )
58
+ parser.add_argument(
59
+ '--no-parallel-queries', dest='parallel_queries', action='store_false'
60
+ )
61
+ parser.add_argument('--simulate', dest='simulate', action='store_true')
62
+ parser.add_argument('--dry-run', dest='dry_run', action='store_true')
63
+ parser.add_argument('-v', '--version', dest='version', action='store_true')
64
+ parser.add_argument(
65
+ '--parallel-threshold', dest='parallel_threshold', default=10, type=int
66
+ )
67
+ parser.add_argument(
68
+ '--enable-cache', dest='enable_cache', action='store_true'
69
+ )
70
+ parser.add_argument(
71
+ '--cache-ttl-seconds',
72
+ dest='cache_ttl_seconds',
73
+ default=3600,
74
+ type=int,
75
+ )
76
+ parser.add_argument('--workflow-skip', dest='workflow_skip', default=None)
77
+ parser.add_argument(
78
+ '--workflow-include', dest='workflow_include', default=None
79
+ )
80
+ parser.set_defaults(parallel_queries=True)
81
+ parser.set_defaults(simulate=False)
82
+ parser.set_defaults(enable_cache=False)
83
+ parser.set_defaults(dry_run=False)
84
+ args, kwargs = parser.parse_known_args()
85
+
86
+ span = trace.get_current_span()
87
+ command_args = ' '.join(sys.argv[1:])
88
+ span.set_attribute('cli.command', f'garf {command_args}')
89
+ if args.version:
90
+ print(garf.executors.__version__)
91
+ sys.exit()
92
+ logger = utils.init_logging(
93
+ loglevel=args.loglevel.upper(), logger_type=args.logger, name=args.log_name
94
+ )
95
+ reader_client = reader.create_reader(args.input)
96
+ param_types = ['source', 'macro', 'template']
97
+ outputs = args.output.split(',')
98
+ extra_parameters = utils.ParamsParser([*param_types, *outputs]).parse(kwargs)
99
+ source_parameters = extra_parameters.get('source', {})
100
+ writer_parameters = {}
101
+ for output in outputs:
102
+ writer_parameters.update(extra_parameters.get(output))
103
+
104
+ context = garf.executors.api_executor.ApiExecutionContext(
105
+ query_parameters={
106
+ 'macro': extra_parameters.get('macro'),
107
+ 'template': extra_parameters.get('template'),
108
+ },
109
+ writer=outputs,
110
+ writer_parameters=writer_parameters,
111
+ fetcher_parameters=source_parameters,
112
+ )
113
+ if workflow_file := args.workflow:
114
+ wf_parent = pathlib.Path.cwd() / pathlib.Path(workflow_file).parent
115
+ execution_workflow = workflow.Workflow.from_file(workflow_file, context)
116
+ workflow_skip = args.workflow_skip if args.workflow_skip else None
117
+ workflow_include = args.workflow_include if args.workflow_include else None
118
+ workflow_runner.WorkflowRunner(
119
+ execution_workflow=execution_workflow, wf_parent=wf_parent
120
+ ).run(
121
+ enable_cache=args.enable_cache,
122
+ cache_ttl_seconds=args.cache_ttl_seconds,
123
+ selected_aliases=workflow_include,
124
+ skipped_aliases=workflow_skip,
125
+ )
126
+ meter_provider.shutdown()
127
+ sys.exit()
128
+
129
+ if not args.query:
130
+ logger.error('Please provide one or more queries to run')
131
+ raise exceptions.GarfExecutorError(
132
+ 'Please provide one or more queries to run'
133
+ )
134
+ if config_file := args.config:
135
+ execution_config = config.Config.from_file(config_file)
136
+ if not (context := execution_config.sources.get(args.source)):
137
+ raise exceptions.GarfExecutorError(
138
+ f'No execution context found for source {args.source} in {config_file}'
139
+ )
140
+ query_executor = setup.setup_executor(
141
+ source=args.source,
142
+ fetcher_parameters=context.fetcher_parameters,
143
+ enable_cache=args.enable_cache,
144
+ cache_ttl_seconds=args.cache_ttl_seconds,
145
+ simulate=args.simulate,
146
+ )
147
+ batch = {query: reader_client.read(query) for query in args.query}
148
+ if args.parallel_queries and len(args.query) > 1:
149
+ logger.info('Running queries in parallel')
150
+ batch = {query: reader_client.read(query) for query in args.query}
151
+ query_executor.execute_batch(batch, context, args.parallel_threshold)
152
+ else:
153
+ if len(args.query) > 1:
154
+ logger.info('Running queries sequentially')
155
+ for query in args.query:
156
+ query_executor.execute(
157
+ query=reader_client.read(query), title=query, context=context
158
+ )
159
+ logging.shutdown()
160
+ meter_provider.shutdown()
161
+
162
+
163
+ if __name__ == '__main__':
164
+ main()