-
Notifications
You must be signed in to change notification settings - Fork 18
/
JobManager.py
285 lines (185 loc) · 9.17 KB
/
JobManager.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
# Copyright 2022-2023 Google, LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import uuid, datetime, json, configparser
import constants
from google.cloud import firestore
from google.cloud.firestore_v1.base_query import FieldFilter
from google.cloud import tasks_v2
from google.api_core.client_info import ClientInfo
USER_AGENT = 'cloud-solutions/datacatalog-tag-engine-v2'
class JobManager:
"""Class for managing jobs for async task create and update requests
cloud_run_sa = Cloud Run service account
queue_project = Project where the queue is based (e.g. tag-engine-project)
queue_region = Region where the queue is based (e.g. us-central1)
queue_name = Name of the queue (e.g. tag-engine-queue)
task_handler_uri = task handler uri in the Flask app hosted by Cloud Run
"""
def __init__(self,
tag_engine_sa,
tag_engine_project,
tag_engine_region,
tag_engine_queue,
task_handler_uri,
db_project,
db_name):
self.tag_engine_sa = tag_engine_sa
self.tag_engine_project = tag_engine_project
self.tag_engine_region = tag_engine_region
self.tag_engine_queue = tag_engine_queue
self.task_handler_uri = task_handler_uri
self.db = firestore.Client(project=db_project, database=db_name, client_info=ClientInfo(user_agent=USER_AGENT))
##################### API METHODS #################
def create_job(self, tag_creator_account, tag_invoker_account, config_uuid, config_type, metadata=None):
job_uuid = self._create_job_record(config_uuid, config_type)
if metadata != None:
self._create_job_metadata_record(job_uuid, config_uuid, config_type, metadata)
resp = self._create_job_task(tag_creator_account, tag_invoker_account, job_uuid, config_uuid, config_type)
return job_uuid
def update_job_running(self, job_uuid):
#print('*** update_job_running ***')
job_ref = self.db.collection('jobs').document(job_uuid)
job_ref.update({'job_status': 'RUNNING'})
print('Set job running.')
def record_num_tasks(self, job_uuid, num_tasks):
job_ref = self.db.collection('jobs').document(job_uuid)
job_ref.update({'task_count': num_tasks})
print('record_num_tasks')
def calculate_job_completion(self, job_uuid):
tasks_success = self._get_tasks_success(job_uuid)
tasks_failed = self._get_tasks_failed(job_uuid)
tasks_ran = tasks_success + tasks_failed
print('tasks_success:', tasks_success)
print('tasks_failed:', tasks_failed)
print('tasks_ran:', tasks_ran)
job_ref = self.db.collection('jobs').document(job_uuid)
job = job_ref.get()
if job.exists:
job_dict = job.to_dict()
task_count = job_dict['task_count']
# job running
if job_dict['task_count'] > tasks_ran:
job_ref.update({
'tasks_ran': tasks_success + tasks_failed,
'job_status': 'RUNNING',
'tasks_success': tasks_success,
'tasks_failed': tasks_failed,
})
pct_complete = round(tasks_ran / task_count * 100, 2)
# job completed
if job_dict['task_count'] <= tasks_ran:
if tasks_failed > 0:
job_ref.update({
'tasks_ran': tasks_success + tasks_failed,
'tasks_success': tasks_success,
'tasks_failed': tasks_failed,
'job_status': 'ERROR',
'completion_time': datetime.datetime.utcnow()
})
else:
job_ref.update({
'tasks_ran': tasks_success + tasks_failed,
'tasks_success': tasks_success,
'tasks_failed': tasks_failed,
'job_status': 'SUCCESS',
'completion_time': datetime.datetime.utcnow()
})
pct_complete = 100
return tasks_success, tasks_failed, pct_complete
def get_job_status(self, job_uuid):
job = self.db.collection('jobs').document(job_uuid).get()
if job.exists:
job_dict = job.to_dict()
return job_dict
def set_job_status(self, job_uuid, status):
self.db.collection('jobs').document(job_uuid).update({
'job_status': status
})
################ INTERNAL PROCESSING METHODS #################
def _create_job_record(self, config_uuid, config_type):
print('*** _create_job_record ***')
job_uuid = uuid.uuid1().hex
job_ref = self.db.collection('jobs').document(job_uuid)
job_ref.set({
'job_uuid': job_uuid,
'config_uuid': config_uuid,
'config_type': config_type,
'job_status': 'PENDING',
'task_count': 0,
'tasks_ran': 0,
'tasks_success': 0,
'tasks_failed': 0,
'creation_time': datetime.datetime.utcnow()
})
print('Created job record.')
return job_uuid
def _create_job_task(self, tag_creator_account, tag_invoker_account, job_uuid, config_uuid, config_type):
payload = {'job_uuid': job_uuid, 'config_uuid': config_uuid, 'config_type': config_type, \
'tag_creator_account': tag_creator_account, 'tag_invoker_account': tag_invoker_account}
task = {
'http_request': {
'http_method': 'POST',
'url': self.task_handler_uri,
'headers': {'content-type': 'application/json'},
'body': json.dumps(payload).encode(),
'oidc_token': {'service_account_email': self.tag_engine_sa, 'audience': self.task_handler_uri}
}
}
print('task create:', task)
client = tasks_v2.CloudTasksClient()
parent = client.queue_path(self.tag_engine_project, self.tag_engine_region, self.tag_engine_queue)
resp = client.create_task(parent=parent, task=task)
print('task resp: ', resp)
return resp
def _get_task_count(job_uuid):
job = self.db.collection('jobs').document(job_uuid).get()
if job.exists:
job_dict = job.to_dict()
return job_dict['task_count']
def _get_tasks_success(self, job_uuid):
tasks_success = 0
shards = self.db.collection('shards').where(filter=FieldFilter('job_uuid', '==', job_uuid)).stream()
for shard in shards:
tasks_success += shard.to_dict().get('tasks_success', 0)
return tasks_success
def _get_tasks_failed(self, job_uuid):
tasks_failed = 0
shards = self.db.collection('shards').where(filter=FieldFilter('job_uuid', '==', job_uuid)).stream()
for shard in shards:
tasks_failed += shard.to_dict().get('tasks_failed', 0)
return tasks_failed
def _create_job_metadata_record(self, job_uuid, config_uuid, config_type, metadata):
print('*** _create_job_metadata_record ***')
job_ref = self.db.collection('job_metadata').document(job_uuid)
job_ref.set({
'job_uuid': job_uuid,
'config_uuid': config_uuid,
'config_type': config_type,
'metadata': metadata,
'creation_time': datetime.datetime.utcnow()
})
print('Created job_metadata record.')
if __name__ == '__main__':
config = configparser.ConfigParser()
config.read("tagengine.ini")
queue_project = config['DEFAULT']['QUEUE_PROJECT']
queue_region = config['DEFAULT']['QUEUE_REGION']
queue_name = config['DEFAULT']['INJECTOR_QUEUE']
task_handler_uri = '/_split_work'
db_project = config['DEFAULT']['FIRESTORE_PROJECT']
db_name = config['DEFAULT']['FIRESTORE_DB']
jm = JobManager(queue_project, queue_region, queue_name, task_handler_uri, db_project, db_name)
config_uuid = '1f1b4720839c11eca541e1ad551502cb'
jm.create_async_job(config_uuid)
print('done')