#!/usr/bin/env python # # jose.lausuch@ericsson.com # valentin.boucher@orange.com # All rights reserved. This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 # import logging import os.path import re import sys import time from keystoneauth1 import loading from keystoneauth1 import session from cinderclient import client as cinderclient from glanceclient import client as glanceclient from heatclient import client as heatclient from novaclient import client as novaclient from keystoneclient import client as keystoneclient from neutronclient.neutron import client as neutronclient from functest.utils.constants import CONST import functest.utils.functest_utils as ft_utils logger = logging.getLogger(__name__) DEFAULT_API_VERSION = '2' DEFAULT_HEAT_API_VERSION = '1' # ********************************************* # CREDENTIALS # ********************************************* class MissingEnvVar(Exception): def __init__(self, var): self.var = var def __str__(self): return str.format("Please set the mandatory env var: {}", self.var) def is_keystone_v3(): keystone_api_version = os.getenv('OS_IDENTITY_API_VERSION') if (keystone_api_version is None or keystone_api_version == '2'): return False else: return True def get_rc_env_vars(): env_vars = ['OS_AUTH_URL', 'OS_USERNAME', 'OS_PASSWORD'] if is_keystone_v3(): env_vars.extend(['OS_PROJECT_NAME', 'OS_USER_DOMAIN_NAME', 'OS_PROJECT_DOMAIN_NAME']) else: env_vars.extend(['OS_TENANT_NAME']) return env_vars def check_credentials(): """ Check if the OpenStack credentials (openrc) are sourced """ env_vars = get_rc_env_vars() return all(map(lambda v: v in os.environ and os.environ[v], env_vars)) def get_env_cred_dict(): env_cred_dict = { 'OS_USERNAME': 'username', 'OS_PASSWORD': 'password', 'OS_AUTH_URL': 'auth_url', 'OS_TENANT_NAME': 'tenant_name', 'OS_USER_DOMAIN_NAME': 'user_domain_name', 'OS_PROJECT_DOMAIN_NAME': 'project_domain_name', 'OS_PROJECT_NAME': 'project_name', 'OS_ENDPOINT_TYPE': 'endpoint_type', 'OS_REGION_NAME': 'region_name', 'OS_CACERT': 'https_cacert', 'OS_INSECURE': 'https_insecure' } return env_cred_dict def get_credentials(other_creds={}): """Returns a creds dictionary filled with parsed from env """ creds = {} env_vars = get_rc_env_vars() env_cred_dict = get_env_cred_dict() for envvar in env_vars: if os.getenv(envvar) is None: raise MissingEnvVar(envvar) else: creds_key = env_cred_dict.get(envvar) creds.update({creds_key: os.getenv(envvar)}) if 'tenant' in other_creds.keys(): if is_keystone_v3(): tenant = 'project_name' else: tenant = 'tenant_name' other_creds[tenant] = other_creds.pop('tenant') creds.update(other_creds) return creds def source_credentials(rc_file): with open(rc_file, "r") as f: for line in f: var = (line.rstrip('"\n').replace('export ', '').split("=") if re.search(r'(.*)=(.*)', line) else None) # The two next lines should be modified as soon as rc_file # conforms with common rules. Be aware that it could induce # issues if value starts with ' if var: key = re.sub(r'^["\' ]*|[ \'"]*$', '', var[0]) value = re.sub(r'^["\' ]*|[ \'"]*$', '', "".join(var[1:])) os.environ[key] = value def get_credentials_for_rally(): creds = get_credentials() env_cred_dict = get_env_cred_dict() rally_conf = {"type": "ExistingCloud", "admin": {}} for key in creds: if key == 'auth_url': rally_conf[key] = 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 cred_key = env_cred_dict.get('OS_CACERT') rally_conf[cred_key] = os.getenv('OS_CACERT', '') insecure_key = env_cred_dict.get('OS_INSECURE') rally_conf[insecure_key] = os.getenv('OS_INSECURE', '').lower() == 'true' 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, interface='public'): auth = get_session_auth() return get_session().get_endpoint(auth=auth, service_type=service_type, interface=interface) def get_session(other_creds={}): auth = get_session_auth(other_creds) https_cacert = os.getenv('OS_CACERT', '') https_insecure = os.getenv('OS_INSECURE', '').lower() == 'true' return session.Session(auth=auth, verify=(https_cacert or not https_insecure)) # ********************************************* # 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) def download_and_add_image_on_glance(glance, image_name, image_url, data_dir): try: dest_path = data_dir if not os.path.exists(dest_path): os.makedirs(dest_path) file_name = image_url.rsplit('/')[-1] if not ft_utils.download_url(image_url, dest_path): return False except Exception: raise Exception("Impossible to download image from {}".format( image_url)) try: image = create_glance_image( glance, image_name, dest_path + file_name) if not image: return False else: return image except Exception: raise Exception("Impossible to put image {} in glance".format( image_name)) # ********************************************* # 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
/*********************************************************************
 *
 * Filename:      ircomm_event.c
 * Version:       1.0
 * Description:   IrCOMM layer state machine
 * Status:        Stable
 * Author:        Dag Brattli <dagb@cs.uit.no>
 * Created at:    Sun Jun  6 20:33:11 1999
 * Modified at:   Sun Dec 12 13:44:32 1999
 * Modified by:   Dag Brattli <dagb@cs.uit.no>
 *
 *     Copyright (c) 1999 Dag Brattli, All Rights Reserved.
 *
 *     This program is free software; you can redistribute it and/or
 *     modify it under the terms of the GNU General Public License as
 *     published by the Free Software Foundation; either version 2 of
 *     the License, or (at your option) any later version.
 *
 *     This program is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *     GNU General Public License for more details.
 *
 *     You should have received a copy of the GNU General Public License
 *     along with this program; if not, see <http://www.gnu.org/licenses/>.
 *
 ********************************************************************/

#include <linux/proc_fs.h>
#include <linux/init.h>

#include <net/irda/irda.h>
#include <net/irda/irlmp.h>
#include <net/irda/iriap.h>
#include <net/irda/irttp.h>
#include <net/irda/irias_object.h>

#include <net/irda/ircomm_core.h>
#include <net/irda/ircomm_event.h>

static int ircomm_state_idle(struct ircomm_cb *self, IRCOMM_EVENT event,
			     struct sk_buff *skb, struct ircomm_info *info);
static int ircomm_state_waiti(struct ircomm_cb *self, IRCOMM_EVENT event,
			      struct sk_buff *skb, struct ircomm_info *info);
static int ircomm_state_waitr(struct ircomm_cb *self, IRCOMM_EVENT event,
			      struct sk_buff *skb, struct ircomm_info *info);
static int ircomm_state_conn(struct ircomm_cb *self, IRCOMM_EVENT event,
			     struct sk_buff *skb, struct ircomm_info *info);

const char *const ircomm_state[] = {
	"IRCOMM_IDLE",
	"IRCOMM_WAITI",
	"IRCOMM_WAITR",
	"IRCOMM_CONN",
};

static const char *const ircomm_event[] __maybe_unused = {
	"IRCOMM_CONNECT_REQUEST",
	"IRCOMM_CONNECT_RESPONSE",
	"IRCOMM_TTP_CONNECT_INDICATION",
	"IRCOMM_LMP_CONNECT_INDICATION",
	"IRCOMM_TTP_CONNECT_CONFIRM",
	"IRCOMM_LMP_CONNECT_CONFIRM",

	"IRCOMM_LMP_DISCONNECT_INDICATION",
	"IRCOMM_TTP_DISCONNECT_INDICATION",
	"IRCOMM_DISCONNECT_REQUEST",

	"IRCOMM_TTP_DATA_INDICATION",
	"IRCOMM_LMP_DATA_INDICATION",
	"IRCOMM_DATA_REQUEST",
	"IRCOMM_CONTROL_REQUEST",
	"IRCOMM_CONTROL_INDICATION",
};

static int (*state[])(struct ircomm_cb *self, IRCOMM_EVENT event,
		      struct sk_buff *skb, struct ircomm_info *info) =
{
	ircomm_state_idle,
	ircomm_state_waiti,
	ircomm_state_waitr,
	ircomm_state_conn,
};

/*
 * Function ircomm_state_idle (self, event, skb)
 *
 *    IrCOMM is currently idle
 *
 */
static int ircomm_state_idle(struct ircomm_cb *self, IRCOMM_EVENT event,
			     struct sk_buff *skb, struct ircomm_info *info)
{
	int ret = 0;

	switch (event) {
	case IRCOMM_CONNECT_REQUEST:
		ircomm_next_state(self, IRCOMM_WAITI);
		ret = self->issue.connect_request(self, skb, info);
		break;
	case IRCOMM_TTP_CONNECT_INDICATION:
	case IRCOMM_LMP_CONNECT_INDICATION:
		ircomm_next_state(self, IRCOMM_WAITR);
		ircomm_connect_indication(self, skb, info);
		break;
	default:
		pr_debug("%s(), unknown event: %s\n", __func__ ,
			 ircomm_event[event]);
		ret = -EINVAL;
	}
	return ret;
}

/*
 * Function ircomm_state_waiti (self, event, skb)
 *
 *    The IrCOMM user has requested an IrCOMM connection to the remote
 *    device and is awaiting confirmation
 */
static int ircomm_state_waiti(struct ircomm_cb *self, IRCOMM_EVENT event,
			      struct sk_buff *skb, struct ircomm_info *info)
{
	int ret = 0;

	switch (event) {
	case IRCOMM_TTP_CONNECT_CONFIRM:
	case IRCOMM_LMP_CONNECT_CONFIRM:
		ircomm_next_state(self, IRCOMM_CONN);
		ircomm_connect_confirm(self, skb, info);
		break;
	case IRCOMM_TTP_DISCONNECT_INDICATION:
	case IRCOMM_LMP_DISCONNECT_INDICATION:
		ircomm_next_state(self, IRCOMM_IDLE);
		ircomm_disconnect_indication(self, skb, info);
		break;
	default:
		pr_debug("%s(), unknown event: %s\n", __func__ ,
			 ircomm_event[event]);
		ret = -EINVAL;
	}
	return ret;
}

/*
 * Function ircomm_state_waitr (self, event, skb)
 *
 *    IrCOMM has received an incoming connection request and is awaiting
 *    response from the user
 */
static int ircomm_state_waitr(struct ircomm_cb *self, IRCOMM_EVENT event,
			      struct sk_buff *skb, struct ircomm_info *info)
{
	int ret = 0;

	switch (event) {
	case IRCOMM_CONNECT_RESPONSE:
		ircomm_next_state(self, IRCOMM_CONN);
		ret = self->issue.connect_response(self, skb);
		break;
	case IRCOMM_DISCONNECT_REQUEST:
		ircomm_next_state(self, IRCOMM_IDLE);
		ret = self->issue.disconnect_request(self, skb, info);
		break;
	case IRCOMM_TTP_DISCONNECT_INDICATION:
	case IRCOMM_LMP_DISCONNECT_INDICATION:
		ircomm_next_state(self, IRCOMM_IDLE);
		ircomm_disconnect_indication(self, skb, info);
		break;
	default:
		pr_debug("%s(), unknown event = %s\n", __func__ ,
			 ircomm_event[event]);
		ret = -EINVAL;
	}
	return ret;
}

/*
 * Function ircomm_state_conn (self, event, skb)
 *
 *    IrCOMM is connected to the peer IrCOMM device
 *
 */
static int ircomm_state_conn(struct ircomm_cb *self, IRCOMM_EVENT event,
			     struct sk_buff *skb, struct ircomm_info *info)
{
	int ret = 0;

	switch (event) {
	case IRCOMM_DATA_REQUEST:
		ret = self->issue.data_request(self, skb, 0);
		break;
	case IRCOMM_TTP_DATA_INDICATION:
		ircomm_process_data(self, skb);
		break;
	case IRCOMM_LMP_DATA_INDICATION:
		ircomm_data_indication(self, skb);
		break;
	case IRCOMM_CONTROL_REQUEST:
		/* Just send a separate frame for now */
		ret = self->issue.data_request(self, skb, skb->len);
		break;
	case IRCOMM_TTP_DISCONNECT_INDICATION:
	case IRCOMM_LMP_DISCONNECT_INDICATION:
		ircomm_next_state(self, IRCOMM_IDLE);
		ircomm_disconnect_indication(self, skb, info);
		break;
	case IRCOMM_DISCONNECT_REQUEST:
		ircomm_next_state(self, IRCOMM_IDLE);
		ret = self->issue.disconnect_request(self, skb, info);
		break;
	default:
		pr_debug("%s(), unknown event = %s\n", __func__ ,
			 ircomm_event[event]);
		ret = -EINVAL;
	}
	return ret;
}

/*
 * Function ircomm_do_event (self, event, skb)
 *
 *    Process event
 *
 */
int ircomm_do_event(struct ircomm_cb *self, IRCOMM_EVENT event,
		    struct sk_buff *skb, struct ircomm_info *info)
{
	pr_debug("%s: state=%s, event=%s\n", __func__ ,
		 ircomm_state[self->state], ircomm_event[event]);

	return (*state[self->state])(self, event, skb, info);
}

/*
 * Function ircomm_next_state (self, state)
 *
 *    Switch state
 *
 */
void ircomm_next_state(struct ircomm_cb *self, IRCOMM_STATE state)
{
	self->state = state;

	pr_debug("%s: next state=%s, service type=%d\n", __func__ ,
		 ircomm_state[self->state], self->service_type);
}
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 get_or_create_user_for_vnf(keystone_client, vnf_ref): """Get or Create user for VNF Args: keystone_client: keystone client reference vnf_ref: VNF reference used as user name & password, tenant name return False if user retrieved through get return True if user created raise Exception if error during processing """ try: user_id = get_user_id(keystone_client, vnf_ref) tenant_id = get_tenant_id(keystone_client, vnf_ref) created = False if not user_id: user_id = create_user(keystone_client, vnf_ref, vnf_ref, "", tenant_id) created = True try: role_id = get_role_id(keystone_client, 'admin') tenant_id = get_tenant_id(keystone_client, vnf_ref) add_role_user(keystone_client, user_id, role_id, tenant_id) except: logger.warn("Cannot associate user to role admin on tenant") return created except: raise Exception("Impossible to create a user for the VNF {}".format( vnf_ref)) 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