-
Notifications
You must be signed in to change notification settings - Fork 213
Expand file tree
/
Copy pathproject_cleanup.py
More file actions
160 lines (137 loc) · 5.2 KB
/
project_cleanup.py
File metadata and controls
160 lines (137 loc) · 5.2 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
# Copyright 2020 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
import getpass
import logging
import os
import queue
import typing as ty
from cliff.formatters import table
from openstackclient import command
from openstackclient.i18n import _
from openstackclient.identity import common as identity_common
LOG = logging.getLogger(__name__)
def ask_user_yesno(msg):
"""Ask user Y/N question
:param str msg: question text
:return bool: User choice
"""
while True:
answer = getpass.getpass('{} [{}]: '.format(msg, 'y/n'))
if answer in ('y', 'Y', 'yes'):
return True
elif answer in ('n', 'N', 'no'):
return False
class ProjectCleanup(command.Command):
_description = _("Clean resources associated with a project")
def get_parser(self, prog_name):
parser = super().get_parser(prog_name)
action_group = parser.add_mutually_exclusive_group()
action_group.add_argument(
'--dry-run',
action='store_true',
help=_("List a project's resources but do not delete them"),
)
action_group.add_argument(
'--auto-approve',
action='store_true',
help=_("Delete resources without asking for confirmation"),
)
project_group = parser.add_mutually_exclusive_group(required=True)
project_group.add_argument(
'--auth-project',
action='store_true',
help=_('Delete resources of the project used to authenticate'),
)
project_group.add_argument(
'--project',
metavar='<project>',
help=_('Project to clean (name or ID)'),
)
parser.add_argument(
'--created-before',
metavar='<YYYY-MM-DDTHH24:MI:SS>',
help=_('Only delete resources created before the given time'),
)
parser.add_argument(
'--updated-before',
metavar='<YYYY-MM-DDTHH24:MI:SS>',
help=_('Only delete resources updated before the given time'),
)
parser.add_argument(
'--skip-resource',
metavar='<resource>',
help='Skip cleanup of specific resource (repeat if necessary)',
action='append',
)
identity_common.add_project_domain_option_to_parser(parser)
return parser
def take_action(self, parsed_args):
connection = self.app.client_manager.sdk_connection
if parsed_args.auth_project:
# is we've got a project already configured, use the connection
# as-is
pass
elif parsed_args.project:
project = connection.identity.find_project(
name_or_id=parsed_args.project, ignore_missing=False
)
connection = connection.connect_as_project(project)
if connection:
status_queue: queue.Queue[ty.Any] = queue.Queue()
parsed_args.max_width = int(
os.environ.get('CLIFF_MAX_TERM_WIDTH', 0)
)
parsed_args.fit_width = bool(
int(os.environ.get('CLIFF_FIT_WIDTH', 0))
)
parsed_args.print_empty = False
table_fmt = table.TableFormatter()
self.log.info('Searching resources...')
filters = {}
if parsed_args.created_before:
filters['created_at'] = parsed_args.created_before
if parsed_args.updated_before:
filters['updated_at'] = parsed_args.updated_before
connection.project_cleanup(
dry_run=True,
status_queue=status_queue,
filters=filters,
skip_resources=parsed_args.skip_resource,
)
data = []
while not status_queue.empty():
resource = status_queue.get_nowait()
data.append(
(type(resource).__name__, resource.id, resource.name)
)
status_queue.task_done()
status_queue.join()
table_fmt.emit_list(
('Type', 'ID', 'Name'), data, self.app.stdout, parsed_args
)
if parsed_args.dry_run:
return
if not parsed_args.auto_approve:
if not ask_user_yesno(
_("These resources will be deleted. Are you sure")
):
return
self.log.warning(_('Deleting resources'))
connection.project_cleanup(
dry_run=False,
status_queue=status_queue,
filters=filters,
skip_resources=parsed_args.skip_resource,
)