-
Notifications
You must be signed in to change notification settings - Fork 1
/
group_cleanup.py
69 lines (57 loc) · 1.79 KB
/
group_cleanup.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
"""
Delete machines belonging to group that are too old.
"""
import logging
from datetime import datetime, timedelta
import threading
import argh
from app import (
app,
Machine,
MachineState,
MachineTemplate,
User,
db,
and_,
VirtService,
DockerService,
OpenStackService,
Audit,
create_audit,
update_audit,
finish_audit,
)
def main(group_id, hours_old_to_delete, do_delete=False):
"""
Delete machines belonging to group that are too old.
"""
with app.app_context():
VirtService.set_app(app)
current_time = datetime.utcnow()
time_hours_ago = current_time - timedelta(hours=int(hours_old_to_delete))
# get machines from group that are > hours old
results = (
db.session.query(User, Machine, MachineTemplate)
.join(Machine, Machine.owner_id == User.id)
.join(MachineTemplate, Machine.machine_template_id == MachineTemplate.id)
.filter(
and_(
MachineTemplate.group_id == group_id,
Machine.state.in_([MachineState.READY, MachineState.STOPPED]),
Machine.creation_date <= time_hours_ago,
~User.is_admin,
)
)
).all()
for u, m, mt in results:
machine_age = current_time - m.creation_date
print(
f"template: {mt.name}, owner: {u.username}, name: {m.display_name}, age: {machine_age}"
)
if do_delete:
audit = create_audit("timeout vm", "starting")
update_audit(audit, machine=m)
OpenStackService.stop(m.id, audit.id)
finish_audit(audit, "ok")
if __name__ == "__main__":
argh.dispatch_command(main)