Repository navigation
Expand file tree
/
Copy pathqueue.py
More file actions
290 lines (230 loc) · 8.54 KB
/
Copy pathqueue.py
File metadata and controls
290 lines (230 loc) · 8.54 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
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
"""Database interface for automated ACL queue. Used primarily by ``load_acl`` and
``acl``` commands for manipulating the work queue.
>>> from trigger.acl.queue import Queue
>>> q = Queue()
>>> q.list()
(('dc1-abc.net.aol.com', 'datacenter-protect'), ('dc2-abc.net.aol.com',
'datacenter-protect'))
""" # noqa: D205
import datetime
from trigger import exceptions
from trigger.conf import settings
from trigger.netdevices import NetDevices
from trigger.utils import get_user
from . import models
# Globals
QUEUE_NAMES = ("integrated", "manual")
# Exports
__all__ = ("Queue",)
# Classes
class Queue:
"""Interacts with firewalls database to insert/remove items into the queue.
:param verbose:
Toggle verbosity
:type verbose:
Boolean
"""
def __init__(self, verbose=True): # noqa: D107
self.nd = NetDevices()
self.verbose = verbose
self.login = get_user()
def vprint(self, msg):
"""Print something if ``verbose`` instance variable is set.
:param msg:
The string to print
"""
if self.verbose:
print(msg)
def get_model(self, queue):
"""Given a queue name, return its DB model.
:param queue:
Name of the queue whose object you want
"""
return models.MODEL_MAP.get(queue, None)
def create_task(self, queue, *args, **kwargs):
"""Create a task in the specified queue.
:param queue:
Name of the queue whose object you want
"""
model = self.get_model(queue)
model.create(*args, **kwargs)
def _normalize(self, arg, prefix=""):
"""Remove ``prefix`` from ``arg``, and set "escalation" bit.
:param arg:
Arg (typically an ACL filename) to trim
:param prefix:
Prefix to trim from arg
"""
arg = arg.removeprefix(prefix)
escalation = False
if arg.upper().endswith(" ESCALATION"):
escalation = True
arg = arg[:-11]
return (escalation, arg)
def insert(self, acl, routers, escalation=False):
"""Insert an ACL and associated devices into the ACL load queue.
Attempts to insert into integrated queue. If ACL test fails, then
item is inserted into manual queue.
:param acl:
ACL name
:param routers:
List of device names
:param escalation:
Whether this is an escalated task
"""
if not acl:
msg = "You must specify an ACL to insert into the queue"
raise exceptions.ACLQueueError(
msg,
)
if not routers:
routers = []
escalation, acl = self._normalize(acl)
if routers:
for router in routers:
try:
dev = self.nd.find(router)
except KeyError as err:
msg = f"Could not find device {router}"
raise exceptions.TriggerError(msg) from err
if acl not in dev.acls:
msg = f"Could not find {acl} in ACL list for {router}"
raise exceptions.TriggerError(msg)
self.create_task(
queue="integrated",
acl=acl,
router=router,
escalation=escalation,
)
self.vprint(
"ACL {} injected into integrated load queue for {}".format(
acl,
", ".join(dev[: dev.find(".")] for dev in routers),
),
)
else:
self.create_task(queue="manual", q_name=acl, login=self.login)
self.vprint(f'"{acl}" injected into manual load queue')
def delete(self, acl, routers=None, escalation=False):
"""Delete an ACL from the firewall database queue.
Attempts to delete from integrated queue. If ACL test fails
or if routers are not specified, the item is deleted from manual queue.
:param acl:
ACL name
:param routers:
List of device names. If this is ommitted, the manual queue is used.
:param escalation:
Whether this is an escalated task
"""
if not acl:
msg = "You must specify an ACL to delete from the queue"
raise exceptions.ACLQueueError(
msg,
)
_escalation, acl = self._normalize(acl)
m = self.get_model("integrated")
if routers is not None:
devs = routers
else:
self.vprint("Fetching routers from database")
result = (
m.select(m.router)
.distinct()
.where(m.acl == acl, m.loaded >> None)
.order_by(m.router)
)
rows = result.tuples()
devs = [row[0] for row in rows]
if devs:
for dev in devs:
m.delete().where(
m.acl == acl,
m.router == dev,
m.loaded >> None,
).execute()
self.vprint(
"ACL {} cleared from integrated load queue for {}".format(
acl,
", ".join(dev[: dev.find(".")] for dev in devs),
),
)
return True
m = self.get_model("manual")
if m.delete().where(m.q_name == acl, m.done == False).execute(): # noqa: E712 - peewee requires == for query
self.vprint(f"{acl!r} cleared from manual load queue")
return True
self.vprint(f"{acl!r} not found in any queues")
return False
def complete(self, device, acls):
"""Mark a device and its ACLs as complete using current timestamp.
(Integrated queue only.)
:param device:
Device names
:param acls:
List of ACL names
"""
m = self.get_model("integrated")
for acl in acls:
now = datetime.datetime.now()
m.update(loaded=now).where(
m.acl == acl,
m.router == device,
m.loaded >> None,
).execute()
self.vprint(f"Marked the following ACLs as complete for {device}:")
self.vprint(", ".join(acls))
def remove(self, acl, routers, escalation=False):
"""Integrated queue only.
Mark an ACL and associated devices as "removed" (loaded=0). Intended
for use when performing manual actions on the load queue when
troubleshooting or addressing errors with automated loads. This leaves
the items in the database but removes them from the active queue.
:param acl:
ACL name
:param routers:
List of device names
:param escalation:
Whether this is an escalated task
"""
if not acl:
msg = "You must specify an ACL to remove from the queue"
raise exceptions.ACLQueueError(
msg,
)
m = self.get_model("integrated")
loaded = 0
if settings.DATABASE_ENGINE == "postgresql":
loaded = "-infinity" # See: http://bit.ly/15f0J3z
for router in routers:
m.update(loaded=loaded).where(
m.acl == acl,
m.router == router,
m.loaded >> None,
).execute()
self.vprint(f"Marked the following devices as removed for ACL {acl}: ")
self.vprint(", ".join(routers))
def list(self, queue="integrated", escalation=False, q_names=QUEUE_NAMES):
"""List items in the specified queue, defauls to integrated queue.
:param queue:
Name of the queue to list
:param escalation:
Whether this is an escalated task
:param q_names:
(Optional) List of valid queue names
"""
if queue not in q_names:
self.vprint(f"Queue must be one of {q_names}, not: {queue}")
return False
m = self.get_model(queue)
if queue == "integrated":
result = (
m.select(m.router, m.acl)
.distinct()
.where(m.loaded >> None, m.escalation == escalation)
)
elif queue == "manual":
result = m.select(m.q_name, m.login, m.q_ts, m.done).where(m.done == False) # noqa: E712 - peewee requires == for query
else:
msg = "This should never happen!!"
raise RuntimeError(msg)
return list(result.tuples())