blob: 5f421d698912510538a3eeef47a472b029307243 [file] [log] [blame]
David Patersonce781492014-09-18 01:07:01 -04001#!/usr/bin/env python
2#
3# Copyright 2014 Dell Inc.
4# Licensed under the Apache License, Version 2.0 (the "License"); you may
5# not use this file except in compliance with the License. You may obtain
6# a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
David Patersond6babc52014-10-14 00:11:56 -040012# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
David Patersonce781492014-09-18 01:07:01 -040013# License for the specific language governing permissions and limitations
14# under the License.
David Patersonce781492014-09-18 01:07:01 -040015
16"""
17Utility for cleaning up environment after Tempest run
18
19Runtime Arguments
20-----------------
21
Joe H. Rahme8bd59e02014-12-19 13:53:50 +020022**--init-saved-state**: Before you can execute cleanup you must initialize
23the saved state by running it with the **--init-saved-state** flag
David Patersonce781492014-09-18 01:07:01 -040024(creating ./saved_state.json), which protects your deployment from
25cleanup deleting objects you want to keep. Typically you would run
Joe H. Rahme8bd59e02014-12-19 13:53:50 +020026cleanup with **--init-saved-state** prior to a tempest run. If this is not
David Patersonce781492014-09-18 01:07:01 -040027the case saved_state.json must be edited, removing objects you want
28cleanup to delete.
29
Joe H. Rahme8bd59e02014-12-19 13:53:50 +020030**--dry-run**: Creates a report (dry_run.json) of the tenants that will be
David Patersonce781492014-09-18 01:07:01 -040031cleaned up (in the "_tenants_to_clean" array), and the global objects
32that will be removed (tenants, users, flavors and images). Once
Joe H. Rahme8bd59e02014-12-19 13:53:50 +020033cleanup is executed in normal mode, running it again with **--dry-run**
David Patersonce781492014-09-18 01:07:01 -040034should yield an empty report.
35
36**NOTE**: The _tenants_to_clean array in dry-run.json lists the
37tenants that cleanup will loop through and delete child objects, not
38delete the tenant itself. This may differ from the tenants array as you
David Patersond6babc52014-10-14 00:11:56 -040039can clean the tempest and alternate tempest tenants but by default,
40cleanup deletes the objects in the tempest and alternate tempest tenants
Joe H. Rahme8bd59e02014-12-19 13:53:50 +020041but does not delete those tenants unless the **--delete-tempest-conf-objects**
David Patersond6babc52014-10-14 00:11:56 -040042flag is used to force their deletion.
David Patersonce781492014-09-18 01:07:01 -040043
44**Normal mode**: running with no arguments, will query your deployment and
David Patersond6babc52014-10-14 00:11:56 -040045build a list of objects to delete after filtering out the objects found in
Joe H. Rahme8bd59e02014-12-19 13:53:50 +020046saved_state.json and based on the **--delete-tempest-conf-objects** flag.
David Patersonce781492014-09-18 01:07:01 -040047
48By default the tempest and alternate tempest users and tenants are not
49deleted and the admin user specified in tempest.conf is never deleted.
50
Joe H. Rahme8bd59e02014-12-19 13:53:50 +020051Please run with **--help** to see full list of options.
David Patersonce781492014-09-18 01:07:01 -040052"""
David Patersonce781492014-09-18 01:07:01 -040053import sys
54
David Paterson07661de2015-10-29 20:15:04 -070055from cliff import command
Doug Hellmann583ce2c2015-03-11 14:55:46 +000056from oslo_log import log as logging
Matthew Treinish21905512015-07-13 10:33:35 -040057from oslo_serialization import jsonutils as json
Doug Hellmann583ce2c2015-03-11 14:55:46 +000058
David Patersonce781492014-09-18 01:07:01 -040059from tempest import clients
60from tempest.cmd import cleanup_service
Andrea Frittoli (andreaf)290b3e12015-10-08 10:25:02 +010061from tempest.common import credentials_factory as credentials
David Patersonce781492014-09-18 01:07:01 -040062from tempest import config
David Patersonce781492014-09-18 01:07:01 -040063
64SAVED_STATE_JSON = "saved_state.json"
65DRY_RUN_JSON = "dry_run.json"
66LOG = logging.getLogger(__name__)
67CONF = config.CONF
68
69
David Paterson07661de2015-10-29 20:15:04 -070070class TempestCleanup(command.Command):
David Patersonce781492014-09-18 01:07:01 -040071
David Paterson07661de2015-10-29 20:15:04 -070072 def __init__(self, app, cmd):
73 super(TempestCleanup, self).__init__(app, cmd)
74
75 def take_action(self, parsed_args):
76 cleanup_service.init_conf()
77 self.options = parsed_args
Andrea Frittoli (andreaf)290b3e12015-10-08 10:25:02 +010078 self.admin_mgr = credentials.AdminManager()
David Patersonce781492014-09-18 01:07:01 -040079 self.dry_run_data = {}
80 self.json_data = {}
David Patersonce781492014-09-18 01:07:01 -040081
82 self.admin_id = ""
83 self.admin_role_id = ""
84 self.admin_tenant_id = ""
85 self._init_admin_ids()
86
87 self.admin_role_added = []
88
89 # available services
90 self.tenant_services = cleanup_service.get_tenant_cleanup_services()
91 self.global_services = cleanup_service.get_global_cleanup_services()
David Patersonce781492014-09-18 01:07:01 -040092
David Paterson07661de2015-10-29 20:15:04 -070093 if parsed_args.init_saved_state:
David Patersonce781492014-09-18 01:07:01 -040094 self._init_state()
95 return
96
97 self._load_json()
98 self._cleanup()
99
100 def _cleanup(self):
101 LOG.debug("Begin cleanup")
102 is_dry_run = self.options.dry_run
David Patersond6babc52014-10-14 00:11:56 -0400103 is_preserve = not self.options.delete_tempest_conf_objects
David Patersonce781492014-09-18 01:07:01 -0400104 is_save_state = False
105
106 if is_dry_run:
107 self.dry_run_data["_tenants_to_clean"] = {}
108 f = open(DRY_RUN_JSON, 'w+')
109
110 admin_mgr = self.admin_mgr
111 # Always cleanup tempest and alt tempest tenants unless
112 # they are in saved state json. Therefore is_preserve is False
113 kwargs = {'data': self.dry_run_data,
114 'is_dry_run': is_dry_run,
115 'saved_state_json': self.json_data,
116 'is_preserve': False,
117 'is_save_state': is_save_state}
118 tenant_service = cleanup_service.TenantService(admin_mgr, **kwargs)
119 tenants = tenant_service.list()
120 LOG.debug("Process %s tenants" % len(tenants))
121
122 # Loop through list of tenants and clean them up.
123 for tenant in tenants:
124 self._add_admin(tenant['id'])
125 self._clean_tenant(tenant)
126
127 kwargs = {'data': self.dry_run_data,
128 'is_dry_run': is_dry_run,
129 'saved_state_json': self.json_data,
130 'is_preserve': is_preserve,
131 'is_save_state': is_save_state}
132 for service in self.global_services:
133 svc = service(admin_mgr, **kwargs)
134 svc.run()
135
136 if is_dry_run:
137 f.write(json.dumps(self.dry_run_data, sort_keys=True,
138 indent=2, separators=(',', ': ')))
139 f.close()
140
141 self._remove_admin_user_roles()
142
143 def _remove_admin_user_roles(self):
144 tenant_ids = self.admin_role_added
145 LOG.debug("Removing admin user roles where needed for tenants: %s"
146 % tenant_ids)
147 for tenant_id in tenant_ids:
148 self._remove_admin_role(tenant_id)
149
150 def _clean_tenant(self, tenant):
151 LOG.debug("Cleaning tenant: %s " % tenant['name'])
152 is_dry_run = self.options.dry_run
153 dry_run_data = self.dry_run_data
David Patersond6babc52014-10-14 00:11:56 -0400154 is_preserve = not self.options.delete_tempest_conf_objects
David Patersonce781492014-09-18 01:07:01 -0400155 tenant_id = tenant['id']
156 tenant_name = tenant['name']
157 tenant_data = None
158 if is_dry_run:
159 tenant_data = dry_run_data["_tenants_to_clean"][tenant_id] = {}
160 tenant_data['name'] = tenant_name
161
David Paterson07661de2015-10-29 20:15:04 -0700162 kwargs = {"username": CONF.auth.admin_username,
163 "password": CONF.auth.admin_password,
David Patersonce781492014-09-18 01:07:01 -0400164 "tenant_name": tenant['name']}
Andrea Frittoli (andreaf)290b3e12015-10-08 10:25:02 +0100165 mgr = clients.Manager(credentials=credentials.get_credentials(
Andrea Frittoli878d5ab2015-01-30 13:22:50 +0000166 **kwargs))
David Patersonce781492014-09-18 01:07:01 -0400167 kwargs = {'data': tenant_data,
168 'is_dry_run': is_dry_run,
169 'saved_state_json': None,
170 'is_preserve': is_preserve,
171 'is_save_state': False,
172 'tenant_id': tenant_id}
173 for service in self.tenant_services:
174 svc = service(mgr, **kwargs)
175 svc.run()
176
177 def _init_admin_ids(self):
178 id_cl = self.admin_mgr.identity_client
179
David Paterson07661de2015-10-29 20:15:04 -0700180 tenant = id_cl.get_tenant_by_name(CONF.auth.admin_tenant_name)
David Patersonce781492014-09-18 01:07:01 -0400181 self.admin_tenant_id = tenant['id']
182
183 user = id_cl.get_user_by_username(self.admin_tenant_id,
David Paterson07661de2015-10-29 20:15:04 -0700184 CONF.auth.admin_username)
David Patersonce781492014-09-18 01:07:01 -0400185 self.admin_id = user['id']
186
David Paterson07661de2015-10-29 20:15:04 -0700187 roles = id_cl.list_roles()['roles']
David Patersonce781492014-09-18 01:07:01 -0400188 for role in roles:
189 if role['name'] == CONF.identity.admin_role:
190 self.admin_role_id = role['id']
191 break
192
David Paterson07661de2015-10-29 20:15:04 -0700193 def get_parser(self, prog_name):
194 parser = super(TempestCleanup, self).get_parser(prog_name)
David Patersonce781492014-09-18 01:07:01 -0400195 parser.add_argument('--init-saved-state', action="store_true",
196 dest='init_saved_state', default=False,
197 help="Creates JSON file: " + SAVED_STATE_JSON +
198 ", representing the current state of your "
David Patersond6babc52014-10-14 00:11:56 -0400199 "deployment, specifically object types "
200 "tempest creates and destroys during a run. "
David Patersonce781492014-09-18 01:07:01 -0400201 "You must run with this flag prior to "
David Patersond6babc52014-10-14 00:11:56 -0400202 "executing cleanup in normal mode, which is with "
203 "no arguments.")
David Patersonce781492014-09-18 01:07:01 -0400204 parser.add_argument('--delete-tempest-conf-objects',
David Patersond6babc52014-10-14 00:11:56 -0400205 action="store_true",
206 dest='delete_tempest_conf_objects',
David Patersonce781492014-09-18 01:07:01 -0400207 default=False,
David Patersond6babc52014-10-14 00:11:56 -0400208 help="Force deletion of the tempest and "
David Patersonce781492014-09-18 01:07:01 -0400209 "alternate tempest users and tenants.")
210 parser.add_argument('--dry-run', action="store_true",
211 dest='dry_run', default=False,
212 help="Generate JSON file:" + DRY_RUN_JSON +
213 ", that reports the objects that would have "
214 "been deleted had a full cleanup been run.")
David Paterson07661de2015-10-29 20:15:04 -0700215 return parser
David Patersonce781492014-09-18 01:07:01 -0400216
David Paterson07661de2015-10-29 20:15:04 -0700217 def get_description(self):
218 return 'Cleanup after tempest run'
David Patersonce781492014-09-18 01:07:01 -0400219
220 def _add_admin(self, tenant_id):
221 id_cl = self.admin_mgr.identity_client
222 needs_role = True
David Paterson07661de2015-10-29 20:15:04 -0700223 roles = id_cl.list_user_roles(tenant_id, self.admin_id)['roles']
David Patersonce781492014-09-18 01:07:01 -0400224 for role in roles:
225 if role['id'] == self.admin_role_id:
226 needs_role = False
227 LOG.debug("User already had admin privilege for this tenant")
228 if needs_role:
Tingting Bao2b513342015-02-15 22:54:55 -0800229 LOG.debug("Adding admin privilege for : %s" % tenant_id)
David Patersonce781492014-09-18 01:07:01 -0400230 id_cl.assign_user_role(tenant_id, self.admin_id,
231 self.admin_role_id)
232 self.admin_role_added.append(tenant_id)
233
234 def _remove_admin_role(self, tenant_id):
235 LOG.debug("Remove admin user role for tenant: %s" % tenant_id)
236 # Must initialize AdminManager for each user role
237 # Otherwise authentication exception is thrown, weird
Andrea Frittoli (andreaf)290b3e12015-10-08 10:25:02 +0100238 id_cl = credentials.AdminManager().identity_client
David Patersonce781492014-09-18 01:07:01 -0400239 if (self._tenant_exists(tenant_id)):
240 try:
241 id_cl.remove_user_role(tenant_id, self.admin_id,
242 self.admin_role_id)
243 except Exception as ex:
244 LOG.exception("Failed removing role from tenant which still"
245 "exists, exception: %s" % ex)
246
247 def _tenant_exists(self, tenant_id):
248 id_cl = self.admin_mgr.identity_client
249 try:
250 t = id_cl.get_tenant(tenant_id)
251 LOG.debug("Tenant is: %s" % str(t))
252 return True
253 except Exception as ex:
254 LOG.debug("Tenant no longer exists? %s" % ex)
255 return False
256
257 def _init_state(self):
258 LOG.debug("Initializing saved state.")
259 data = {}
260 admin_mgr = self.admin_mgr
261 kwargs = {'data': data,
262 'is_dry_run': False,
263 'saved_state_json': data,
264 'is_preserve': False,
265 'is_save_state': True}
266 for service in self.global_services:
267 svc = service(admin_mgr, **kwargs)
268 svc.run()
269
270 f = open(SAVED_STATE_JSON, 'w+')
271 f.write(json.dumps(data,
272 sort_keys=True, indent=2, separators=(',', ': ')))
273 f.close()
274
275 def _load_json(self):
276 try:
277 json_file = open(SAVED_STATE_JSON)
278 self.json_data = json.load(json_file)
279 json_file.close()
280 except IOError as ex:
281 LOG.exception("Failed loading saved state, please be sure you"
282 " have first run cleanup with --init-saved-state "
283 "flag prior to running tempest. Exception: %s" % ex)
284 sys.exit(ex)
285 except Exception as ex:
286 LOG.exception("Exception parsing saved state json : %s" % ex)
287 sys.exit(ex)