-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjob_manager.py
More file actions
213 lines (185 loc) · 5.9 KB
/
job_manager.py
File metadata and controls
213 lines (185 loc) · 5.9 KB
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
import psycopg2
from psycopg2.extras import RealDictCursor, Json
from datetime import datetime
import json
class JobManager:
def __init__(self, host='localhost', database='job_registry',
user='postgres', password='labpassword'):
"""Initialize database connection."""
self.conn = psycopg2.connect(
host=host,
database=database,
user=user,
password=password
)
self.conn.autocommit = False
self.cursor = self.conn.cursor(cursor_factory=RealDictCursor)
def create_job(self, job_name: str) -> int:
"""
Create a new job entry with 'pending' status.
Args:
job_name: Name of the job to create
Returns:
job_id: ID of the created job
"""
try:
self.cursor.execute(
"""
INSERT INTO jobs (job_name, status, created_at)
VALUES (%s, %s, %s)
RETURNING job_id;
""",
(job_name, 'pending', datetime.now())
)
job_id = self.cursor.fetchone()['job_id']
self.conn.commit()
return job_id
except Exception:
self.conn.rollback()
raise
def start_job(self, job_id: int) -> bool:
"""
Mark job as running and set started_at timestamp.
Args:
job_id: ID of the job to start
Returns:
bool: True if successful, False otherwise
"""
try:
self.cursor.execute(
"""
UPDATE jobs
SET status = %s,
started_at = %s
WHERE job_id = %s;
""",
('running', datetime.now(), job_id)
)
success = self.cursor.rowcount > 0
self.conn.commit()
return success
except Exception:
self.conn.rollback()
return False
def complete_job(self, job_id: int, result_data: dict) -> bool:
"""
Mark job as completed and store results.
Args:
job_id: ID of the job to complete
result_data: Dictionary containing job results
Returns:
bool: True if successful, False otherwise
"""
try:
self.cursor.execute(
"""
UPDATE jobs
SET status = %s,
completed_at = %s,
result_data = %s
WHERE job_id = %s;
""",
('completed', datetime.now(), Json(result_data), job_id)
)
success = self.cursor.rowcount > 0
self.conn.commit()
return success
except Exception:
self.conn.rollback()
return False
def fail_job(self, job_id: int, error_message: str) -> bool:
"""
Mark job as failed and store error message.
Args:
job_id: ID of the job that failed
error_message: Error description
Returns:
bool: True if successful, False otherwise
"""
try:
self.cursor.execute(
"""
UPDATE jobs
SET status = %s,
completed_at = %s,
error_message = %s
WHERE job_id = %s;
""",
('failed', datetime.now(), error_message, job_id)
)
success = self.cursor.rowcount > 0
self.conn.commit()
return success
except Exception:
self.conn.rollback()
return False
def get_job_status(self, job_id: int) -> dict:
"""
Retrieve current job status and metadata.
Args:
job_id: ID of the job to query
Returns:
dict: Job metadata including status, timestamps, and results
"""
self.cursor.execute(
"""
SELECT job_id, job_name, status, created_at, started_at, completed_at,
result_data, error_message
FROM jobs
WHERE job_id = %s;
""",
(job_id,)
)
result = self.cursor.fetchone()
return dict(result) if result else None
def get_jobs_by_status(self, status: str) -> list:
"""
Retrieve all jobs with specified status.
Args:
status: Job status to filter by
Returns:
list: List of job dictionaries
"""
self.cursor.execute(
"""
SELECT job_id, job_name, status, created_at, started_at, completed_at,
result_data, error_message
FROM jobs
WHERE status = %s
ORDER BY job_id;
""",
(status,)
)
results = self.cursor.fetchall()
return [dict(row) for row in results]
def get_job_duration(self, job_id: int) -> float:
"""
Calculate job execution duration in seconds.
Args:
job_id: ID of the job
Returns:
float: Duration in seconds, or None if not completed
"""
self.cursor.execute(
"""
SELECT started_at, completed_at
FROM jobs
WHERE job_id = %s;
""",
(job_id,)
)
result = self.cursor.fetchone()
if not result:
return None
started_at = result['started_at']
completed_at = result['completed_at']
if started_at is None or completed_at is None:
return None
duration = (completed_at - started_at).total_seconds()
return duration
def close(self):
"""Close database connection."""
if hasattr(self, 'cursor') and self.cursor:
self.cursor.close()
if hasattr(self, 'conn') and self.conn:
self.conn.close()