blob: af86fe34c451d2acdd590aaf3d368c87b06092aa [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
Marc Kodererf3397942015-12-21 11:17:09 +010054import traceback
David Patersonce781492014-09-18 01:07:01 -040055
David Paterson07661de2015-10-29 20:15:04 -070056from cliff import command
Doug Hellmann583ce2c2015-03-11 14:55:46 +000057from oslo_log import log as logging
Matthew Treinish21905512015-07-13 10:33:35 -040058from oslo_serialization import jsonutils as json
Doug Hellmann583ce2c2015-03-11 14:55:46 +000059
David Patersonce781492014-09-18 01:07:01 -040060from tempest import clients
61from tempest.cmd import cleanup_service
Andrea Frittoli (andreaf)290b3e12015-10-08 10:25:02 +010062from tempest.common import credentials_factory as credentials
Ken'ichi Ohmichi6ea3f982015-11-09 12:41:13 +000063from tempest.common import identity
David Patersonce781492014-09-18 01:07:01 -040064from tempest import config
David Patersonce781492014-09-18 01:07:01 -040065
66SAVED_STATE_JSON = "saved_state.json"
67DRY_RUN_JSON = "dry_run.json"
68LOG = logging.getLogger(__name__)
69CONF = config.CONF
70
71
David Paterson07661de2015-10-29 20:15:04 -070072class TempestCleanup(command.Command):
David Patersonce781492014-09-18 01:07:01 -040073
David Paterson07661de2015-10-29 20:15:04 -070074 def take_action(self, parsed_args):
Marc Kodererf3397942015-12-21 11:17:09 +010075 try:
76 self.init(parsed_args)
Ghanshyam41711d32016-02-17 17:11:22 +090077 if not parsed_args.init_saved_state:
78 self._cleanup()
Marc Kodererf3397942015-12-21 11:17:09 +010079 except Exception:
80 LOG.exception("Failure during cleanup")
81 traceback.print_exc()
82 raise
Marc Kodererf3397942015-12-21 11:17:09 +010083
84 def init(self, parsed_args):
David Paterson07661de2015-10-29 20:15:04 -070085 cleanup_service.init_conf()
86 self.options = parsed_args
Andrea Frittoli (andreaf)290b3e12015-10-08 10:25:02 +010087 self.admin_mgr = credentials.AdminManager()
David Patersonce781492014-09-18 01:07:01 -040088 self.dry_run_data = {}
89 self.json_data = {}
David Patersonce781492014-09-18 01:07:01 -040090
91 self.admin_id = ""
92 self.admin_role_id = ""
93 self.admin_tenant_id = ""
94 self._init_admin_ids()
95
96 self.admin_role_added = []
97
98 # available services
99 self.tenant_services = cleanup_service.get_tenant_cleanup_services()
100 self.global_services = cleanup_service.get_global_cleanup_services()
David Patersonce781492014-09-18 01:07:01 -0400101
David Paterson07661de2015-10-29 20:15:04 -0700102 if parsed_args.init_saved_state:
David Patersonce781492014-09-18 01:07:01 -0400103 self._init_state()
104 return
105
106 self._load_json()
David Patersonce781492014-09-18 01:07:01 -0400107
108 def _cleanup(self):
yuyafeie2dbc1f2016-07-06 16:09:19 +0800109 print("Begin cleanup")
David Patersonce781492014-09-18 01:07:01 -0400110 is_dry_run = self.options.dry_run
David Patersond6babc52014-10-14 00:11:56 -0400111 is_preserve = not self.options.delete_tempest_conf_objects
David Patersonce781492014-09-18 01:07:01 -0400112 is_save_state = False
113
114 if is_dry_run:
115 self.dry_run_data["_tenants_to_clean"] = {}
David Patersonce781492014-09-18 01:07:01 -0400116
117 admin_mgr = self.admin_mgr
118 # Always cleanup tempest and alt tempest tenants unless
119 # they are in saved state json. Therefore is_preserve is False
120 kwargs = {'data': self.dry_run_data,
121 'is_dry_run': is_dry_run,
122 'saved_state_json': self.json_data,
123 'is_preserve': False,
124 'is_save_state': is_save_state}
125 tenant_service = cleanup_service.TenantService(admin_mgr, **kwargs)
126 tenants = tenant_service.list()
yuyafeie2dbc1f2016-07-06 16:09:19 +0800127 print("Process %s tenants" % len(tenants))
David Patersonce781492014-09-18 01:07:01 -0400128
129 # Loop through list of tenants and clean them up.
130 for tenant in tenants:
131 self._add_admin(tenant['id'])
132 self._clean_tenant(tenant)
133
134 kwargs = {'data': self.dry_run_data,
135 'is_dry_run': is_dry_run,
136 'saved_state_json': self.json_data,
137 'is_preserve': is_preserve,
138 'is_save_state': is_save_state}
139 for service in self.global_services:
140 svc = service(admin_mgr, **kwargs)
141 svc.run()
142
143 if is_dry_run:
zhang.leia4b1cef2016-03-01 10:50:01 +0800144 with open(DRY_RUN_JSON, 'w+') as f:
145 f.write(json.dumps(self.dry_run_data, sort_keys=True,
146 indent=2, separators=(',', ': ')))
David Patersonce781492014-09-18 01:07:01 -0400147
148 self._remove_admin_user_roles()
149
150 def _remove_admin_user_roles(self):
151 tenant_ids = self.admin_role_added
152 LOG.debug("Removing admin user roles where needed for tenants: %s"
153 % tenant_ids)
154 for tenant_id in tenant_ids:
155 self._remove_admin_role(tenant_id)
156
157 def _clean_tenant(self, tenant):
yuyafeie2dbc1f2016-07-06 16:09:19 +0800158 print("Cleaning tenant: %s " % tenant['name'])
David Patersonce781492014-09-18 01:07:01 -0400159 is_dry_run = self.options.dry_run
160 dry_run_data = self.dry_run_data
David Patersond6babc52014-10-14 00:11:56 -0400161 is_preserve = not self.options.delete_tempest_conf_objects
David Patersonce781492014-09-18 01:07:01 -0400162 tenant_id = tenant['id']
163 tenant_name = tenant['name']
164 tenant_data = None
165 if is_dry_run:
166 tenant_data = dry_run_data["_tenants_to_clean"][tenant_id] = {}
167 tenant_data['name'] = tenant_name
168
David Paterson07661de2015-10-29 20:15:04 -0700169 kwargs = {"username": CONF.auth.admin_username,
170 "password": CONF.auth.admin_password,
David Patersonce781492014-09-18 01:07:01 -0400171 "tenant_name": tenant['name']}
Andrea Frittoli (andreaf)290b3e12015-10-08 10:25:02 +0100172 mgr = clients.Manager(credentials=credentials.get_credentials(
Andrea Frittoli878d5ab2015-01-30 13:22:50 +0000173 **kwargs))
David Patersonce781492014-09-18 01:07:01 -0400174 kwargs = {'data': tenant_data,
175 'is_dry_run': is_dry_run,
176 'saved_state_json': None,
177 'is_preserve': is_preserve,
178 'is_save_state': False,
179 'tenant_id': tenant_id}
180 for service in self.tenant_services:
181 svc = service(mgr, **kwargs)
182 svc.run()
183
184 def _init_admin_ids(self):
Daniel Melladob83ea562015-12-18 09:12:49 +0000185 tn_cl = self.admin_mgr.tenants_client
Daniel Mellado6b16b922015-12-07 12:43:08 +0000186 rl_cl = self.admin_mgr.roles_client
David Patersonce781492014-09-18 01:07:01 -0400187
Daniel Melladob83ea562015-12-18 09:12:49 +0000188 tenant = identity.get_tenant_by_name(tn_cl,
Daniel Melladod4d0b932016-04-08 08:57:29 +0000189 CONF.auth.admin_project_name)
David Patersonce781492014-09-18 01:07:01 -0400190 self.admin_tenant_id = tenant['id']
191
Daniel Melladob83ea562015-12-18 09:12:49 +0000192 user = identity.get_user_by_username(tn_cl, self.admin_tenant_id,
Ken'ichi Ohmichid9fed312015-11-09 13:05:32 +0000193 CONF.auth.admin_username)
David Patersonce781492014-09-18 01:07:01 -0400194 self.admin_id = user['id']
195
Daniel Mellado6b16b922015-12-07 12:43:08 +0000196 roles = rl_cl.list_roles()['roles']
David Patersonce781492014-09-18 01:07:01 -0400197 for role in roles:
198 if role['name'] == CONF.identity.admin_role:
199 self.admin_role_id = role['id']
200 break
201
David Paterson07661de2015-10-29 20:15:04 -0700202 def get_parser(self, prog_name):
203 parser = super(TempestCleanup, self).get_parser(prog_name)
David Patersonce781492014-09-18 01:07:01 -0400204 parser.add_argument('--init-saved-state', action="store_true",
205 dest='init_saved_state', default=False,
206 help="Creates JSON file: " + SAVED_STATE_JSON +
207 ", representing the current state of your "
David Patersond6babc52014-10-14 00:11:56 -0400208 "deployment, specifically object types "
209 "tempest creates and destroys during a run. "
David Patersonce781492014-09-18 01:07:01 -0400210 "You must run with this flag prior to "
David Patersond6babc52014-10-14 00:11:56 -0400211 "executing cleanup in normal mode, which is with "
212 "no arguments.")
David Patersonce781492014-09-18 01:07:01 -0400213 parser.add_argument('--delete-tempest-conf-objects',
David Patersond6babc52014-10-14 00:11:56 -0400214 action="store_true",
215 dest='delete_tempest_conf_objects',
David Patersonce781492014-09-18 01:07:01 -0400216 default=False,
David Patersond6babc52014-10-14 00:11:56 -0400217 help="Force deletion of the tempest and "
David Patersonce781492014-09-18 01:07:01 -0400218 "alternate tempest users and tenants.")
219 parser.add_argument('--dry-run', action="store_true",
220 dest='dry_run', default=False,
221 help="Generate JSON file:" + DRY_RUN_JSON +
222 ", that reports the objects that would have "
223 "been deleted had a full cleanup been run.")
David Paterson07661de2015-10-29 20:15:04 -0700224 return parser
David Patersonce781492014-09-18 01:07:01 -0400225
David Paterson07661de2015-10-29 20:15:04 -0700226 def get_description(self):
227 return 'Cleanup after tempest run'
David Patersonce781492014-09-18 01:07:01 -0400228
229 def _add_admin(self, tenant_id):
Daniel Mellado6b16b922015-12-07 12:43:08 +0000230 rl_cl = self.admin_mgr.roles_client
David Patersonce781492014-09-18 01:07:01 -0400231 needs_role = True
ghanshyam50894fc2016-06-17 13:20:25 +0900232 roles = rl_cl.list_user_roles_on_project(tenant_id,
233 self.admin_id)['roles']
David Patersonce781492014-09-18 01:07:01 -0400234 for role in roles:
235 if role['id'] == self.admin_role_id:
236 needs_role = False
237 LOG.debug("User already had admin privilege for this tenant")
238 if needs_role:
Tingting Bao2b513342015-02-15 22:54:55 -0800239 LOG.debug("Adding admin privilege for : %s" % tenant_id)
ghanshyam50894fc2016-06-17 13:20:25 +0900240 rl_cl.create_user_role_on_project(tenant_id, self.admin_id,
241 self.admin_role_id)
David Patersonce781492014-09-18 01:07:01 -0400242 self.admin_role_added.append(tenant_id)
243
244 def _remove_admin_role(self, tenant_id):
245 LOG.debug("Remove admin user role for tenant: %s" % tenant_id)
246 # Must initialize AdminManager for each user role
247 # Otherwise authentication exception is thrown, weird
Andrea Frittoli (andreaf)290b3e12015-10-08 10:25:02 +0100248 id_cl = credentials.AdminManager().identity_client
David Patersonce781492014-09-18 01:07:01 -0400249 if (self._tenant_exists(tenant_id)):
250 try:
ghanshyam50894fc2016-06-17 13:20:25 +0900251 id_cl.delete_role_from_user_on_project(tenant_id,
252 self.admin_id,
253 self.admin_role_id)
David Patersonce781492014-09-18 01:07:01 -0400254 except Exception as ex:
255 LOG.exception("Failed removing role from tenant which still"
256 "exists, exception: %s" % ex)
257
258 def _tenant_exists(self, tenant_id):
Daniel Melladob83ea562015-12-18 09:12:49 +0000259 tn_cl = self.admin_mgr.tenants_client
David Patersonce781492014-09-18 01:07:01 -0400260 try:
Daniel Melladob83ea562015-12-18 09:12:49 +0000261 t = tn_cl.show_tenant(tenant_id)
David Patersonce781492014-09-18 01:07:01 -0400262 LOG.debug("Tenant is: %s" % str(t))
263 return True
264 except Exception as ex:
265 LOG.debug("Tenant no longer exists? %s" % ex)
266 return False
267
268 def _init_state(self):
yuyafeie2dbc1f2016-07-06 16:09:19 +0800269 print("Initializing saved state.")
David Patersonce781492014-09-18 01:07:01 -0400270 data = {}
271 admin_mgr = self.admin_mgr
272 kwargs = {'data': data,
273 'is_dry_run': False,
274 'saved_state_json': data,
275 'is_preserve': False,
276 'is_save_state': True}
277 for service in self.global_services:
278 svc = service(admin_mgr, **kwargs)
279 svc.run()
280
zhang.leia4b1cef2016-03-01 10:50:01 +0800281 with open(SAVED_STATE_JSON, 'w+') as f:
282 f.write(json.dumps(data,
283 sort_keys=True, indent=2, separators=(',', ': ')))
David Patersonce781492014-09-18 01:07:01 -0400284
285 def _load_json(self):
286 try:
zhang.leia4b1cef2016-03-01 10:50:01 +0800287 with open(SAVED_STATE_JSON) as json_file:
288 self.json_data = json.load(json_file)
289
David Patersonce781492014-09-18 01:07:01 -0400290 except IOError as ex:
291 LOG.exception("Failed loading saved state, please be sure you"
292 " have first run cleanup with --init-saved-state "
293 "flag prior to running tempest. Exception: %s" % ex)
294 sys.exit(ex)
295 except Exception as ex:
296 LOG.exception("Exception parsing saved state json : %s" % ex)
297 sys.exit(ex)