blob: c8a8159f0b9445e9c88251865029a60c6ee757c1 [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 __init__(self, app, cmd):
75 super(TempestCleanup, self).__init__(app, cmd)
76
77 def take_action(self, parsed_args):
Marc Kodererf3397942015-12-21 11:17:09 +010078 try:
79 self.init(parsed_args)
80 self._cleanup()
81 except Exception:
82 LOG.exception("Failure during cleanup")
83 traceback.print_exc()
84 raise
85 return 0
86
87 def init(self, parsed_args):
David Paterson07661de2015-10-29 20:15:04 -070088 cleanup_service.init_conf()
89 self.options = parsed_args
Andrea Frittoli (andreaf)290b3e12015-10-08 10:25:02 +010090 self.admin_mgr = credentials.AdminManager()
David Patersonce781492014-09-18 01:07:01 -040091 self.dry_run_data = {}
92 self.json_data = {}
David Patersonce781492014-09-18 01:07:01 -040093
94 self.admin_id = ""
95 self.admin_role_id = ""
96 self.admin_tenant_id = ""
97 self._init_admin_ids()
98
99 self.admin_role_added = []
100
101 # available services
102 self.tenant_services = cleanup_service.get_tenant_cleanup_services()
103 self.global_services = cleanup_service.get_global_cleanup_services()
David Patersonce781492014-09-18 01:07:01 -0400104
David Paterson07661de2015-10-29 20:15:04 -0700105 if parsed_args.init_saved_state:
David Patersonce781492014-09-18 01:07:01 -0400106 self._init_state()
107 return
108
109 self._load_json()
David Patersonce781492014-09-18 01:07:01 -0400110
111 def _cleanup(self):
Marc Kodererf3397942015-12-21 11:17:09 +0100112 print ("Begin cleanup")
David Patersonce781492014-09-18 01:07:01 -0400113 is_dry_run = self.options.dry_run
David Patersond6babc52014-10-14 00:11:56 -0400114 is_preserve = not self.options.delete_tempest_conf_objects
David Patersonce781492014-09-18 01:07:01 -0400115 is_save_state = False
116
117 if is_dry_run:
118 self.dry_run_data["_tenants_to_clean"] = {}
119 f = open(DRY_RUN_JSON, 'w+')
120
121 admin_mgr = self.admin_mgr
122 # Always cleanup tempest and alt tempest tenants unless
123 # they are in saved state json. Therefore is_preserve is False
124 kwargs = {'data': self.dry_run_data,
125 'is_dry_run': is_dry_run,
126 'saved_state_json': self.json_data,
127 'is_preserve': False,
128 'is_save_state': is_save_state}
129 tenant_service = cleanup_service.TenantService(admin_mgr, **kwargs)
130 tenants = tenant_service.list()
Marc Kodererf3397942015-12-21 11:17:09 +0100131 print ("Process %s tenants" % len(tenants))
David Patersonce781492014-09-18 01:07:01 -0400132
133 # Loop through list of tenants and clean them up.
134 for tenant in tenants:
135 self._add_admin(tenant['id'])
136 self._clean_tenant(tenant)
137
138 kwargs = {'data': self.dry_run_data,
139 'is_dry_run': is_dry_run,
140 'saved_state_json': self.json_data,
141 'is_preserve': is_preserve,
142 'is_save_state': is_save_state}
143 for service in self.global_services:
144 svc = service(admin_mgr, **kwargs)
145 svc.run()
146
147 if is_dry_run:
148 f.write(json.dumps(self.dry_run_data, sort_keys=True,
149 indent=2, separators=(',', ': ')))
150 f.close()
151
152 self._remove_admin_user_roles()
153
154 def _remove_admin_user_roles(self):
155 tenant_ids = self.admin_role_added
156 LOG.debug("Removing admin user roles where needed for tenants: %s"
157 % tenant_ids)
158 for tenant_id in tenant_ids:
159 self._remove_admin_role(tenant_id)
160
161 def _clean_tenant(self, tenant):
Marc Kodererf3397942015-12-21 11:17:09 +0100162 print ("Cleaning tenant: %s " % tenant['name'])
David Patersonce781492014-09-18 01:07:01 -0400163 is_dry_run = self.options.dry_run
164 dry_run_data = self.dry_run_data
David Patersond6babc52014-10-14 00:11:56 -0400165 is_preserve = not self.options.delete_tempest_conf_objects
David Patersonce781492014-09-18 01:07:01 -0400166 tenant_id = tenant['id']
167 tenant_name = tenant['name']
168 tenant_data = None
169 if is_dry_run:
170 tenant_data = dry_run_data["_tenants_to_clean"][tenant_id] = {}
171 tenant_data['name'] = tenant_name
172
David Paterson07661de2015-10-29 20:15:04 -0700173 kwargs = {"username": CONF.auth.admin_username,
174 "password": CONF.auth.admin_password,
David Patersonce781492014-09-18 01:07:01 -0400175 "tenant_name": tenant['name']}
Andrea Frittoli (andreaf)290b3e12015-10-08 10:25:02 +0100176 mgr = clients.Manager(credentials=credentials.get_credentials(
Andrea Frittoli878d5ab2015-01-30 13:22:50 +0000177 **kwargs))
David Patersonce781492014-09-18 01:07:01 -0400178 kwargs = {'data': tenant_data,
179 'is_dry_run': is_dry_run,
180 'saved_state_json': None,
181 'is_preserve': is_preserve,
182 'is_save_state': False,
183 'tenant_id': tenant_id}
184 for service in self.tenant_services:
185 svc = service(mgr, **kwargs)
186 svc.run()
187
188 def _init_admin_ids(self):
Daniel Melladob83ea562015-12-18 09:12:49 +0000189 tn_cl = self.admin_mgr.tenants_client
Daniel Mellado6b16b922015-12-07 12:43:08 +0000190 rl_cl = self.admin_mgr.roles_client
David Patersonce781492014-09-18 01:07:01 -0400191
Daniel Melladob83ea562015-12-18 09:12:49 +0000192 tenant = identity.get_tenant_by_name(tn_cl,
Ken'ichi Ohmichi6ea3f982015-11-09 12:41:13 +0000193 CONF.auth.admin_tenant_name)
David Patersonce781492014-09-18 01:07:01 -0400194 self.admin_tenant_id = tenant['id']
195
Daniel Melladob83ea562015-12-18 09:12:49 +0000196 user = identity.get_user_by_username(tn_cl, self.admin_tenant_id,
Ken'ichi Ohmichid9fed312015-11-09 13:05:32 +0000197 CONF.auth.admin_username)
David Patersonce781492014-09-18 01:07:01 -0400198 self.admin_id = user['id']
199
Daniel Mellado6b16b922015-12-07 12:43:08 +0000200 roles = rl_cl.list_roles()['roles']
David Patersonce781492014-09-18 01:07:01 -0400201 for role in roles:
202 if role['name'] == CONF.identity.admin_role:
203 self.admin_role_id = role['id']
204 break
205
David Paterson07661de2015-10-29 20:15:04 -0700206 def get_parser(self, prog_name):
207 parser = super(TempestCleanup, self).get_parser(prog_name)
David Patersonce781492014-09-18 01:07:01 -0400208 parser.add_argument('--init-saved-state', action="store_true",
209 dest='init_saved_state', default=False,
210 help="Creates JSON file: " + SAVED_STATE_JSON +
211 ", representing the current state of your "
David Patersond6babc52014-10-14 00:11:56 -0400212 "deployment, specifically object types "
213 "tempest creates and destroys during a run. "
David Patersonce781492014-09-18 01:07:01 -0400214 "You must run with this flag prior to "
David Patersond6babc52014-10-14 00:11:56 -0400215 "executing cleanup in normal mode, which is with "
216 "no arguments.")
David Patersonce781492014-09-18 01:07:01 -0400217 parser.add_argument('--delete-tempest-conf-objects',
David Patersond6babc52014-10-14 00:11:56 -0400218 action="store_true",
219 dest='delete_tempest_conf_objects',
David Patersonce781492014-09-18 01:07:01 -0400220 default=False,
David Patersond6babc52014-10-14 00:11:56 -0400221 help="Force deletion of the tempest and "
David Patersonce781492014-09-18 01:07:01 -0400222 "alternate tempest users and tenants.")
223 parser.add_argument('--dry-run', action="store_true",
224 dest='dry_run', default=False,
225 help="Generate JSON file:" + DRY_RUN_JSON +
226 ", that reports the objects that would have "
227 "been deleted had a full cleanup been run.")
David Paterson07661de2015-10-29 20:15:04 -0700228 return parser
David Patersonce781492014-09-18 01:07:01 -0400229
David Paterson07661de2015-10-29 20:15:04 -0700230 def get_description(self):
231 return 'Cleanup after tempest run'
David Patersonce781492014-09-18 01:07:01 -0400232
233 def _add_admin(self, tenant_id):
Daniel Mellado6b16b922015-12-07 12:43:08 +0000234 rl_cl = self.admin_mgr.roles_client
David Patersonce781492014-09-18 01:07:01 -0400235 needs_role = True
Daniel Mellado6b16b922015-12-07 12:43:08 +0000236 roles = rl_cl.list_user_roles(tenant_id, self.admin_id)['roles']
David Patersonce781492014-09-18 01:07:01 -0400237 for role in roles:
238 if role['id'] == self.admin_role_id:
239 needs_role = False
240 LOG.debug("User already had admin privilege for this tenant")
241 if needs_role:
Tingting Bao2b513342015-02-15 22:54:55 -0800242 LOG.debug("Adding admin privilege for : %s" % tenant_id)
Ghanshyam9d146762016-02-17 13:37:19 +0900243 rl_cl.assign_user_role(tenant_id, self.admin_id,
David Patersonce781492014-09-18 01:07:01 -0400244 self.admin_role_id)
245 self.admin_role_added.append(tenant_id)
246
247 def _remove_admin_role(self, tenant_id):
248 LOG.debug("Remove admin user role for tenant: %s" % tenant_id)
249 # Must initialize AdminManager for each user role
250 # Otherwise authentication exception is thrown, weird
Andrea Frittoli (andreaf)290b3e12015-10-08 10:25:02 +0100251 id_cl = credentials.AdminManager().identity_client
David Patersonce781492014-09-18 01:07:01 -0400252 if (self._tenant_exists(tenant_id)):
253 try:
Ken'ichi Ohmichib8461cb2015-11-20 08:10:51 +0000254 id_cl.delete_user_role(tenant_id, self.admin_id,
David Patersonce781492014-09-18 01:07:01 -0400255 self.admin_role_id)
256 except Exception as ex:
257 LOG.exception("Failed removing role from tenant which still"
258 "exists, exception: %s" % ex)
259
260 def _tenant_exists(self, tenant_id):
Daniel Melladob83ea562015-12-18 09:12:49 +0000261 tn_cl = self.admin_mgr.tenants_client
David Patersonce781492014-09-18 01:07:01 -0400262 try:
Daniel Melladob83ea562015-12-18 09:12:49 +0000263 t = tn_cl.show_tenant(tenant_id)
David Patersonce781492014-09-18 01:07:01 -0400264 LOG.debug("Tenant is: %s" % str(t))
265 return True
266 except Exception as ex:
267 LOG.debug("Tenant no longer exists? %s" % ex)
268 return False
269
270 def _init_state(self):
Marc Kodererf3397942015-12-21 11:17:09 +0100271 print ("Initializing saved state.")
David Patersonce781492014-09-18 01:07:01 -0400272 data = {}
273 admin_mgr = self.admin_mgr
274 kwargs = {'data': data,
275 'is_dry_run': False,
276 'saved_state_json': data,
277 'is_preserve': False,
278 'is_save_state': True}
279 for service in self.global_services:
280 svc = service(admin_mgr, **kwargs)
281 svc.run()
282
283 f = open(SAVED_STATE_JSON, 'w+')
284 f.write(json.dumps(data,
285 sort_keys=True, indent=2, separators=(',', ': ')))
286 f.close()
287
288 def _load_json(self):
289 try:
290 json_file = open(SAVED_STATE_JSON)
291 self.json_data = json.load(json_file)
292 json_file.close()
293 except IOError as ex:
294 LOG.exception("Failed loading saved state, please be sure you"
295 " have first run cleanup with --init-saved-state "
296 "flag prior to running tempest. Exception: %s" % ex)
297 sys.exit(ex)
298 except Exception as ex:
299 LOG.exception("Exception parsing saved state json : %s" % ex)
300 sys.exit(ex)