summaryrefslogtreecommitdiffstats
path: root/kernel/drivers/atm/suni.c
blob: 02159345566c3d018d01d50f8309fc4bd680a1d1 (plain)
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
/*
 * drivers/atm/suni.c - S/UNI PHY driver
 *
 * Supports the following:
 * 	PMC PM5346 S/UNI LITE
 * 	PMC PM5350 S/UNI 155 ULTRA
 * 	PMC PM5355 S/UNI 622
 */
 
/* Written 1995-2000 by Werner Almesberger, EPFL LRC/ICA */

#include <linux/module.h>
#include <linux/jiffies.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/errno.h>
#include <linux/atmdev.h>
#include <linux/sonet.h>
#include <linux/delay.h>
#include <linux/timer.h>
#include <linux/init.h>
#include <linux/capability.h>
#include <linux/atm_suni.h>
#include <linux/slab.h>
#include <asm/param.h>
#include <asm/uaccess.h>
#include <linux/atomic.h>

#include "suni.h"


#if 0
#define DPRINTK(format,args...) printk(KERN_DEBUG format,##args)
#else
#define DPRINTK(format,args...)
#endif

#define PRIV(dev) ((struct suni_priv *) dev->phy_data)

#define PUT(val,reg) dev->ops->phy_put(dev,val,SUNI_##reg)
#define GET(reg) dev->ops->phy_get(dev,SUNI_##reg)
#define REG_CHANGE(mask,shift,value,reg) \
  PUT((GET(reg) & ~(mask)) | ((value) << (shift)),reg)


static struct timer_list poll_timer;
static struct suni_priv *sunis = NULL;
static DEFINE_SPINLOCK(sunis_lock);


#define ADD_LIMITED(s,v) \
    atomic_add((v),&stats->s); \
    if (atomic_read(&stats->s) < 0) atomic_set(&stats->s,INT_MAX);


static void suni_hz(unsigned long from_timer)
{
	struct suni_priv *walk;
	struct atm_dev *dev;
	struct k_sonet_stats *stats;

	for (walk = sunis; walk; walk = walk->next) {
		dev = walk->dev;
		stats = &walk->sonet_stats;
		PUT(0,MRI); /* latch counters */
		udelay(1);
		ADD_LIMITED(section_bip,(GET(RSOP_SBL) & 0xff) |
		    ((GET(RSOP_SBM) & 0xff) << 8));
		ADD_LIMITED(line_bip,(GET(RLOP_LBL) & 0xff) |
		    ((GET(RLOP_LB) & 0xff) << 8) |
		    ((GET(RLOP_LBM) & 0xf) << 16));
		ADD_LIMITED(path_bip,(GET(RPOP_PBL) & 0xff) |
		    ((GET(RPOP_PBM) & 0xff) << 8));
		ADD_LIMITED(line_febe,(GET(RLOP_LFL) & 0xff) |
		    ((GET(RLOP_LF) & 0xff) << 8) |
		    ((GET(RLOP_LFM) & 0xf) << 16));
		ADD_LIMITED(path_febe,(GET(RPOP_PFL) & 0xff) |
		    ((GET(RPOP_PFM) & 0xff) << 8));
		ADD_LIMITED(corr_hcs,GET(RACP_CHEC) & 0xff);
		ADD_LIMITED(uncorr_hcs,GET(RACP_UHEC) & 0xff);
		ADD_LIMITED(rx_cells,(GET(RACP_RCCL) & 0xff) |
		    ((GET(RACP_RCC) & 0xff) << 8) |
		    ((GET(RACP_RCCM) & 7) << 16));
		ADD_LIMITED(tx_cells,(GET(TACP_TCCL) & 0xff) |
		    ((GET(TACP_TCC) & 0xff) << 8) |
		    ((GET(TACP_TCCM) & 7) << 16));
	}
	if (from_timer) mod_timer(&poll_timer,jiffies+HZ);
}


#undef ADD_LIMITED


static int fetch_stats(struct atm_dev *dev,struct sonet_stats __user *arg,int zero)
{
	struct sonet_stats tmp;
	int error = 0;

	sonet_copy_stats(&PRIV(dev)->sonet_stats,&tmp);
	if (arg) error = copy_to_user(arg,&tmp,sizeof(tmp));
	if (zero && !error) sonet_subtract_stats(&PRIV(dev)->sonet_stats,&tmp);
	return error ? -EFAULT : 0;
}


#define HANDLE_FLAG(flag,reg,bit) \
  if (todo & flag) { \
    if (set) PUT(GET(reg) | bit,reg); \
    else PUT(GET(reg) & ~bit,reg); \
    todo &= ~flag; \
  }


static int change_diag(struct atm_dev *dev,void __user *arg,int set)
{
	int todo;

	if (get_user(todo,(int __user *)arg)) return -EFAULT;
	HANDLE_FLAG(SONET_INS_SBIP,TSOP_DIAG,SUNI_TSOP_DIAG_DBIP8);
	HANDLE_FLAG(SONET_INS_LBIP,TLOP_DIAG,SUNI_TLOP_DIAG_DBIP);
	HANDLE_FLAG(SONET_INS_PBIP,TPOP_CD,SUNI_TPOP_DIAG_DB3);
	HANDLE_FLAG(SONET_INS_FRAME,RSOP_CIE,SUNI_RSOP_CIE_FOOF);
	HANDLE_FLAG(SONET_INS_LAIS,TSOP_CTRL,SUNI_TSOP_CTRL_LAIS);
	HANDLE_FLAG(SONET_INS_PAIS,TPOP_CD,SUNI_TPOP_DIAG_PAIS);
	HANDLE_FLAG(SONET_INS_LOS,TSOP_DIAG,SUNI_TSOP_DIAG_DLOS);
	HANDLE_FLAG(SONET_INS_HCS,TACP_CS,SUNI_TACP_CS_DHCS);
	return put_user(todo,(int __user *)arg) ? -EFAULT : 0;
}


#undef HANDLE_FLAG


static int get_diag(struct atm_dev *dev,void __user *arg)
{
	int set;

	set = 0;
	if (GET(TSOP_DIAG) & SUNI_TSOP_DIAG_DBIP8) set |= SONET_INS_SBIP;
	if (GET(TLOP_DIAG) & SUNI_TLOP_DIAG_DBIP) set |= SONET_INS_LBIP;
	if (GET(TPOP_CD) & SUNI_TPOP_DIAG_DB3) set |= SONET_INS_PBIP;
	/* SONET_INS_FRAME is one-shot only */
	if (GET(TSOP_CTRL) & SUNI_TSOP_CTRL_LAIS) set |= SONET_INS_LAIS;
	if (GET(TPOP_CD) & SUNI_TPOP_DIAG_PAIS) set |= SONET_INS_PAIS;
	if (GET(TSOP_DIAG) & SUNI_TSOP_DIAG_DLOS) set |= SONET_INS_LOS;
	if (GET(TACP_CS) & SUNI_TACP_CS_DHCS) set |= SONET_INS_HCS;
	return put_user(set,(int __user *)arg) ? -EFAULT : 0;
}


static int set_loopback(struct atm_dev *dev,int mode)
{
	unsigned char control;
	int reg, dle, lle;

	if (PRIV(dev)->type == SUNI_MRI_TYPE_PM5355) {
		reg = SUNI_MCM;
		dle = SUNI_MCM_DLE;
		lle = SUNI_MCM_LLE;
	} else {
		reg = SUNI_MCT;
		dle = SUNI_MCT_DLE;
		lle = SUNI_MCT_LLE;
	}

	control = dev->ops->phy_get(dev, reg) & ~(dle | lle);
	switch (mode) {
		case ATM_LM_NONE:
			break;
		case ATM_LM_LOC_PHY:
			control |= dle;
			break;
		case ATM_LM_RMT_PHY:
			control |= lle;
			break;
		default:
			return -EINVAL;
	}
	 dev->ops->phy_put(dev, control, reg);
	PRIV(dev)->loop_mode = mode;
	return 0;
}

/*
 * SONET vs. SDH Configuration
 *
 * Z0INS (register 0x06): 0 for SONET, 1 for SDH
 * ENSS (register 0x3D): 0 for SONET, 1 for SDH
 * LEN16 (register 0x28): 0 for SONET, 1 for SDH (n/a for S/UNI 155 QUAD)
 * LEN16 (register 0x50): 0 for SONET, 1 for SDH (n/a for S/UNI 155 QUAD)
 * S[1:0] (register 0x46): 00 for SONET, 10 for SDH
 */

static int set_sonet(struct atm_dev *dev)
{
	if (PRIV(dev)->type == SUNI_MRI_TYPE_PM5355) {
		PUT(GET(RPOP_RC) & ~SUNI_RPOP_RC_ENSS, RPOP_RC);
		PUT(GET(SSTB_CTRL) & ~SUNI_SSTB_CTRL_LEN16, SSTB_CTRL);
		PUT(GET(SPTB_CTRL) & ~SUNI_SPTB_CTRL_LEN16, SPTB_CTRL);
	}

	REG_CHANGE(SUNI_TPOP_APM_S, SUNI_TPOP_APM_S_SHIFT,
		   SUNI_TPOP_S_SONET, TPOP_APM);

	return 0;
}

static int set_sdh(struct atm_dev *dev)
{
	if (PRIV(dev)->type == SUNI_MRI_TYPE_PM5355) {
		PUT(GET(RPOP_RC) | SUNI_RPOP_RC_ENSS, RPOP_RC);
		PUT(GET(SSTB_CTRL) | SUNI_SSTB_CTRL_LEN16, SSTB_CTRL);
		PUT(GET(SPTB_CTRL) | SUNI_SPTB_CTRL_LEN16, SPTB_CTRL);
	}

	REG_CHANGE(SUNI_TPOP_APM_S, SUNI_TPOP_APM_S_SHIFT,
		   SUNI_TPOP_S_SDH, TPOP_APM);

	return 0;
}


static int get_framing(struct atm_dev *dev, void __user *arg)
{
	int framing;
	unsigned char s;


	s = (GET(TPOP_APM) & SUNI_TPOP_APM_S) >> SUNI_TPOP_APM_S_SHIFT;
	if (s == SUNI_TPOP_S_SONET)
		framing = SONET_FRAME_SONET;
	else
		framing = SONET_FRAME_SDH;

	return put_user(framing, (int __user *) arg) ? -EFAULT : 0;
}

static int set_framing(struct atm_dev *dev, void __user *arg)
{
	int mode;

	if (get_user(mode, (int __user *) arg))
		return -EFAULT;

	if (mode == SONET_FRAME_SONET)
		return set_sonet(dev);
	else if (mode == SONET_FRAME_SDH)
		return set_sdh(dev);

	return -EINVAL;
}


static int suni_ioctl(struct atm_dev *dev,unsigned int cmd,void __user *arg)
{
	switch (cmd) {
		case SONET_GETSTATZ:
		case SONET_GETSTAT:
			return fetch_stats(dev, arg, cmd == SONET_GETSTATZ);
		case SONET_SETDIAG:
			return change_diag(dev,arg,1);
		case SONET_CLRDIAG:
			return change_diag(dev,arg,0);
		case SONET_GETDIAG:
			return get_diag(dev,arg);
		case SONET_SETFRAMING:
			if (!capable(CAP_NET_ADMIN))
				return -EPERM;
			return set_framing(dev, arg);
		case SONET_GETFRAMING:
			return get_framing(dev, arg);
		case SONET_GETFRSENSE:
			return -EINVAL;
		case ATM_SETLOOP:
			if (!capable(CAP_NET_ADMIN))
				return -EPERM;
			return set_loopback(dev,(int)(unsigned long)arg);
		case ATM_GETLOOP:
			return put_user(PRIV(dev)->loop_mode,(int __user *)arg) ?
			    -EFAULT : 0;
		case ATM_QUERYLOOP:
			return put_user(ATM_LM_LOC_PHY | ATM_LM_RMT_PHY,
			    (int __user *) arg) ? -EFAULT : 0;
		default:
			return -ENOIOCTLCMD;
	}
}


static void poll_los(struct atm_dev *dev)
{
	atm_dev_signal_change(dev,
		GET(RSOP_SIS) & SUNI_RSOP_SIS_LOSV ?
		ATM_PHY_SIG_LOST : ATM_PHY_SIG_FOUND);
}


static void suni_int(struct atm_dev *dev)
{
	poll_los(dev);
	printk(KERN_NOTICE "%s(itf %d): signal %s\n",dev->type,dev->number,
	    dev->signal == ATM_PHY_SIG_LOST ?  "lost" : "detected again");
}


static int suni_start(struct atm_dev *dev)
{
	unsigned long flags;
	int first;

	spin_lock_irqsave(&sunis_lock,flags);
	first = !sunis;
	PRIV(dev)->next = sunis;
	sunis = PRIV(dev);
	spin_unlock_irqrestore(&sunis_lock,flags);
	memset(&PRIV(dev)->sonet_stats,0,sizeof(struct k_sonet_stats));
	PUT(GET(RSOP_CIE) | SUNI_RSOP_CIE_LOSE,RSOP_CIE);
		/* interrupt on loss of signal */
	poll_los(dev); /* ... and clear SUNI interrupts */
	if (dev->signal == ATM_PHY_SIG_LOST)
		printk(KERN_WARNING "%s(itf %d): no signal\n",dev->type,
		    dev->number);
	PRIV(dev)->loop_mode = ATM_LM_NONE;
	suni_hz(0); /* clear SUNI counters */
	(void) fetch_stats(dev,NULL,1); /* clear kernel counters */
	if (first) {
		init_timer(&poll_timer);
		poll_timer.expires = jiffies+HZ;
		poll_timer.function = suni_hz;
		poll_timer.data = 1;
#if 0
printk(KERN_DEBUG "[u] p=0x%lx,n=0x%lx\n",(unsigned long) poll_timer.list.prev,
    (unsigned long) poll_timer.list.next);
#endif
		add_timer(&poll_timer);
	}
	return 0;
}


static int suni_stop(struct atm_dev *dev)
{
	struct suni_priv **walk;
	unsigned long flags;

	/* let SAR driver worry about stopping interrupts */
	spin_lock_irqsave(&sunis_lock,flags);
	for (walk = &sunis; *walk != PRIV(dev);
	    walk = &PRIV((*walk)->dev)->next);
	*walk = PRIV((*walk)->dev)->next;
	if (!sunis) del_timer_sync(&poll_timer);
	spin_unlock_irqrestore(&sunis_lock,flags);
	kfree(PRIV(dev));

	return 0;
}


static const struct atmphy_ops suni_ops = {
	.start		= suni_start,
	.ioctl		= suni_ioctl,
	.interrupt	= suni_int,
	.stop		= suni_stop,
};


int suni_init(struct atm_dev *dev)
{
	unsigned char mri;

	if (!(dev->phy_data = kmalloc(sizeof(struct suni_priv),GFP_KERNEL)))
		return -ENOMEM;
	PRIV(dev)->dev = dev;

	mri = GET(MRI); /* reset SUNI */
	PRIV(dev)->type = (mri & SUNI_MRI_TYPE) >> SUNI_MRI_TYPE_SHIFT;
	PUT(mri | SUNI_MRI_RESET,MRI);
	PUT(mri,MRI);
	PUT((GET(MT) & SUNI_MT_DS27_53),MT); /* disable all tests */
        set_sonet(dev);
	REG_CHANGE(SUNI_TACP_IUCHP_CLP,0,SUNI_TACP_IUCHP_CLP,
	    TACP_IUCHP); /* idle cells */
	PUT(SUNI_IDLE_PATTERN,TACP_IUCPOP);
	dev->phy = &suni_ops;

	return 0;
}

EXPORT_SYMBOL(suni_init);

MODULE_LICENSE("GPL");
an class="p">] = creds[key] else: rally_conf['admin'][key] = creds[key] endpoint_types = [('internalURL', 'internal'), ('publicURL', 'public'), ('adminURL', 'admin')] endpoint_type = get_endpoint_type_from_env() if endpoint_type is not None: cred_key = env_cred_dict.get('OS_ENDPOINT_TYPE') for k, v in endpoint_types: if endpoint_type == v: rally_conf[cred_key] = v region_name = os.getenv('OS_REGION_NAME') if region_name is not None: cred_key = env_cred_dict.get('OS_REGION_NAME') rally_conf[cred_key] = region_name cacert = os.getenv('OS_CACERT') if cacert is not None: cred_key = env_cred_dict.get('OS_CACERT') rally_conf[cred_key] = cacert return rally_conf def get_endpoint_type_from_env(): endpoint_type = os.environ.get("OS_ENDPOINT_TYPE", os.environ.get("OS_INTERFACE")) if endpoint_type and "URL" in endpoint_type: endpoint_type = endpoint_type.replace("URL", "") return endpoint_type def get_session_auth(other_creds={}): loader = loading.get_plugin_loader('password') creds = get_credentials(other_creds) auth = loader.load_from_options(**creds) return auth def get_endpoint(service_type, endpoint_type='publicURL'): auth = get_session_auth() return get_session().get_endpoint(auth=auth, service_type=service_type, endpoint_type=endpoint_type) def get_session(other_creds={}): auth = get_session_auth(other_creds) cacert = os.getenv('OS_CACERT') if cacert is not None: if not os.path.isfile(cacert): raise Exception("The 'OS_CACERT' environment" "variable is set to %s but the file" "does not exist.", cacert) return session.Session(auth=auth, verify=cacert) # ********************************************* # CLIENTS # ********************************************* def get_keystone_client_version(): api_version = os.getenv('OS_IDENTITY_API_VERSION') if api_version is not None: logger.info("OS_IDENTITY_API_VERSION is set in env as '%s'", api_version) return api_version return DEFAULT_API_VERSION def get_keystone_client(other_creds={}): sess = get_session(other_creds) return keystoneclient.Client(get_keystone_client_version(), session=sess, interface=os.getenv('OS_INTERFACE', 'admin')) def get_nova_client_version(): api_version = os.getenv('OS_COMPUTE_API_VERSION') if api_version is not None: logger.info("OS_COMPUTE_API_VERSION is set in env as '%s'", api_version) return api_version return DEFAULT_API_VERSION def get_nova_client(other_creds={}): sess = get_session(other_creds) return novaclient.Client(get_nova_client_version(), session=sess) def get_cinder_client_version(): api_version = os.getenv('OS_VOLUME_API_VERSION') if api_version is not None: logger.info("OS_VOLUME_API_VERSION is set in env as '%s'", api_version) return api_version return DEFAULT_API_VERSION def get_cinder_client(other_creds={}): sess = get_session(other_creds) return cinderclient.Client(get_cinder_client_version(), session=sess) def get_neutron_client_version(): api_version = os.getenv('OS_NETWORK_API_VERSION') if api_version is not None: logger.info("OS_NETWORK_API_VERSION is set in env as '%s'", api_version) return api_version return DEFAULT_API_VERSION def get_neutron_client(other_creds={}): sess = get_session(other_creds) return neutronclient.Client(get_neutron_client_version(), session=sess) def get_glance_client_version(): api_version = os.getenv('OS_IMAGE_API_VERSION') if api_version is not None: logger.info("OS_IMAGE_API_VERSION is set in env as '%s'", api_version) return api_version return DEFAULT_API_VERSION def get_glance_client(other_creds={}): sess = get_session(other_creds) return glanceclient.Client(get_glance_client_version(), session=sess) def get_heat_client_version(): api_version = os.getenv('OS_ORCHESTRATION_API_VERSION') if api_version is not None: logger.info("OS_ORCHESTRATION_API_VERSION is set in env as '%s'", api_version) return api_version return DEFAULT_HEAT_API_VERSION def get_heat_client(other_creds={}): sess = get_session(other_creds) return heatclient.Client(get_heat_client_version(), session=sess) # ********************************************* # NOVA # ********************************************* def get_instances(nova_client): try: instances = nova_client.servers.list(search_opts={'all_tenants': 1}) return instances except Exception as e: logger.error("Error [get_instances(nova_client)]: %s" % e) return None def get_instance_status(nova_client, instance): try: instance = nova_client.servers.get(instance.id) return instance.status except Exception as e: logger.error("Error [get_instance_status(nova_client)]: %s" % e) return None def get_instance_by_name(nova_client, instance_name): try: instance = nova_client.servers.find(name=instance_name) return instance except Exception as e: logger.error("Error [get_instance_by_name(nova_client, '%s')]: %s" % (instance_name, e)) return None def get_flavor_id(nova_client, flavor_name): flavors = nova_client.flavors.list(detailed=True) id = '' for f in flavors: if f.name == flavor_name: id = f.id break return id def get_flavor_id_by_ram_range(nova_client, min_ram, max_ram): flavors = nova_client.flavors.list(detailed=True) id = '' for f in flavors: if min_ram <= f.ram and f.ram <= max_ram: id = f.id break return id def get_aggregates(nova_client): try: aggregates = nova_client.aggregates.list() return aggregates except Exception as e: logger.error("Error [get_aggregates(nova_client)]: %s" % e) return None def get_aggregate_id(nova_client, aggregate_name): try: aggregates = get_aggregates(nova_client) _id = [ag.id for ag in aggregates if ag.name == aggregate_name][0] return _id except Exception as e: logger.error("Error [get_aggregate_id(nova_client, %s)]:" " %s" % (aggregate_name, e)) return None def get_availability_zones(nova_client): try: availability_zones = nova_client.availability_zones.list() return availability_zones except Exception as e: logger.error("Error [get_availability_zones(nova_client)]: %s" % e) return None def get_availability_zone_names(nova_client): try: az_names = [az.zoneName for az in get_availability_zones(nova_client)] return az_names except Exception as e: logger.error("Error [get_availability_zone_names(nova_client)]:" " %s" % e) return None def create_flavor(nova_client, flavor_name, ram, disk, vcpus, public=True): try: flavor = nova_client.flavors.create( flavor_name, ram, vcpus, disk, is_public=public) try: extra_specs = ft_utils.get_functest_config( 'general.flavor_extra_specs') flavor.set_keys(extra_specs) except ValueError: # flavor extra specs are not configured, therefore skip the update pass except Exception as e: logger.error("Error [create_flavor(nova_client, '%s', '%s', '%s', " "'%s')]: %s" % (flavor_name, ram, disk, vcpus, e)) return None return flavor.id def get_or_create_flavor(flavor_name, ram, disk, vcpus, public=True): flavor_exists = False nova_client = get_nova_client() flavor_id = get_flavor_id(nova_client, flavor_name) if flavor_id != '': logger.info("Using existing flavor '%s'..." % flavor_name) flavor_exists = True else: logger.info("Creating flavor '%s' with '%s' RAM, '%s' disk size, " "'%s' vcpus..." % (flavor_name, ram, disk, vcpus)) flavor_id = create_flavor( nova_client, flavor_name, ram, disk, vcpus, public=public) if not flavor_id: logger.error("Failed to create flavor '%s'..." % (flavor_name)) else: logger.debug("Flavor '%s' with ID=%s created successfully." % (flavor_name, flavor_id)) return flavor_exists, flavor_id def get_floating_ips(nova_client): try: floating_ips = nova_client.floating_ips.list() return floating_ips except Exception as e: logger.error("Error [get_floating_ips(nova_client)]: %s" % e) return None def get_hypervisors(nova_client): try: nodes = [] hypervisors = nova_client.hypervisors.list() for hypervisor in hypervisors: if hypervisor.state == "up": nodes.append(hypervisor.hypervisor_hostname) return nodes except Exception as e: logger.error("Error [get_hypervisors(nova_client)]: %s" % e) return None def create_aggregate(nova_client, aggregate_name, av_zone): try: nova_client.aggregates.create(aggregate_name, av_zone) return True except Exception as e: logger.error("Error [create_aggregate(nova_client, %s, %s)]: %s" % (aggregate_name, av_zone, e)) return None def add_host_to_aggregate(nova_client, aggregate_name, compute_host): try: aggregate_id = get_aggregate_id(nova_client, aggregate_name) nova_client.aggregates.add_host(aggregate_id, compute_host) return True except Exception as e: logger.error("Error [add_host_to_aggregate(nova_client, %s, %s)]: %s" % (aggregate_name, compute_host, e)) return None def create_aggregate_with_host( nova_client, aggregate_name, av_zone, compute_host): try: create_aggregate(nova_client, aggregate_name, av_zone) add_host_to_aggregate(nova_client, aggregate_name, compute_host) return True except Exception as e: logger.error("Error [create_aggregate_with_host(" "nova_client, %s, %s, %s)]: %s" % (aggregate_name, av_zone, compute_host, e)) return None def create_instance(flavor_name, image_id, network_id, instance_name="functest-vm", confdrive=True, userdata=None, av_zone='', fixed_ip=None, files=None): nova_client = get_nova_client() try: flavor = nova_client.flavors.find(name=flavor_name) except: flavors = nova_client.flavors.list() logger.error("Error: Flavor '%s' not found. Available flavors are: " "\n%s" % (flavor_name, flavors)) return None if fixed_ip is not None: nics = {"net-id": network_id, "v4-fixed-ip": fixed_ip} else: nics = {"net-id": network_id} if userdata is None: instance = nova_client.servers.create( name=instance_name, flavor=flavor, image=image_id, nics=[nics], availability_zone=av_zone, files=files ) else: instance = nova_client.servers.create( name=instance_name, flavor=flavor, image=image_id, nics=[nics], config_drive=confdrive, userdata=userdata, availability_zone=av_zone, files=files ) return instance def create_instance_and_wait_for_active(flavor_name, image_id, network_id, instance_name="", config_drive=False, userdata="", av_zone='', fixed_ip=None, files=None): SLEEP = 3 VM_BOOT_TIMEOUT = 180 nova_client = get_nova_client() instance = create_instance(flavor_name, image_id, network_id, instance_name, config_drive, userdata, av_zone=av_zone, fixed_ip=fixed_ip, files=files) count = VM_BOOT_TIMEOUT / SLEEP for n in range(count, -1, -1): status = get_instance_status(nova_client, instance) if status.lower() == "active": return instance elif status.lower() == "error": logger.error("The instance %s went to ERROR status." % instance_name) return None time.sleep(SLEEP) logger.error("Timeout booting the instance %s." % instance_name) return None def create_floating_ip(neutron_client): extnet_id = get_external_net_id(neutron_client) props = {'floating_network_id': extnet_id} try: ip_json = neutron_client.create_floatingip({'floatingip': props}) fip_addr = ip_json['floatingip']['floating_ip_address'] fip_id = ip_json['floatingip']['id'] except Exception as e: logger.error("Error [create_floating_ip(neutron_client)]: %s" % e) return None return {'fip_addr': fip_addr, 'fip_id': fip_id} def add_floating_ip(nova_client, server_id, floatingip_addr): try: nova_client.servers.add_floating_ip(server_id, floatingip_addr) return True except Exception as e: logger.error("Error [add_floating_ip(nova_client, '%s', '%s')]: %s" % (server_id, floatingip_addr, e)) return False def delete_instance(nova_client, instance_id): try: nova_client.servers.force_delete(instance_id) return True except Exception as e: logger.error("Error [delete_instance(nova_client, '%s')]: %s" % (instance_id, e)) return False def delete_floating_ip(nova_client, floatingip_id): try: nova_client.floating_ips.delete(floatingip_id) return True except Exception as e: logger.error("Error [delete_floating_ip(nova_client, '%s')]: %s" % (floatingip_id, e)) return False def remove_host_from_aggregate(nova_client, aggregate_name, compute_host): try: aggregate_id = get_aggregate_id(nova_client, aggregate_name) nova_client.aggregates.remove_host(aggregate_id, compute_host) return True except Exception as e: logger.error("Error [remove_host_from_aggregate(nova_client, %s, %s)]:" " %s" % (aggregate_name, compute_host, e)) return False def remove_hosts_from_aggregate(nova_client, aggregate_name): aggregate_id = get_aggregate_id(nova_client, aggregate_name) hosts = nova_client.aggregates.get(aggregate_id).hosts assert( all(remove_host_from_aggregate(nova_client, aggregate_name, host) for host in hosts)) def delete_aggregate(nova_client, aggregate_name): try: remove_hosts_from_aggregate(nova_client, aggregate_name) nova_client.aggregates.delete(aggregate_name) return True except Exception as e: logger.error("Error [delete_aggregate(nova_client, %s)]: %s" % (aggregate_name, e)) return False # ********************************************* # NEUTRON # ********************************************* def get_network_list(neutron_client): network_list = neutron_client.list_networks()['networks'] if len(network_list) == 0: return None else: return network_list def get_router_list(neutron_client): router_list = neutron_client.list_routers()['routers'] if len(router_list) == 0: return None else: return router_list def get_port_list(neutron_client): port_list = neutron_client.list_ports()['ports'] if len(port_list) == 0: return None else: return port_list def get_network_id(neutron_client, network_name): networks = neutron_client.list_networks()['networks'] id = '' for n in networks: if n['name'] == network_name: id = n['id'] break return id def get_subnet_id(neutron_client, subnet_name): subnets = neutron_client.list_subnets()['subnets'] id = '' for s in subnets: if s['name'] == subnet_name: id = s['id'] break return id def get_router_id(neutron_client, router_name): routers = neutron_client.list_routers()['routers'] id = '' for r in routers: if r['name'] == router_name: id = r['id'] break return id def get_private_net(neutron_client): # Checks if there is an existing shared private network networks = neutron_client.list_networks()['networks'] if len(networks) == 0: return None for net in networks: if (net['router:external'] is False) and (net['shared'] is True): return net return None def get_external_net(neutron_client): for network in neutron_client.list_networks()['networks']: if network['router:external']: return network['name'] return None def get_external_net_id(neutron_client): for network in neutron_client.list_networks()['networks']: if network['router:external']: return network['id'] return None def check_neutron_net(neutron_client, net_name): for network in neutron_client.list_networks()['networks']: if network['name'] == net_name: for subnet in network['subnets']: return True return False def create_neutron_net(neutron_client, name): json_body = {'network': {'name': name, 'admin_state_up': True}} try: network = neutron_client.create_network(body=json_body) network_dict = network['network'] return network_dict['id'] except Exception as e: logger.error("Error [create_neutron_net(neutron_client, '%s')]: %s" % (name, e)) return None def create_neutron_subnet(neutron_client, name, cidr, net_id): json_body = {'subnets': [{'name': name, 'cidr': cidr, 'ip_version': 4, 'network_id': net_id}]} try: subnet = neutron_client.create_subnet(body=json_body) return subnet['subnets'][0]['id'] except Exception as e: logger.error("Error [create_neutron_subnet(neutron_client, '%s', " "'%s', '%s')]: %s" % (name, cidr, net_id, e)) return None def create_neutron_router(neutron_client, name): json_body = {'router': {'name': name, 'admin_state_up': True}} try: router = neutron_client.create_router(json_body) return router['router']['id'] except Exception as e: logger.error("Error [create_neutron_router(neutron_client, '%s')]: %s" % (name, e)) return None def create_neutron_port(neutron_client, name, network_id, ip): json_body = {'port': { 'admin_state_up': True, 'name': name, 'network_id': network_id, 'fixed_ips': [{"ip_address": ip}] }} try: port = neutron_client.create_port(body=json_body) return port['port']['id'] except Exception as e: logger.error("Error [create_neutron_port(neutron_client, '%s', '%s', " "'%s')]: %s" % (name, network_id, ip, e)) return None def update_neutron_net(neutron_client, network_id, shared=False): json_body = {'network': {'shared': shared}} try: neutron_client.update_network(network_id, body=json_body) return True except Exception as e: logger.error("Error [update_neutron_net(neutron_client, '%s', '%s')]: " "%s" % (network_id, str(shared), e)) return False def update_neutron_port(neutron_client, port_id, device_owner): json_body = {'port': { 'device_owner': device_owner, }} try: port = neutron_client.update_port(port=port_id, body=json_body) return port['port']['id'] except Exception as e: logger.error("Error [update_neutron_port(neutron_client, '%s', '%s')]:" " %s" % (port_id, device_owner, e)) return None def add_interface_router(neutron_client, router_id, subnet_id): json_body = {"subnet_id": subnet_id} try: neutron_client.add_interface_router(router=router_id, body=json_body) return True except Exception as e: logger.error("Error [add_interface_router(neutron_client, '%s', " "'%s')]: %s" % (router_id, subnet_id, e)) return False def add_gateway_router(neutron_client, router_id): ext_net_id = get_external_net_id(neutron_client) router_dict = {'network_id': ext_net_id} try: neutron_client.add_gateway_router(router_id, router_dict) return True except Exception as e: logger.error("Error [add_gateway_router(neutron_client, '%s')]: %s" % (router_id, e)) return False def delete_neutron_net(neutron_client, network_id): try: neutron_client.delete_network(network_id) return True except Exception as e: logger.error("Error [delete_neutron_net(neutron_client, '%s')]: %s" % (network_id, e)) return False def delete_neutron_subnet(neutron_client, subnet_id): try: neutron_client.delete_subnet(subnet_id) return True except Exception as e: logger.error("Error [delete_neutron_subnet(neutron_client, '%s')]: %s" % (subnet_id, e)) return False def delete_neutron_router(neutron_client, router_id): try: neutron_client.delete_router(router=router_id) return True except Exception as e: logger.error("Error [delete_neutron_router(neutron_client, '%s')]: %s" % (router_id, e)) return False def delete_neutron_port(neutron_client, port_id): try: neutron_client.delete_port(port_id) return True except Exception as e: logger.error("Error [delete_neutron_port(neutron_client, '%s')]: %s" % (port_id, e)) return False def remove_interface_router(neutron_client, router_id, subnet_id): json_body = {"subnet_id": subnet_id} try: neutron_client.remove_interface_router(router=router_id, body=json_body) return True except Exception as e: logger.error("Error [remove_interface_router(neutron_client, '%s', " "'%s')]: %s" % (router_id, subnet_id, e)) return False def remove_gateway_router(neutron_client, router_id): try: neutron_client.remove_gateway_router(router_id) return True except Exception as e: logger.error("Error [remove_gateway_router(neutron_client, '%s')]: %s" % (router_id, e)) return False def create_network_full(neutron_client, net_name, subnet_name, router_name, cidr): # Check if the network already exists network_id = get_network_id(neutron_client, net_name) subnet_id = get_subnet_id(neutron_client, subnet_name) router_id = get_router_id(neutron_client, router_name) if network_id != '' and subnet_id != '' and router_id != '': logger.info("A network with name '%s' already exists..." % net_name) else: neutron_client.format = 'json' logger.info('Creating neutron network %s...' % net_name) network_id = create_neutron_net(neutron_client, net_name) if not network_id: return False logger.debug("Network '%s' created successfully" % network_id) logger.debug('Creating Subnet....') subnet_id = create_neutron_subnet(neutron_client, subnet_name, cidr, network_id) if not subnet_id: return None logger.debug("Subnet '%s' created successfully" % subnet_id) logger.debug('Creating Router...') router_id = create_neutron_router(neutron_client, router_name) if not router_id: return None logger.debug("Router '%s' created successfully" % router_id) logger.debug('Adding router to subnet...') if not add_interface_router(neutron_client, router_id, subnet_id): return None logger.debug("Interface added successfully.") logger.debug('Adding gateway to router...') if not add_gateway_router(neutron_client, router_id): return None logger.debug("Gateway added successfully.") network_dic = {'net_id': network_id, 'subnet_id': subnet_id, 'router_id': router_id} return network_dic def create_shared_network_full(net_name, subnt_name, router_name, subnet_cidr): neutron_client = get_neutron_client() network_dic = create_network_full(neutron_client, net_name, subnt_name, router_name, subnet_cidr) if network_dic: if not update_neutron_net(neutron_client, network_dic['net_id'], shared=True): logger.error("Failed to update network %s..." % net_name) return None else: logger.debug("Network '%s' is available..." % net_name) else: logger.error("Network %s creation failed" % net_name) return None return network_dic def create_bgpvpn(neutron_client, **kwargs): # route_distinguishers # route_targets json_body = {"bgpvpn": kwargs} return neutron_client.create_bgpvpn(json_body) def create_network_association(neutron_client, bgpvpn_id, neutron_network_id): json_body = {"network_association": {"network_id": neutron_network_id}} return neutron_client.create_network_association(bgpvpn_id, json_body) def create_router_association(neutron_client, bgpvpn_id, router_id): json_body = {"router_association": {"router_id": router_id}} return neutron_client.create_router_association(bgpvpn_id, json_body) def update_bgpvpn(neutron_client, bgpvpn_id, **kwargs): json_body = {"bgpvpn": kwargs} return neutron_client.update_bgpvpn(bgpvpn_id, json_body) def delete_bgpvpn(neutron_client, bgpvpn_id): return neutron_client.delete_bgpvpn(bgpvpn_id) def get_bgpvpn(neutron_client, bgpvpn_id): return neutron_client.show_bgpvpn(bgpvpn_id) def get_bgpvpn_routers(neutron_client, bgpvpn_id): return get_bgpvpn(neutron_client, bgpvpn_id)['bgpvpn']['routers'] def get_bgpvpn_networks(neutron_client, bgpvpn_id): return get_bgpvpn(neutron_client, bgpvpn_id)['bgpvpn']['networks'] # ********************************************* # SEC GROUPS # ********************************************* def get_security_groups(neutron_client): try: security_groups = neutron_client.list_security_groups()[ 'security_groups'] return security_groups except Exception as e: logger.error("Error [get_security_groups(neutron_client)]: %s" % e) return None def get_security_group_id(neutron_client, sg_name): security_groups = get_security_groups(neutron_client) id = '' for sg in security_groups: if sg['name'] == sg_name: id = sg['id'] break return id def create_security_group(neutron_client, sg_name, sg_description): json_body = {'security_group': {'name': sg_name, 'description': sg_description}} try: secgroup = neutron_client.create_security_group(json_body) return secgroup['security_group'] except Exception as e: logger.error("Error [create_security_group(neutron_client, '%s', " "'%s')]: %s" % (sg_name, sg_description, e)) return None def create_secgroup_rule(neutron_client, sg_id, direction, protocol, port_range_min=None, port_range_max=None): # We create a security group in 2 steps # 1 - we check the format and set the json body accordingly # 2 - we call neturon client to create the security group # Format check json_body = {'security_group_rule': {'direction': direction, 'security_group_id': sg_id, 'protocol': protocol}} # parameters may be # - both None => we do nothing # - both Not None => we add them to the json description # but one cannot be None is the other is not None if (port_range_min is not None and port_range_max is not None): # add port_range in json description json_body['security_group_rule']['port_range_min'] = port_range_min json_body['security_group_rule']['port_range_max'] = port_range_max logger.debug("Security_group format set (port range included)") else: # either both port range are set to None => do nothing # or one is set but not the other => log it and return False if port_range_min is None and port_range_max is None: logger.debug("Security_group format set (no port range mentioned)") else: logger.error("Bad security group format." "One of the port range is not properly set:" "range min: {}," "range max: {}".format(port_range_min, port_range_max)) return False # Create security group using neutron client try: neutron_client.create_security_group_rule(json_body) return True except: logger.exception("Impossible to create_security_group_rule," "security group rule probably already exists") return False def get_security_group_rules(neutron_client, sg_id): try: security_rules = neutron_client.list_security_group_rules()[ 'security_group_rules'] security_rules = [rule for rule in security_rules if rule["security_group_id"] == sg_id] return security_rules except Exception as e: logger.error("Error [get_security_group_rules(neutron_client, sg_id)]:" " %s" % e) return None def check_security_group_rules(neutron_client, sg_id, direction, protocol, port_min=None, port_max=None): try: security_rules = get_security_group_rules(neutron_client, sg_id) security_rules = [rule for rule in security_rules if (rule["direction"].lower() == direction and rule["protocol"].lower() == protocol and rule["port_range_min"] == port_min and rule["port_range_max"] == port_max)] if len(security_rules) == 0: return True else: return False except Exception as e: logger.error("Error [check_security_group_rules(" " neutron_client, sg_id, direction," " protocol, port_min=None, port_max=None)]: " "%s" % e) return None def create_security_group_full(neutron_client, sg_name, sg_description): sg_id = get_security_group_id(neutron_client, sg_name) if sg_id != '': logger.info("Using existing security group '%s'..." % sg_name) else: logger.info("Creating security group '%s'..." % sg_name) SECGROUP = create_security_group(neutron_client, sg_name, sg_description) if not SECGROUP: logger.error("Failed to create the security group...") return None sg_id = SECGROUP['id'] logger.debug("Security group '%s' with ID=%s created successfully." % (SECGROUP['name'], sg_id)) logger.debug("Adding ICMP rules in security group '%s'..." % sg_name) if not create_secgroup_rule(neutron_client, sg_id, 'ingress', 'icmp'): logger.error("Failed to create the security group rule...") return None logger.debug("Adding SSH rules in security group '%s'..." % sg_name) if not create_secgroup_rule( neutron_client, sg_id, 'ingress', 'tcp', '22', '22'): logger.error("Failed to create the security group rule...") return None if not create_secgroup_rule( neutron_client, sg_id, 'egress', 'tcp', '22', '22'): logger.error("Failed to create the security group rule...") return None return sg_id def add_secgroup_to_instance(nova_client, instance_id, secgroup_id): try: nova_client.servers.add_security_group(instance_id, secgroup_id) return True except Exception as e: logger.error("Error [add_secgroup_to_instance(nova_client, '%s', " "'%s')]: %s" % (instance_id, secgroup_id, e)) return False def update_sg_quota(neutron_client, tenant_id, sg_quota, sg_rule_quota): json_body = {"quota": { "security_group": sg_quota, "security_group_rule": sg_rule_quota }} try: neutron_client.update_quota(tenant_id=tenant_id, body=json_body) return True except Exception as e: logger.error("Error [update_sg_quota(neutron_client, '%s', '%s', " "'%s')]: %s" % (tenant_id, sg_quota, sg_rule_quota, e)) return False def delete_security_group(neutron_client, secgroup_id): try: neutron_client.delete_security_group(secgroup_id) return True except Exception as e: logger.error("Error [delete_security_group(neutron_client, '%s')]: %s" % (secgroup_id, e)) return False # ********************************************* # GLANCE # ********************************************* def get_images(nova_client): try: images = nova_client.images.list() return images except Exception as e: logger.error("Error [get_images]: %s" % e) return None def get_image_id(glance_client, image_name): images = glance_client.images.list() id = '' for i in images: if i.name == image_name: id = i.id break return id def create_glance_image(glance_client, image_name, file_path, disk="qcow2", container="bare", public="public"): if not os.path.isfile(file_path): logger.error("Error: file %s does not exist." % file_path) return None try: image_id = get_image_id(glance_client, image_name) if image_id != '': logger.info("Image %s already exists." % image_name) else: logger.info("Creating image '%s' from '%s'..." % (image_name, file_path)) image = glance_client.images.create(name=image_name, visibility=public, disk_format=disk, container_format=container) image_id = image.id with open(file_path) as image_data: glance_client.images.upload(image_id, image_data) return image_id except Exception as e: logger.error("Error [create_glance_image(glance_client, '%s', '%s', " "'%s')]: %s" % (image_name, file_path, public, e)) return None def get_or_create_image(name, path, format): image_exists = False glance_client = get_glance_client() image_id = get_image_id(glance_client, name) if image_id != '': logger.info("Using existing image '%s'..." % name) image_exists = True else: logger.info("Creating image '%s' from '%s'..." % (name, path)) image_id = create_glance_image(glance_client, name, path, format) if not image_id: logger.error("Failed to create a Glance image...") else: logger.debug("Image '%s' with ID=%s created successfully." % (name, image_id)) return image_exists, image_id def delete_glance_image(nova_client, image_id): try: nova_client.images.delete(image_id) return True except Exception as e: logger.error("Error [delete_glance_image(nova_client, '%s')]: %s" % (image_id, e)) return False # ********************************************* # CINDER # ********************************************* def get_volumes(cinder_client): try: volumes = cinder_client.volumes.list(search_opts={'all_tenants': 1}) return volumes except Exception as e: logger.error("Error [get_volumes(cinder_client)]: %s" % e) return None def list_volume_types(cinder_client, public=True, private=True): try: volume_types = cinder_client.volume_types.list() if not public: volume_types = [vt for vt in volume_types if not vt.is_public] if not private: volume_types = [vt for vt in volume_types if vt.is_public] return volume_types except Exception as e: logger.error("Error [list_volume_types(cinder_client)]: %s" % e) return None def create_volume_type(cinder_client, name): try: volume_type = cinder_client.volume_types.create(name) return volume_type except Exception as e: logger.error("Error [create_volume_type(cinder_client, '%s')]: %s" % (name, e)) return None def update_cinder_quota(cinder_client, tenant_id, vols_quota, snapshots_quota, gigabytes_quota): quotas_values = {"volumes": vols_quota, "snapshots": snapshots_quota, "gigabytes": gigabytes_quota} try: cinder_client.quotas.update(tenant_id, **quotas_values) return True except Exception as e: logger.error("Error [update_cinder_quota(cinder_client, '%s', '%s', " "'%s' '%s')]: %s" % (tenant_id, vols_quota, snapshots_quota, gigabytes_quota, e)) return False def delete_volume(cinder_client, volume_id, forced=False): try: if forced: try: cinder_client.volumes.detach(volume_id) except: logger.error(sys.exc_info()[0]) cinder_client.volumes.force_delete(volume_id) else: cinder_client.volumes.delete(volume_id) return True except Exception as e: logger.error("Error [delete_volume(cinder_client, '%s', '%s')]: %s" % (volume_id, str(forced), e)) return False def delete_volume_type(cinder_client, volume_type): try: cinder_client.volume_types.delete(volume_type) return True except Exception as e: logger.error("Error [delete_volume_type(cinder_client, '%s')]: %s" % (volume_type, e)) return False # ********************************************* # KEYSTONE # ********************************************* def get_tenants(keystone_client): try: if is_keystone_v3(): tenants = keystone_client.projects.list() else: tenants = keystone_client.tenants.list() return tenants except Exception as e: logger.error("Error [get_tenants(keystone_client)]: %s" % e) return None def get_users(keystone_client): try: users = keystone_client.users.list() return users except Exception as e: logger.error("Error [get_users(keystone_client)]: %s" % e) return None def get_tenant_id(keystone_client, tenant_name): tenants = get_tenants(keystone_client) id = '' for t in tenants: if t.name == tenant_name: id = t.id break return id def get_user_id(keystone_client, user_name): users = get_users(keystone_client) id = '' for u in users: if u.name == user_name: id = u.id break return id def get_role_id(keystone_client, role_name): roles = keystone_client.roles.list() id = '' for r in roles: if r.name == role_name: id = r.id break return id def create_tenant(keystone_client, tenant_name, tenant_description): try: if is_keystone_v3(): tenant = keystone_client.projects.create( name=tenant_name, description=tenant_description, domain="default", enabled=True) else: tenant = keystone_client.tenants.create(tenant_name, tenant_description, enabled=True) return tenant.id except Exception as e: logger.error("Error [create_tenant(keystone_client, '%s', '%s')]: %s" % (tenant_name, tenant_description, e)) return None def get_or_create_tenant(keystone_client, tenant_name, tenant_description): tenant_id = get_tenant_id(keystone_client, tenant_name) if not tenant_id: tenant_id = create_tenant(keystone_client, tenant_name, tenant_description) return tenant_id def create_user(keystone_client, user_name, user_password, user_email, tenant_id): try: if is_keystone_v3(): user = keystone_client.users.create(name=user_name, password=user_password, email=user_email, project_id=tenant_id, enabled=True) else: user = keystone_client.users.create(user_name, user_password, user_email, tenant_id, enabled=True) return user.id except Exception as e: logger.error("Error [create_user(keystone_client, '%s', '%s', '%s'" "'%s')]: %s" % (user_name, user_password, user_email, tenant_id, e)) return None def get_or_create_user(keystone_client, user_name, user_password, tenant_id, user_email=None): user_id = get_user_id(keystone_client, user_name) if not user_id: user_id = create_user(keystone_client, user_name, user_password, user_email, tenant_id) return user_id def add_role_user(keystone_client, user_id, role_id, tenant_id): try: if is_keystone_v3(): keystone_client.roles.grant(role=role_id, user=user_id, project=tenant_id) else: keystone_client.roles.add_user_role(user_id, role_id, tenant_id) return True except Exception as e: logger.error("Error [add_role_user(keystone_client, '%s', '%s'" "'%s')]: %s " % (user_id, role_id, tenant_id, e)) return False def delete_tenant(keystone_client, tenant_id): try: if is_keystone_v3(): keystone_client.projects.delete(tenant_id) else: keystone_client.tenants.delete(tenant_id) return True except Exception as e: logger.error("Error [delete_tenant(keystone_client, '%s')]: %s" % (tenant_id, e)) return False def delete_user(keystone_client, user_id): try: keystone_client.users.delete(user_id) return True except Exception as e: logger.error("Error [delete_user(keystone_client, '%s')]: %s" % (user_id, e)) return False # ********************************************* # HEAT # ********************************************* def get_resource(heat_client, stack_id, resource): try: resources = heat_client.resources.get(stack_id, resource) return resources except Exception as e: logger.error("Error [get_resource]: %s" % e) return None