forked from Netflix/dispatch
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecorators.py
More file actions
167 lines (131 loc) · 5.1 KB
/
decorators.py
File metadata and controls
167 lines (131 loc) · 5.1 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
from functools import wraps
from typing import Any, Callable, List
import inspect
import logging
import time
from dispatch.metrics import provider as metrics_provider
from dispatch.organization import service as organization_service
from dispatch.project import service as project_service
from .database.core import engine, sessionmaker
from sqlalchemy.orm import scoped_session
log = logging.getLogger(__name__)
def fullname(o):
module = inspect.getmodule(o)
return f"{module.__name__}.{o.__qualname__}"
def _execute_task_in_project_context(
func: Callable,
*args,
**kwargs,
) -> None:
CoreSession = scoped_session(sessionmaker(bind=engine))
db_session = CoreSession()
metrics_provider.counter("function.call.counter", tags={"function": fullname(func)})
start = time.perf_counter()
try:
# iterate for all schema
for organization in organization_service.get_all(db_session=db_session):
schema_engine = engine.execution_options(
schema_translate_map={None: f"dispatch_organization_{organization.slug}"}
)
OrgSession = scoped_session(sessionmaker(bind=schema_engine))
schema_session = OrgSession()
try:
kwargs["db_session"] = schema_session
for project in project_service.get_all(db_session=schema_session):
kwargs["project"] = project
func(*args, **kwargs)
except Exception as e:
log.error(
f"Error trying to execute task: {fullname(func)} with parameters {args} and {kwargs}"
)
log.exception(e)
finally:
OrgSession.remove()
elapsed_time = time.perf_counter() - start
metrics_provider.timer(
"function.elapsed.time", value=elapsed_time, tags={"function": fullname(func)}
)
except Exception as e:
# No rollback necessary as we only read from the database
log.error(f"Error trying to execute task: {fullname(func)}")
log.exception(e)
finally:
CoreSession.remove()
def scheduled_project_task(func: Callable):
"""Decorator that sets up a background task function with
a database session and exception tracking.
Each task is executed in a specific project context.
"""
@wraps(func)
def wrapper(*args, **kwargs):
_execute_task_in_project_context(
func,
*args,
**kwargs,
)
return wrapper
def background_task(func):
"""Decorator that sets up the a background task function
with a database session and exception tracking.
As background tasks run in their own threads, it does not attempt
to propagate errors.
"""
@wraps(func)
def wrapper(*args, **kwargs):
background = False
if not kwargs.get("db_session"):
if not kwargs.get("organization_slug"):
raise Exception("If not db_session is supplied organization slug must be provided.")
schema_engine = engine.execution_options(
schema_translate_map={
None: f"dispatch_organization_{kwargs['organization_slug']}",
}
)
db_session = sessionmaker(bind=schema_engine)
background = True
kwargs["db_session"] = db_session()
try:
metrics_provider.counter("function.call.counter", tags={"function": fullname(func)})
start = time.perf_counter()
result = func(*args, **kwargs)
elapsed_time = time.perf_counter() - start
metrics_provider.timer(
"function.elapsed.time", value=elapsed_time, tags={"function": fullname(func)}
)
return result
except Exception as e:
log.exception(e)
finally:
if background:
kwargs["db_session"].close()
return wrapper
def timer(func: Any):
"""Timing decorator that sends a timing metric."""
@wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
elapsed_time = time.perf_counter() - start
metrics_provider.timer(
"function.elapsed.time", value=elapsed_time, tags={"function": fullname(func)}
)
log.debug(f"function.elapsed.time.{fullname(func)}: {elapsed_time}")
return result
return wrapper
def counter(func: Any):
"""Counting decorator that sends a counting metric."""
@wraps(func)
def wrapper(*args, **kwargs):
metrics_provider.counter("function.call.counter", tags={"function": fullname(func)})
return func(*args, **kwargs)
return wrapper
def apply(decorator: Any, exclude: List[str] = None):
"""Class decorator that applies specified decorator to all class methods."""
if not exclude:
exclude = []
def decorate(cls):
for attr in cls.__dict__:
if callable(getattr(cls, attr)) and attr not in exclude:
setattr(cls, attr, decorator(getattr(cls, attr)))
return cls
return decorate