-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.py
597 lines (470 loc) · 17.3 KB
/
db.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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "ipetrash"
import enum
import time
from datetime import datetime
from typing import Type, Iterable, Self, Optional, Any
from urllib.parse import urljoin
from jinja2.sandbox import SandboxedEnvironment
# pip install peewee
from peewee import (
Model,
Field,
TextField,
ForeignKeyField,
DateTimeField,
BooleanField,
CharField,
IntegerField,
)
from playhouse.hybrid import hybrid_property
from playhouse.shortcuts import model_to_dict
from playhouse.sqliteq import SqliteQueueDatabase
from root_config import DB_FILE_NAME, CONFIG, CONFIG_NOTIFICATION
from third_party.db_enum_field import EnumField
from third_party.shorten import shorten
class NotDefinedParameterException(ValueError):
def __init__(self, parameter_name: str):
self.parameter_name = parameter_name
text = f'Parameter "{self.parameter_name}" must be defined!'
super().__init__(text)
# This working with multithreading
# SOURCE: http://docs.peewee-orm.com/en/latest/peewee/playhouse.html#sqliteq
db = SqliteQueueDatabase(
DB_FILE_NAME,
pragmas={
"foreign_keys": 1,
"journal_mode": "wal", # WAL-mode
"cache_size": -1024 * 64, # 64MB page-cache
},
use_gevent=False, # Use the standard library "threading" module.
autostart=True,
queue_max_size=64, # Max. # of pending writes that can accumulate.
results_timeout=5.0, # Max. time to wait for query to be executed.
)
@enum.unique
class TaskRunStatusEnum(enum.StrEnum):
PENDING = enum.auto()
RUNNING = enum.auto()
FINISHED = enum.auto()
STOPPED = enum.auto()
UNKNOWN = enum.auto()
ERROR = enum.auto()
@enum.unique
class TaskRunWorkStatusEnum(enum.StrEnum):
NONE = enum.auto()
IN_PROCESSED = enum.auto()
SUCCESSFUL = enum.auto()
FAILED = enum.auto()
STOPPED = enum.auto()
@enum.unique
class StopReasonEnum(enum.StrEnum):
SERVER_API = enum.auto()
TASK_DISABLED = enum.auto()
UNIT_STOP = enum.auto()
@enum.unique
class LogKindEnum(enum.StrEnum):
OUT = enum.auto()
ERR = enum.auto()
@enum.unique
class NotificationKindEnum(enum.StrEnum):
EMAIL = enum.auto()
TELEGRAM = enum.auto()
class BaseModel(Model):
class Meta:
database = db
only_save_dirty = True
def get_new(self) -> Self:
return type(self).get(self._pk_expr())
@classmethod
def get_first(cls) -> Self:
return cls.select().first()
@classmethod
def get_last(cls) -> Self:
return cls.select().order_by(cls.id.desc()).first()
@classmethod
def get_inherited_models(cls) -> list[Type[Self]]:
return sorted(cls.__subclasses__(), key=lambda x: x.__name__)
@classmethod
def print_count_of_tables(cls):
items = []
for sub_cls in cls.get_inherited_models():
name = sub_cls.__name__
count = sub_cls.select().count()
items.append(f"{name}: {count}")
print(", ".join(items))
@classmethod
def count(cls, filters: Iterable = None) -> int:
query = cls.select()
if filters:
query = query.filter(*filters)
return query.count()
def to_dict(self) -> dict[str, Any]:
return model_to_dict(self, recurse=False)
def __str__(self):
fields = []
for k, field in self._meta.fields.items():
v = getattr(self, k)
if isinstance(field, (TextField, CharField)):
if isinstance(v, enum.Enum):
v = v.value
if v:
v = repr(shorten(v, length=30))
elif isinstance(field, ForeignKeyField):
k = f"{k}_id"
if v:
v = v.id
fields.append(f"{k}={v}")
return self.__class__.__name__ + "(" + ", ".join(fields) + ")"
class Task(BaseModel):
name = TextField(unique=True)
command = TextField()
description = TextField(null=True)
is_enabled = BooleanField(default=True)
cron = TextField(null=True)
is_infinite = BooleanField(default=False)
@hybrid_property
def number_of_runs(self) -> int:
return self.runs.where(TaskRun.status != TaskRunStatusEnum.PENDING).count()
def get_last_started_run(self) -> Optional["TaskRun"]:
return (
self
.runs
.where(TaskRun.status != TaskRunStatusEnum.PENDING)
.order_by(TaskRun.id.desc())
.first()
)
# TODO: единая логика с get_last_started_run. Добавить параметр фильтра
def get_last_run(self) -> Optional["TaskRun"]:
return (
self
.runs
.order_by(TaskRun.id.desc())
.first()
)
@hybrid_property
def last_started_run_seq(self) -> int | None:
run: TaskRun | None = self.get_last_started_run()
return run.seq if run else None
@hybrid_property
def last_started_run_start_date(self) -> datetime | None:
run: TaskRun | None = self.get_last_started_run()
return run.start_date if run else None
@hybrid_property
def next_scheduled_date(self) -> datetime | None:
run = self.get_pending_run(has_scheduled_date=True)
return run.scheduled_date if run else None
@hybrid_property
def last_work_status(self) -> TaskRunWorkStatusEnum:
run: TaskRun | None = self.get_last_started_run()
if not run:
return TaskRunWorkStatusEnum.NONE
return run.work_status
def to_dict(self) -> dict[str, Any]:
return model_to_dict(
self,
recurse=False,
extra_attrs=[
"number_of_runs",
"last_started_run_seq",
"last_started_run_start_date",
"next_scheduled_date",
"last_work_status",
],
)
@classmethod
def get_by_name(cls, name: str) -> Self | None:
if not name:
raise NotDefinedParameterException("name")
return cls.get_or_none(name=name)
def get_actual_is_enabled(self) -> bool:
return Task.get_by_id(self.id).is_enabled
@classmethod
def add(
cls,
name: str,
command: str,
description: str = None,
cron: str = None,
is_enabled: bool = True,
is_infinite: bool = False,
) -> Self:
obj = cls.get_by_name(name)
if obj:
return obj
return cls.create(
name=name,
command=command,
description=description,
cron=cron,
is_enabled=is_enabled,
is_infinite=is_infinite,
)
def set_command(self, command: str):
if self.command == command:
return
self.command = command
self.save()
def set_description(self, description: str):
if self.description == description:
return
self.description = description
self.save()
def set_enabled(self, value: bool):
if self.is_enabled == value:
return
self.is_enabled = value
self.save()
def set_is_infinite(self, value: bool):
if self.is_infinite == value:
return
self.is_infinite = value
self.save()
# TODO: Надо ли?
def get_last_scheduled_run(self) -> Optional["TaskRun"]:
last_run: TaskRun | None = self.get_last_run()
if not last_run or last_run.scheduled_date is None:
return None
return last_run
def get_pending_run(self, has_scheduled_date: bool = False) -> Optional["TaskRun"]:
for run in self.get_runs_by([TaskRunStatusEnum.PENDING]):
# Если нужно вернуть запуск с запланированной датой
if has_scheduled_date:
if run.scheduled_date is not None:
return run
else:
if run.scheduled_date is None:
return run
return None
def add_or_get_run(self, scheduled_date: datetime = None) -> "TaskRun":
# Ограничение количества запусков в ожидании, максимум 2: без запланированной даты и с ней
# Возврат уже ранее добавленного запуска
run = self.get_pending_run(has_scheduled_date=scheduled_date is not None)
if not run:
last_run = self.get_last_run()
run = TaskRun.create(
task=self,
seq=last_run.seq + 1 if last_run else 1,
command=self.command,
scheduled_date=scheduled_date,
)
return run
def get_runs_by(self, statuses: list[TaskRunStatusEnum]) -> list["TaskRun"]:
return list(
self.runs.where(
TaskRun.status.in_(statuses),
).order_by(TaskRun.create_date)
)
def get_current_run(self) -> Optional["TaskRun"]:
items = self.get_runs_by([TaskRunStatusEnum.RUNNING])
return items[0] if items else None
def get_all_logs(
self,
filter_by_text: str | None = None,
order_by: Field | None = None, # NOTE: Ожидается поле TaskRunLog
page: int = 1,
items_per_page: int = 10,
) -> list["TaskRunLog"]:
filters = [
TaskRunLog.task_run.in_(
TaskRun.select().where(TaskRun.task == self)
),
]
if filter_by_text:
filters.append(
TaskRunLog.text.ilike(f"%{filter_by_text}%")
)
query = TaskRunLog.select().where(*filters)
if order_by:
query = query.order_by(order_by)
query = query.paginate(page, items_per_page)
return list(query)
class TaskRun(BaseModel):
task = ForeignKeyField(Task, on_delete="CASCADE", backref="runs")
seq = IntegerField(default=1)
command = TextField()
status = EnumField(choices=TaskRunStatusEnum, default=TaskRunStatusEnum.PENDING)
stop_reason = EnumField(choices=StopReasonEnum, null=True)
process_id = IntegerField(null=True)
process_return_code = IntegerField(null=True)
create_date = DateTimeField(default=datetime.now)
start_date = DateTimeField(null=True)
finish_date = DateTimeField(null=True)
scheduled_date = DateTimeField(null=True)
class Meta:
indexes = (
# Уникальный индекс по ид. задачи и номеру запуска
(("task_id", "seq"), True),
)
@hybrid_property
def is_success(self) -> bool:
return self.status == TaskRunStatusEnum.FINISHED and self.process_return_code == 0
@hybrid_property
def work_status(self) -> TaskRunWorkStatusEnum:
if self.status == TaskRunStatusEnum.PENDING:
return TaskRunWorkStatusEnum.NONE
if self.status == TaskRunStatusEnum.RUNNING:
return TaskRunWorkStatusEnum.IN_PROCESSED
if self.status == TaskRunStatusEnum.STOPPED:
return TaskRunWorkStatusEnum.STOPPED
if self.is_success:
return TaskRunWorkStatusEnum.SUCCESSFUL
return TaskRunWorkStatusEnum.FAILED
def to_dict(self) -> dict[str, Any]:
return model_to_dict(
self,
recurse=False,
extra_attrs=[
"work_status",
],
)
@classmethod
def get_by_seq(cls, task_id: int, seq: int) -> Self:
return cls.get(
task_id=task_id,
seq=seq,
)
def set_status(self, value: TaskRunStatusEnum):
if value is None:
raise ValueError(
f"Нельзя изменить статус {self.status.value!r} в {value!r}"
)
if self.status == value:
return
def raise_about_bad_status():
raise ValueError(
f"Нельзя изменить статус {self.status.value!r} в {value.value!r}"
)
match value:
case TaskRunStatusEnum.PENDING:
raise_about_bad_status()
case TaskRunStatusEnum.RUNNING:
if self.status != TaskRunStatusEnum.PENDING:
raise_about_bad_status()
self.start_date = datetime.now()
case TaskRunStatusEnum.STOPPED:
if self.status not in [TaskRunStatusEnum.PENDING, TaskRunStatusEnum.RUNNING]:
raise_about_bad_status()
case TaskRunStatusEnum.FINISHED:
if self.status != TaskRunStatusEnum.RUNNING:
raise_about_bad_status()
self.finish_date = datetime.now()
case TaskRunStatusEnum.UNKNOWN:
if self.status != TaskRunStatusEnum.RUNNING:
raise_about_bad_status()
case TaskRunStatusEnum.ERROR:
# Ignore
pass
self.status = value
self.save()
def set_error(self, error_text: str):
self.set_status(TaskRunStatusEnum.ERROR)
self.add_log_err(text=error_text)
def set_stop(self, reason: StopReasonEnum):
self.stop_reason = reason
self.set_status(TaskRunStatusEnum.STOPPED)
self.add_log_out(text=f"Запуск остановлен по причине: {reason.value}") # TODO:
def is_scheduled_date_has_arrived(self) -> bool:
if self.scheduled_date is None:
return False
return self.scheduled_date <= datetime.now()
def set_process_id(self, value: int):
self.process_id = value
self.save()
def get_actual_status(self) -> TaskRunStatusEnum:
return TaskRun.get_by_id(self.id).status
def add_log(self, text: str, kind: LogKindEnum, end: str = "\n") -> "TaskRunLog":
return TaskRunLog.create(
task_run=self,
text=text + end,
kind=kind,
)
def add_log_out(self, text: str, end: str = "\n") -> "TaskRunLog":
return self.add_log(text=text, kind=LogKindEnum.OUT, end=end)
def add_log_err(self, text: str, end: str = "\n") -> "TaskRunLog":
return self.add_log(text=text, kind=LogKindEnum.ERR, end=end)
def send_notifications(self):
variables: dict[str, Any] = dict(run=self, config=CONFIG)
env = SandboxedEnvironment()
for kind in NotificationKindEnum:
template: dict[str, str] = CONFIG_NOTIFICATION[kind.value]["template"]
template_name: str = template["name"]
template_text: str = template["text"]
name: str = env.from_string(template_name).render(variables)
text: str = env.from_string(template_text).render(variables)
Notification.add(
task_run=self,
name=name,
text=text,
kind=kind,
)
def get_url(self, full: bool = True) -> str:
uri: str = f"/task/{self.task.id}/run/{self.seq}"
if not full:
return uri
return urljoin(CONFIG_NOTIFICATION["base_url"], uri)
class TaskRunLog(BaseModel):
task_run = ForeignKeyField(TaskRun, on_delete="CASCADE", backref="logs")
text = TextField()
kind = EnumField(choices=LogKindEnum)
date = DateTimeField(default=datetime.now)
class Notification(BaseModel):
task_run = ForeignKeyField(TaskRun, null=True, on_delete="CASCADE", backref="notifications")
name = TextField()
text = TextField()
kind = EnumField(choices=NotificationKindEnum)
append_date = DateTimeField(default=datetime.now)
sending_date = DateTimeField(null=True)
canceling_date = DateTimeField(null=True)
@classmethod
def add(
cls,
task_run: TaskRun | None,
name: str,
text: str,
kind: NotificationKindEnum,
) -> Self:
return cls.create(
task_run=task_run,
name=name,
text=text,
kind=kind,
)
@classmethod
def get_unsent(cls) -> list[Self]:
"""
Функция, что возвращает неотправленные уведомления
"""
return list(
cls
.select()
.where(
cls.sending_date.is_null(True),
cls.canceling_date.is_null(True),
)
.order_by(cls.append_date)
)
def is_ready(self) -> bool:
return self.sending_date is None and self.canceling_date is None
def set_as_send(self):
"""
Функция устанавливает дату отправки и сохраняет ее
"""
if self.is_ready():
self.sending_date = datetime.now()
self.save()
def cancel(self):
"""
Функция устанавливает дату отмены и сохраняет ее
"""
if self.is_ready():
self.canceling_date = datetime.now()
self.save()
db.connect()
db.create_tables(BaseModel.get_inherited_models())
# Задержка в 50мс, чтобы дать время на запуск SqliteQueueDatabase и создание таблиц
# Т.к. в SqliteQueueDatabase запросы на чтение выполняются сразу, а на запись попадают в очередь
time.sleep(0.050)
if __name__ == "__main__":
BaseModel.print_count_of_tables()