From 868220c566cfd302a38f9a45a75f4dbd4ebbf395 Mon Sep 17 00:00:00 2001 From: tierno Date: Tue, 26 Sep 2017 00:11:05 +0200 Subject: [PATCH] Feature 1413 resiliency to single component failure Feature 645 concurrent access to VIMs Feature 629 horizontal_scale_out_of_VDUs Change-Id: I2a832708e2bf3e4669bbfa999aad869bb15e65b1 Signed-off-by: tierno --- database_utils/migrate_mano_db.sh | 161 +++++- openmano | 28 + openmanod | 4 +- osm_ro/db_base.py | 16 +- osm_ro/httpserver.py | 31 +- osm_ro/nfvo.py | 493 ++++++++++------- osm_ro/nfvo_db.py | 19 +- osm_ro/openmano_schemas.py | 25 + osm_ro/vim_thread.py | 892 ++++++++++++++++++------------ 9 files changed, 1092 insertions(+), 577 deletions(-) diff --git a/database_utils/migrate_mano_db.sh b/database_utils/migrate_mano_db.sh index 557f5978..4a08a423 100755 --- a/database_utils/migrate_mano_db.sh +++ b/database_utils/migrate_mano_db.sh @@ -33,7 +33,7 @@ DBPORT="3306" DBNAME="mano_db" QUIET_MODE="" #TODO update it with the last database version -LAST_DB_VERSION=25 +LAST_DB_VERSION=26 # Detect paths MYSQL=$(which mysql) @@ -193,6 +193,7 @@ fi #[ $OPENMANO_VER_NUM -ge 5020 ] && DB_VERSION=23 #0.5.20 => 23 #[ $OPENMANO_VER_NUM -ge 5021 ] && DB_VERSION=24 #0.5.21 => 24 #[ $OPENMANO_VER_NUM -ge 5022 ] && DB_VERSION=25 #0.5.22 => 25 +#[ $OPENMANO_VER_NUM -ge 5024 ] && DB_VERSION=26 #0.5.24 => 26 #TODO ... put next versions here function upgrade_to_1(){ @@ -850,6 +851,158 @@ function downgrade_from_25(){ sql "DELETE FROM schema_version WHERE version_int='25';" } +function upgrade_to_26(){ + echo " Add name to table datacenter_tenants" + sql "ALTER TABLE datacenter_tenants ADD COLUMN name VARCHAR(255) NULL AFTER uuid;" + sql "UPDATE datacenter_tenants as dt join datacenters as d on dt.datacenter_id = d.uuid set dt.name=d.name;" + echo " Add 'SCHEDULED' to 'status' at tables 'instance_nets', 'instance_vms'" + sql "ALTER TABLE instance_vms CHANGE COLUMN status status ENUM('ACTIVE:NoMgmtIP','ACTIVE','INACTIVE','BUILD',"\ + "'ERROR','VIM_ERROR','PAUSED','SUSPENDED','DELETED','SCHEDULED_CREATION','SCHEDULED_DELETION') "\ + "NOT NULL DEFAULT 'BUILD';" + sql "ALTER TABLE instance_nets CHANGE COLUMN status status ENUM('ACTIVE','INACTIVE','DOWN','BUILD','ERROR',"\ + "'VIM_ERROR','DELETED','SCHEDULED_CREATION','SCHEDULED_DELETION') NOT NULL DEFAULT 'BUILD';" + echo " Enlarge pci at instance_interfaces to allow extended pci for SDN por mapping" + sql "ALTER TABLE instance_interfaces CHANGE COLUMN pci pci VARCHAR(50) NULL DEFAULT NULL COMMENT 'PCI of the "\ + "physical port in the host' AFTER compute_node;" + + for t in flavor image; do + echo " Change 'datacenters_${t}s' to point to datacenter_tenant, add status, vim_info" + sql "ALTER TABLE datacenters_${t}s ADD COLUMN datacenter_vim_id VARCHAR(36) NULL DEFAULT NULL AFTER "\ + "datacenter_id, ADD COLUMN status ENUM('ACTIVE','INACTIVE','BUILD','ERROR','VIM_ERROR','DELETED',"\ + "'SCHEDULED_CREATION','SCHEDULED_DELETION') NOT NULL DEFAULT 'BUILD' AFTER vim_id, ADD COLUMN vim_info "\ + "TEXT NULL AFTER status;" + sql "UPDATE datacenters_${t}s as df left join datacenter_tenants as dt on dt.datacenter_id=df.datacenter_id "\ + "set df.datacenter_vim_id=dt.uuid;" + sql "DELETE FROM datacenters_${t}s WHERE datacenter_vim_id is NULL;" + sql "ALTER TABLE datacenters_${t}s CHANGE COLUMN datacenter_vim_id datacenter_vim_id VARCHAR(36) NOT NULL;" + sql "ALTER TABLE datacenters_${t}s ADD CONSTRAINT FK_datacenters_${t}s_datacenter_tenants FOREIGN KEY "\ + "(datacenter_vim_id) REFERENCES datacenter_tenants (uuid) ON UPDATE CASCADE ON DELETE CASCADE;" + sql "ALTER TABLE datacenters_${t}s DROP FOREIGN KEY FK__datacenters_${t:0:1};" + sql "ALTER TABLE datacenters_${t}s DROP COLUMN datacenter_id;" + done + + echo " Decoupling 'instance_interfaces' from scenarios/vnfs to allow scale actions" + sql "ALTER TABLE instance_interfaces CHANGE COLUMN vim_interface_id vim_interface_id VARCHAR(128) NULL DEFAULT NULL;" + sql "ALTER TABLE instance_interfaces CHANGE COLUMN interface_id interface_id VARCHAR(36) NULL DEFAULT NULL;" + sql "ALTER TABLE instance_interfaces DROP FOREIGN KEY FK_instance_ids" + sql "ALTER TABLE instance_interfaces ADD CONSTRAINT FK_instance_ids FOREIGN KEY (interface_id) "\ + "REFERENCES interfaces (uuid) ON UPDATE CASCADE ON DELETE SET NULL;" + + echo " Decoupling 'instance_vms' from scenarios/vnfs to allow scale actions" + sql "ALTER TABLE instance_vms CHANGE COLUMN vim_vm_id vim_vm_id VARCHAR(128) NULL DEFAULT NULL;" + sql "ALTER TABLE instance_vms CHANGE COLUMN vm_id vm_id VARCHAR(36) NULL DEFAULT NULL;" + sql "ALTER TABLE instance_vms DROP FOREIGN KEY FK_instance_vms_vms;" + sql "ALTER TABLE instance_vms ADD CONSTRAINT FK_instance_vms_vms FOREIGN KEY (vm_id) "\ + "REFERENCES vms (uuid) ON UPDATE CASCADE ON DELETE SET NULL;" + + echo " Decoupling 'instance_nets' from scenarios/vnfs to allow scale actions" + sql "ALTER TABLE instance_nets CHANGE COLUMN vim_net_id vim_net_id VARCHAR(128) NULL DEFAULT NULL;" + + echo " Decoupling 'instance_scenarios' from scenarios" + sql "ALTER TABLE instance_scenarios CHANGE COLUMN scenario_id scenario_id VARCHAR(36) NULL DEFAULT NULL;" + sql "ALTER TABLE instance_scenarios DROP FOREIGN KEY FK_instance_scenarios_scenarios;" + sql "ALTER TABLE instance_scenarios ADD CONSTRAINT FK_instance_scenarios_scenarios FOREIGN KEY (scenario_id) "\ + "REFERENCES scenarios (uuid) ON UPDATE CASCADE ON DELETE SET NULL;" + + echo " Create table instance_actions, vim_actions" + sql "CREATE TABLE IF NOT EXISTS instance_actions ( + uuid VARCHAR(36) NOT NULL, + tenant_id VARCHAR(36) NULL DEFAULT NULL, + instance_id VARCHAR(36) NULL DEFAULT NULL, + description VARCHAR(64) NULL DEFAULT NULL COMMENT 'CREATE, DELETE, SCALE OUT/IN, ...', + number_tasks SMALLINT(6) NOT NULL DEFAULT '1', + number_done SMALLINT(6) NOT NULL DEFAULT '0', + number_failed SMALLINT(6) NOT NULL DEFAULT '0', + created_at DOUBLE NOT NULL, + modified_at DOUBLE NULL DEFAULT NULL, + PRIMARY KEY (uuid), + INDEX FK_actions_tenants (tenant_id), + CONSTRAINT FK_actions_tenant FOREIGN KEY (tenant_id) REFERENCES nfvo_tenants (uuid) ON UPDATE CASCADE ON DELETE CASCADE) + COMMENT='Contains client actions over instances' + COLLATE='utf8_general_ci' + ENGINE=InnoDB;" + + sql "CREATE TABLE IF NOT EXISTS vim_actions ( + instance_action_id VARCHAR(36) NOT NULL, + task_index INT(6) NOT NULL, + datacenter_vim_id VARCHAR(36) NOT NULL, + vim_id VARCHAR(64) NULL DEFAULT NULL, + action VARCHAR(36) NOT NULL COMMENT 'CREATE,DELETE,START,STOP...', + item ENUM('datacenters_flavors','datacenter_images','instance_nets','instance_vms','instance_interfaces') NOT NULL COMMENT 'table where the item is stored', + item_id VARCHAR(36) NULL DEFAULT NULL COMMENT 'uuid of the entry in the table', + status ENUM('SCHEDULED', 'BUILD', 'DONE', 'FAILED', 'SUPERSEDED') NOT NULL DEFAULT 'SCHEDULED', + extra TEXT NULL DEFAULT NULL COMMENT 'json with params:, depends_on: for the task', + error_msg VARCHAR(1024) NULL DEFAULT NULL, + created_at DOUBLE NOT NULL, + modified_at DOUBLE NULL DEFAULT NULL, + PRIMARY KEY (task_index, instance_action_id), + INDEX FK_actions_instance_actions (instance_action_id), + CONSTRAINT FK_actions_instance_actions FOREIGN KEY (instance_action_id) REFERENCES instance_actions (uuid) ON UPDATE CASCADE ON DELETE CASCADE, + INDEX FK_actions_vims (datacenter_vim_id), + CONSTRAINT FK_actions_vims FOREIGN KEY (datacenter_vim_id) REFERENCES datacenter_tenants (uuid) ON UPDATE CASCADE ON DELETE CASCADE) + COMMENT='Table with the individual VIM actions.' + COLLATE='utf8_general_ci' + ENGINE=InnoDB;" + + sql "INSERT INTO schema_version (version_int, version, openmano_ver, comments, date) "\ + "VALUES (26, '0.26', '0.5.23', 'Several changes', '2017-09-09');" +} +function downgrade_from_26(){ + echo " Remove name from table datacenter_tenants" + sql "ALTER TABLE datacenter_tenants DROP COLUMN name;" + echo " Remove 'SCHEDULED' from the 'status' at tables 'instance_nets', 'instance_vms'" + sql "ALTER TABLE instance_vms CHANGE COLUMN status status ENUM('ACTIVE:NoMgmtIP','ACTIVE','INACTIVE','BUILD',"\ + "'ERROR','VIM_ERROR','PAUSED','SUSPENDED','DELETED') NOT NULL DEFAULT 'BUILD';" + sql "ALTER TABLE instance_nets CHANGE COLUMN status status ENUM('ACTIVE','DOWN','BUILD','ERROR','VIM_ERROR',"\ + "'INACTIVE','DELETED') NOT NULL DEFAULT 'BUILD';" + echo " Shorten back pci at instance_interfaces to allow extended pci for SDN por mapping" + sql "ALTER TABLE instance_interfaces CHANGE COLUMN pci pci VARCHAR(12) NULL DEFAULT NULL COMMENT 'PCI of the "\ + "physical port in the host' AFTER compute_node;" + + for t in flavor image; do + echo " Restore back 'datacenters_${t}s'" + sql "ALTER TABLE datacenters_${t}s ADD COLUMN datacenter_id VARCHAR(36) NULL DEFAULT NULL AFTER "\ + "${t}_id, DROP COLUMN status, DROP COLUMN vim_info ;" + sql "UPDATE datacenters_${t}s as df left join datacenter_tenants as dt on dt.uuid=df.datacenter_vim_id set "\ + "df.datacenter_id=dt.datacenter_id;" + sql "ALTER TABLE datacenters_${t}s CHANGE COLUMN datacenter_id datacenter_id VARCHAR(36) NOT NULL;" + sql "ALTER TABLE datacenters_${t}s ADD CONSTRAINT FK__datacenters_${t:0:1} FOREIGN KEY "\ + "(datacenter_id) REFERENCES datacenters (uuid), DROP FOREIGN KEY FK_datacenters_${t}s_datacenter_tenants, "\ + "DROP COLUMN datacenter_vim_id;" + done + + echo " Restore back 'instance_interfaces' coupling to scenarios/vnfs" + sql "ALTER TABLE instance_interfaces CHANGE COLUMN vim_interface_id vim_interface_id VARCHAR(36) NULL DEFAULT NULL;" + sql "ALTER TABLE instance_interfaces DROP FOREIGN KEY FK_instance_ids" + sql "ALTER TABLE instance_interfaces CHANGE COLUMN interface_id interface_id VARCHAR(36) NOT NULL;" + sql "ALTER TABLE instance_interfaces ADD CONSTRAINT FK_instance_ids FOREIGN KEY (interface_id) "\ + "REFERENCES interfaces (uuid);" + + echo " Restore back 'instance_vms' coupling to scenarios/vnfs" + echo " Decoupling 'instance vms' from scenarios/vnfs to allow scale actions" + sql "UPDATE instance_vms SET vim_vm_id='' WHERE vim_vm_id is NULL;" + sql "ALTER TABLE instance_vms CHANGE COLUMN vim_vm_id vim_vm_id VARCHAR(36) NOT NULL;" + sql "ALTER TABLE instance_vms DROP FOREIGN KEY FK_instance_vms_vms;" + sql "ALTER TABLE instance_vms CHANGE COLUMN vm_id vm_id VARCHAR(36) NOT NULL;" + sql "ALTER TABLE instance_vms ADD CONSTRAINT FK_instance_vms_vms FOREIGN KEY (vm_id) "\ + "REFERENCES vms (uuid);" + + echo " Restore back 'instance_nets' coupling to scenarios/vnfs" + sql "UPDATE instance_nets SET vim_net_id='' WHERE vim_net_id is NULL;" + sql "ALTER TABLE instance_nets CHANGE COLUMN vim_net_id vim_net_id VARCHAR(36) NOT NULL;" + + echo " Restore back 'instance_scenarios' coupling to scenarios" + sql "ALTER TABLE instance_scenarios DROP FOREIGN KEY FK_instance_scenarios_scenarios;" + sql "ALTER TABLE instance_scenarios CHANGE COLUMN scenario_id scenario_id VARCHAR(36) NOT NULL;" + sql "ALTER TABLE instance_scenarios ADD CONSTRAINT FK_instance_scenarios_scenarios FOREIGN KEY (scenario_id) "\ + "REFERENCES scenarios (uuid);" + + echo " Delete table instance_actions" + sql "DROP TABLE vim_actions" + sql "DROP TABLE instance_actions" + sql "DELETE FROM schema_version WHERE version_int='26';" +} + function upgrade_to_X(){ echo " change 'datacenter_nets'" sql "ALTER TABLE datacenter_nets ADD COLUMN vim_tenant_id VARCHAR(36) NOT NULL AFTER datacenter_id, DROP INDEX name_datacenter_id, ADD UNIQUE INDEX name_datacenter_id (name, datacenter_id, vim_tenant_id);" @@ -870,14 +1023,14 @@ mysqldump $DEF_EXTRA_FILE_PARAM --add-drop-table --add-drop-database --routines function rollback_db() { - cat $TEMPFILE2 | mysql $DEF_EXTRA_FILE_PARAM && echo " Rollback database OK" || - echo " Rollback database FAIL" + cat $TEMPFILE2 | mysql $DEF_EXTRA_FILE_PARAM && echo " Aborted! Rollback database OK" || + echo " Aborted! Rollback database FAIL" exit 1 } function sql() # send a sql command { - echo "$*" | $DBCMD || ! echo " ERROR. Aborted!" || rollback_db + echo "$*" | $DBCMD || ! echo " ERROR with command '$*'" || rollback_db return 0 } diff --git a/openmano b/openmano index 26ef9b93..e2221bc4 100755 --- a/openmano +++ b/openmano @@ -890,6 +890,28 @@ def instance_scenario_delete(args): print content['error']['description'] return result +def get_action(args): + if not args.all: + tenant = _get_tenant() + else: + tenant = "any" + if not args.instance: + instance_id = "any" + else: + instance_id =args.instance + action_id = "" + if args.id: + action_id = "/" + args.id + URLrequest = "http://{}:{}/openmano/{}/instances/{}/action{}".format(mano_host, mano_port, tenant, instance_id, + action_id) + mano_response = requests.get(URLrequest) + logger.debug("openmano response: %s", mano_response.text ) + if args.verbose == None: + args.verbose = 0 + if args.id != None: + args.verbose += 1 + return _print_verbose(mano_response, args.verbose) + def instance_scenario_action(args): #print "instance-scenario-action", args tenant = _get_tenant() @@ -1752,6 +1774,12 @@ if __name__=="__main__": instance_scenario_action_parser.add_argument("--vm", action="append", help="VM to act on (can use several entries)") instance_scenario_action_parser.set_defaults(func=instance_scenario_action) + action_parser = subparsers.add_parser('action-list', parents=[parent_parser], help="get action over an instance status") + action_parser.add_argument("id", nargs='?', action="store", help="action id") + action_parser.add_argument("--instance", action="store", help="fitler by this instance_id") + action_parser.add_argument("--all", action="store", help="Not filter by tenant") + action_parser.set_defaults(func=get_action) + #instance_scenario_status_parser = subparsers.add_parser('instance-scenario-status', help="show the status of a scenario instance") #instance_scenario_status_parser.add_argument("name", action="store", help="name or uuid of the scenario instance") #instance_scenario_status_parser.set_defaults(func=instance_scenario_status) diff --git a/openmanod b/openmanod index d3efe223..39117f7b 100755 --- a/openmanod +++ b/openmanod @@ -48,9 +48,9 @@ import osm_ro __author__ = "Alfonso Tierno, Gerardo Garcia, Pablo Montes" __date__ = "$26-aug-2014 11:09:29$" -__version__ = "0.5.23-r533" +__version__ = "0.5.24-r534" version_date = "Sep 2017" -database_version = 25 # expected database schema version +database_version = 26 # expected database schema version global global_config global logger diff --git a/osm_ro/db_base.py b/osm_ro/db_base.py index 26e4c002..badf5089 100644 --- a/osm_ro/db_base.py +++ b/osm_ro/db_base.py @@ -271,16 +271,22 @@ class db_base(): return json.dumps(str(data)) def __tuple2db_format_set(self, data): - '''Compose the needed text for a SQL SET, parameter 'data' is a pair tuple (A,B), + """Compose the needed text for a SQL SET, parameter 'data' is a pair tuple (A,B), and it returns the text 'A="B"', where A is a field of a table and B is the value If B is None it returns the 'A=Null' text, without surrounding Null by quotes If B is not None it returns the text "A='B'" or 'A="B"' where B is surrounded by quotes, and it ensures internal quotes of B are escaped. - ''' - if data[1]==None: + B can be also a dict with special keys: + {"INCREMENT": NUMBER}, then it produce "A=A+NUMBER" + """ + if data[1] == None: return str(data[0]) + "=Null" elif isinstance(data[1], str): return str(data[0]) + '=' + json.dumps(data[1]) + elif isinstance(data[1], dict): + if "INCREMENT" in data[1]: + return "{A}={A}{N:+d}".format(A=data[0], N=data[1]["INCREMENT"]) + raise db_base_Exception("Format error for UPDATE field") else: return str(data[0]) + '=' + json.dumps(str(data[1])) @@ -540,7 +546,7 @@ class db_base(): 'WHERE_OR': dict of key:values, translated to key=value OR ... (Optional) 'WHERE_AND_OR: str 'AND' or 'OR'(by default) mark the priority to 'WHERE AND (WHERE_OR)' or (WHERE) OR WHERE_OR' (Optional) 'LIMIT': limit of number of rows (Optional) - 'ORDER_BY': list or tuple of fields to order + 'ORDER_BY': list or tuple of fields to order, add ' DESC' to each item if inverse order is required Return: a list with dictionaries at each row ''' #print sql_dict @@ -573,7 +579,7 @@ class db_base(): where_ = "" #print 'where_', where_ limit_ = "LIMIT " + str(sql_dict['LIMIT']) if 'LIMIT' in sql_dict else "" - order_ = "ORDER BY " + ",".join(map(str,sql_dict['SELECT'])) if 'ORDER_BY' in sql_dict else "" + order_ = "ORDER BY " + ",".join(map(str,sql_dict['ORDER_BY'])) if 'ORDER_BY' in sql_dict else "" #print 'limit_', limit_ cmd = " ".join( (select_, from_, where_, limit_, order_) ) diff --git a/osm_ro/httpserver.py b/osm_ro/httpserver.py index 66b744a1..d77846c8 100644 --- a/osm_ro/httpserver.py +++ b/osm_ro/httpserver.py @@ -1478,7 +1478,12 @@ def http_delete_instance_id(tenant_id, instance_id): @bottle.route(url_base + '//instances//action', method='POST') def http_post_instance_scenario_action(tenant_id, instance_id): - '''take an action over a scenario instance''' + """ + take an action over a scenario instance + :param tenant_id: tenant where user belongs to + :param instance_id: instance indentity + :return: + """ logger.debug('FROM %s %s %s', bottle.request.remote_addr, bottle.request.method, bottle.request.url) # parse input data http_content, _ = format_in(instance_scenario_action_schema) @@ -1505,6 +1510,30 @@ def http_post_instance_scenario_action(tenant_id, instance_id): bottle.abort(HTTP_Internal_Server_Error, type(e).__name__ + ": " + str(e)) +@bottle.route(url_base + '//instances//action', method='GET') +@bottle.route(url_base + '//instances//action/', method='GET') +def http_get_instance_scenario_action(tenant_id, instance_id, action_id=None): + """ + List the actions done over an instance, or the action details + :param tenant_id: tenant where user belongs to. Can be "any" to ignore + :param instance_id: instance id, can be "any" to get actions of all instances + :return: + """ + logger.debug('FROM %s %s %s', bottle.request.remote_addr, bottle.request.method, bottle.request.url) + try: + # check valid tenant_id + if tenant_id != "any": + nfvo.check_tenant(mydb, tenant_id) + data = nfvo.instance_action_get(mydb, tenant_id, instance_id, action_id) + return format_out(data) + except (nfvo.NfvoException, db_base_Exception) as e: + logger.error("http_get_instance_scenario_action error {}: {}".format(e.http_code, str(e))) + bottle.abort(e.http_code, str(e)) + except Exception as e: + logger.error("Unexpected exception: ", exc_info=True) + bottle.abort(HTTP_Internal_Server_Error, type(e).__name__ + ": " + str(e)) + + @bottle.error(400) @bottle.error(401) @bottle.error(404) diff --git a/osm_ro/nfvo.py b/osm_ro/nfvo.py index 2c6a5a3d..d5d2dc66 100644 --- a/osm_ro/nfvo.py +++ b/osm_ro/nfvo.py @@ -43,7 +43,7 @@ from db_base import db_base_Exception import nfvo_db from threading import Lock -from time import time +import time as t from lib_osm_openvim import ovim as ovim_module from lib_osm_openvim.ovim import ovimException @@ -67,10 +67,9 @@ vim_threads = {"running":{}, "deleting": {}, "names": []} # threads running vim_persistent_info = {} logger = logging.getLogger('openmano.nfvo') task_lock = Lock() -global_instance_tasks = {} last_task_id = 0.0 -db=None -db_lock=Lock() +db = None +db_lock = Lock() class NfvoException(Exception): def __init__(self, message, http_code): @@ -80,14 +79,16 @@ class NfvoException(Exception): def get_task_id(): global last_task_id - task_id = time() + task_id = t.time() if task_id <= last_task_id: task_id = last_task_id + 0.000001 last_task_id = task_id - return "TASK.{:.6f}".format(task_id) + return "ACTION-{:.6f}".format(task_id) + # return (t.strftime("%Y%m%dT%H%M%S.{}%Z", t.localtime(task_id))).format(int((task_id % 1)*1e6)) def new_task(name, params, depends=None): + """Deprected!!!""" task_id = get_task_id() task = {"status": "enqueued", "id": task_id, "name": name, "params": params} if depends: @@ -96,7 +97,7 @@ def new_task(name, params, depends=None): def is_task_id(id): - return True if id[:5] == "TASK." else False + return True if id[:5] == "TASK-" else False def get_non_used_vim_name(datacenter_name, datacenter_id, tenant_name, tenant_id): @@ -208,7 +209,7 @@ def stop_service(): if ovim: ovim.stop_service() for thread_id,thread in vim_threads["running"].items(): - thread.insert_task(new_task("exit", None)) + thread.insert_task("exit") vim_threads["deleting"][thread_id] = thread vim_threads["running"] = {} if global_config and global_config.get("console_thread"): @@ -347,7 +348,7 @@ def rollback(mydb, vims, rollback_list): try: if item["what"]=="image": vim.delete_image(item["uuid"]) - mydb.delete_row(FROM="datacenters_images", WHERE={"datacenter_id": vim["id"], "vim_id":item["uuid"]}) + mydb.delete_row(FROM="datacenters_images", WHERE={"datacenter_vim_id": vim["id"], "vim_id":item["uuid"]}) elif item["what"]=="flavor": vim.delete_flavor(item["uuid"]) mydb.delete_row(FROM="datacenters_flavors", WHERE={"datacenter_id": vim["id"], "vim_id":item["uuid"]}) @@ -514,9 +515,11 @@ def create_or_use_image(mydb, vims, image_dict, rollback_list, only_create_at_vi rollback_list.append({"where":"mano", "what":"image","uuid":image_mano_id}) #create image at every vim for vim_id,vim in vims.iteritems(): + datacenter_vim_id = vim["config"]["datacenter_tenant_id"] image_created="false" #look at database - image_db = mydb.get_rows(FROM="datacenters_images", WHERE={'datacenter_id':vim_id, 'image_id':image_mano_id}) + image_db = mydb.get_rows(FROM="datacenters_images", + WHERE={'datacenter_vim_id': datacenter_vim_id, 'image_id': image_mano_id}) #look at VIM if this image exist try: if image_dict['location'] is not None: @@ -565,10 +568,13 @@ def create_or_use_image(mydb, vims, image_dict, rollback_list, only_create_at_vi #if we reach here, the image has been created or existed if len(image_db)==0: #add new vim_id at datacenters_images - mydb.new_row('datacenters_images', {'datacenter_id':vim_id, 'image_id':image_mano_id, 'vim_id': image_vim_id, 'created':image_created}) + mydb.new_row('datacenters_images', {'datacenter_vim_id': datacenter_vim_id, + 'image_id':image_mano_id, + 'vim_id': image_vim_id, + 'created':image_created}) elif image_db[0]["vim_id"]!=image_vim_id: #modify existing vim_id at datacenters_images - mydb.update_rows('datacenters_images', UPDATE={'vim_id':image_vim_id}, WHERE={'datacenter_id':vim_id, 'image_id':image_mano_id}) + mydb.update_rows('datacenters_images', UPDATE={'vim_id':image_vim_id}, WHERE={'datacenter_vim_id':vim_id, 'image_id':image_mano_id}) return image_vim_id if only_create_at_vim else image_mano_id @@ -627,9 +633,11 @@ def create_or_use_flavor(mydb, vims, flavor_dict, rollback_list, only_create_at_ del flavor_dict['uuid'] flavor_vim_id=None for vim_id,vim in vims.items(): + datacenter_vim_id = vim["config"]["datacenter_tenant_id"] flavor_created="false" #look at database - flavor_db = mydb.get_rows(FROM="datacenters_flavors", WHERE={'datacenter_id':vim_id, 'flavor_id':flavor_mano_id}) + flavor_db = mydb.get_rows(FROM="datacenters_flavors", + WHERE={'datacenter_vim_id': datacenter_vim_id, 'flavor_id': flavor_mano_id}) #look at VIM if this flavor exist SKIPPED #res_vim, flavor_vim_id = vim.get_flavor_id_from_path(flavor_dict['location']) #if res_vim < 0: @@ -719,11 +727,12 @@ def create_or_use_flavor(mydb, vims, flavor_dict, rollback_list, only_create_at_ extended_devices['disks'] = disk_list extended_devices_yaml = yaml.safe_dump(extended_devices,default_flow_style=True,width=256) mydb.new_row('datacenters_flavors', - {'datacenter_id':vim_id, 'flavor_id':flavor_mano_id, 'vim_id': flavor_vim_id, - 'created':flavor_created,'extended': extended_devices_yaml}) + {'datacenter_vim_id': datacenter_vim_id, 'flavor_id': flavor_mano_id, 'vim_id': flavor_vim_id, + 'created': flavor_created, 'extended': extended_devices_yaml}) elif flavor_db[0]["vim_id"]!=flavor_vim_id: #modify existing vim_id at datacenters_flavors - mydb.update_rows('datacenters_flavors', UPDATE={'vim_id':flavor_vim_id}, WHERE={'datacenter_id':vim_id, 'flavor_id':flavor_mano_id}) + mydb.update_rows('datacenters_flavors', UPDATE={'vim_id':flavor_vim_id}, + WHERE={'datacenter_vim_id': datacenter_vim_id, 'flavor_id': flavor_mano_id}) return flavor_vim_id if only_create_at_vim else flavor_mano_id @@ -1468,7 +1477,7 @@ def delete_vnf(mydb,tenant_id,vnf_id,datacenter=None,vim_tenant=None): #delelte at VIM c = mydb.get_rows(FROM='datacenters_flavors', WHERE={'flavor_id':flavor}) for flavor_vim in c: - if flavor_vim["datacenter_id"] not in vims: + if flavor_vim["datacenter_vim_id"] not in vims: # TODO change to datacenter_tenant_id continue if flavor_vim['created']=='false': #skip this flavor because not created by openmano continue @@ -1499,7 +1508,7 @@ def delete_vnf(mydb,tenant_id,vnf_id,datacenter=None,vim_tenant=None): #delelte at VIM c = mydb.get_rows(FROM='datacenters_images', WHERE={'image_id':image}) for image_vim in c: - if image_vim["datacenter_id"] not in vims: + if image_vim["datacenter_vim_id"] not in vims: # TODO change to datacenter_tenant_id continue if image_vim['created']=='false': #skip this image because not created by openmano continue @@ -2165,7 +2174,7 @@ def start_scenario(mydb, tenant_id, scenario_id, instance_scenario_name, instanc rollbackList=[] try: #print "Checking that the scenario_id exists and getting the scenario dictionary" - scenarioDict = mydb.get_scenario(scenario_id, tenant_id, datacenter_id) + scenarioDict = mydb.get_scenario(scenario_id, tenant_id, datacenter_id=datacenter_id) scenarioDict['datacenter2tenant'] = { datacenter_id: myvim['config']['datacenter_tenant_id'] } scenarioDict['datacenter_id'] = datacenter_id #print '================scenarioDict=======================' @@ -2533,28 +2542,31 @@ def create_instance(mydb, tenant_id, instance_dict): # logger.debug("Creating instance...") scenario = instance_dict["scenario"] - #find main datacenter + # find main datacenter myvims = {} myvim_threads_id = {} - instance_tasks={} - tasks_to_launch={} datacenter = instance_dict.get("datacenter") default_datacenter_id, vim = get_datacenter_by_name_uuid(mydb, tenant_id, datacenter) myvims[default_datacenter_id] = vim myvim_threads_id[default_datacenter_id], _ = get_vim_thread(mydb, tenant_id, default_datacenter_id) - tasks_to_launch[myvim_threads_id[default_datacenter_id]] = [] - #myvim_tenant = myvim['tenant_id'] -# default_datacenter_name = vim['name'] + # myvim_tenant = myvim['tenant_id'] rollbackList=[] - #print "Checking that the scenario exists and getting the scenario dictionary" - scenarioDict = mydb.get_scenario(scenario, tenant_id, default_datacenter_id) + # print "Checking that the scenario exists and getting the scenario dictionary" + scenarioDict = mydb.get_scenario(scenario, tenant_id, datacenter_vim_id=myvim_threads_id[default_datacenter_id], + datacenter_id=default_datacenter_id) - #logger.debug(">>>>>>> Dictionaries before merging") - #logger.debug(">>>>>>> InstanceDict:\n{}".format(yaml.safe_dump(instance_dict,default_flow_style=False, width=256))) - #logger.debug(">>>>>>> ScenarioDict:\n{}".format(yaml.safe_dump(scenarioDict,default_flow_style=False, width=256))) + # logger.debug(">>>>>> Dictionaries before merging") + # logger.debug(">>>>>> InstanceDict:\n{}".format(yaml.safe_dump(instance_dict,default_flow_style=False, width=256))) + # logger.debug(">>>>>> ScenarioDict:\n{}".format(yaml.safe_dump(scenarioDict,default_flow_style=False, width=256))) + db_instance_vnfs = [] + db_instance_vms = [] + db_instance_interfaces = [] + db_ip_profiles = [] + db_vim_actions = [] uuid_list = [] + task_index = 0 instance_name = instance_dict["name"] instance_uuid = str(uuid4()) uuid_list.append(instance_uuid) @@ -2567,47 +2579,55 @@ def create_instance(mydb, tenant_id, instance_dict): # filled bellow 'datacenter_tenant_id' "description": instance_dict.get("description"), } - db_ip_profiles=[] if scenarioDict.get("cloud-config"): db_instance_scenario["cloud_config"] = yaml.safe_dump(scenarioDict["cloud-config"], default_flow_style=True, width=256) + instance_action_id = get_task_id() + db_instance_action = { + "uuid": instance_action_id, # same uuid for the instance and the action on create + "tenant_id": tenant_id, + "instance_id": instance_uuid, + "description": "CREATE", + } - vnf_net2instance = {} #Auxiliar dictionary. First key:'scenario' or sce_vnf uuid. Second Key: uuid of the net/sce_net. Value: vim_net_id + # Auxiliary dictionaries from x to y + vnf_net2instance = {} sce_net2instance = {} - auxNetDict = {} #Auxiliar dictionary. First key:'scenario' or sce_vnf uuid. Second Key: uuid of the net/sce_net. Value: vim_net_id - auxNetDict['scenario'] = {} + net2task_id = {'scenario': {}} - logger.debug("Creating instance from scenario-dict:\n%s", yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False)) #TODO remove + # logger.debug("Creating instance from scenario-dict:\n%s", + # yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False)) try: # 0 check correct parameters - for net_name, net_instance_desc in instance_dict.get("networks",{}).iteritems(): + for net_name, net_instance_desc in instance_dict.get("networks", {}).iteritems(): found = False for scenario_net in scenarioDict['nets']: if net_name == scenario_net["name"]: found = True break if not found: - raise NfvoException("Invalid scenario network name '{}' at instance:networks".format(net_name), HTTP_Bad_Request) + raise NfvoException("Invalid scenario network name '{}' at instance:networks".format(net_name), + HTTP_Bad_Request) if "sites" not in net_instance_desc: net_instance_desc["sites"] = [ {} ] site_without_datacenter_field = False for site in net_instance_desc["sites"]: if site.get("datacenter"): if site["datacenter"] not in myvims: - #Add this datacenter to myvims + # Add this datacenter to myvims d, v = get_datacenter_by_name_uuid(mydb, tenant_id, site["datacenter"]) myvims[d] = v - myvim_threads_id[d],_ = get_vim_thread(mydb, tenant_id, site["datacenter"]) - tasks_to_launch[myvim_threads_id[d]] = [] - site["datacenter"] = d #change name to id + myvim_threads_id[d], _ = get_vim_thread(mydb, tenant_id, site["datacenter"]) + site["datacenter"] = d # change name to id else: if site_without_datacenter_field: - raise NfvoException("Found more than one entries without datacenter field at instance:networks:{}:sites".format(net_name), HTTP_Bad_Request) + raise NfvoException("Found more than one entries without datacenter field at " + "instance:networks:{}:sites".format(net_name), HTTP_Bad_Request) site_without_datacenter_field = True - site["datacenter"] = default_datacenter_id #change name to id + site["datacenter"] = default_datacenter_id # change name to id for vnf_name, vnf_instance_desc in instance_dict.get("vnfs",{}).iteritems(): - found=False + found = False for scenario_vnf in scenarioDict['vnfs']: if vnf_name == scenario_vnf['name']: found = True @@ -2615,20 +2635,19 @@ def create_instance(mydb, tenant_id, instance_dict): if not found: raise NfvoException("Invalid vnf name '{}' at instance:vnfs".format(vnf_instance_desc), HTTP_Bad_Request) if "datacenter" in vnf_instance_desc: - # Add this datacenter to myvims + # Add this datacenter to myvims if vnf_instance_desc["datacenter"] not in myvims: d, v = get_datacenter_by_name_uuid(mydb, tenant_id, vnf_instance_desc["datacenter"]) myvims[d] = v - myvim_threads_id[d],_ = get_vim_thread(mydb, tenant_id, vnf_instance_desc["datacenter"]) - tasks_to_launch[myvim_threads_id[d]] = [] + myvim_threads_id[d], _ = get_vim_thread(mydb, tenant_id, vnf_instance_desc["datacenter"]) scenario_vnf["datacenter"] = vnf_instance_desc["datacenter"] - #0.1 parse cloud-config parameters + # 0.1 parse cloud-config parameters cloud_config = unify_cloud_config(instance_dict.get("cloud-config"), scenarioDict.get("cloud-config")) - #0.2 merge instance information into scenario - #Ideally, the operation should be as simple as: update(scenarioDict,instance_dict) - #However, this is not possible yet. + # 0.2 merge instance information into scenario + # Ideally, the operation should be as simple as: update(scenarioDict,instance_dict) + # However, this is not possible yet. for net_name, net_instance_desc in instance_dict.get("networks",{}).iteritems(): for scenario_net in scenarioDict['nets']: if net_name == scenario_net["name"]: @@ -2658,16 +2677,17 @@ def create_instance(mydb, tenant_id, instance_dict): if interface['vnf_interface'] == vnf_interface['external_name']: vnf_interface['ip_address']=interface['ip_address'] - #logger.debug(">>>>>>>> Merged dictionary") - logger.debug("Creating instance scenario-dict MERGED:\n%s", yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False)) + # logger.debug(">>>>>>>> Merged dictionary") + # logger.debug("Creating instance scenario-dict MERGED:\n%s", + # yaml.safe_dump(scenarioDict, indent=4, default_flow_style=False)) # 1. Creating new nets (sce_nets) in the VIM" db_instance_nets = [] for sce_net in scenarioDict['nets']: - descriptor_net = instance_dict.get("networks",{}).get(sce_net["name"],{}) + descriptor_net = instance_dict.get("networks", {}).get(sce_net["name"], {}) net_name = descriptor_net.get("vim-network-name") sce_net2instance[sce_net['uuid']] = {} - auxNetDict['scenario'][sce_net['uuid']] = {} + net2task_id['scenario'][sce_net['uuid']] = {} sites = descriptor_net.get("sites", [ {} ]) for site in sites: @@ -2680,7 +2700,7 @@ def create_instance(mydb, tenant_id, instance_dict): datacenter_id = default_datacenter_id myvim_thread_id = myvim_threads_id[default_datacenter_id] net_type = sce_net['type'] - lookfor_filter = {'admin_state_up': True, 'status': 'ACTIVE'} #'shared': True + lookfor_filter = {'admin_state_up': True, 'status': 'ACTIVE'} # 'shared': True if not net_name: if sce_net["external"]: @@ -2707,14 +2727,15 @@ def create_instance(mydb, tenant_id, instance_dict): net_vim_name = site["netmap-create"] elif sce_net["external"]: if sce_net['vim_id'] != None: - #there is a netmap at datacenter_nets database #TODO REVISE!!!! + # there is a netmap at datacenter_nets database # TODO REVISE!!!! create_network = False lookfor_network = True lookfor_filter["id"] = sce_net['vim_id'] - filter_text = "vim_id '%s' datacenter_netmap name '%s'. Try to reload vims with datacenter-net-update" % (sce_net['vim_id'], sce_net["name"]) - #look for network at datacenter and return error + filter_text = "vim_id '{}' datacenter_netmap name '{}'. Try to reload vims with "\ + "datacenter-net-update".format(sce_net['vim_id'], sce_net["name"]) + # look for network at datacenter and return error else: - #There is not a netmap, look at datacenter for a net with this name and create if not found + # There is not a netmap, look at datacenter for a net with this name and create if not found create_network = True lookfor_network = True lookfor_filter["name"] = sce_net["name"] @@ -2725,30 +2746,16 @@ def create_instance(mydb, tenant_id, instance_dict): create_network = True lookfor_network = False - - - if lookfor_network: - vim_nets = vim.get_network_list(filter_dict=lookfor_filter) - if len(vim_nets) > 1: - raise NfvoException("More than one candidate VIM network found for " + filter_text, HTTP_Bad_Request ) - elif len(vim_nets) == 0: - if not create_network: - raise NfvoException("No candidate VIM network found for " + filter_text, HTTP_Bad_Request ) - else: - vim_id = vim_nets[0]['id'] - auxNetDict['scenario'][sce_net['uuid']][datacenter_id] = vim_nets[0]['id'] - create_network = False - if create_network: - #if network is not external - task = new_task("new-net", (net_vim_name, net_type, sce_net.get('ip_profile',None))) - task_id = task["id"] - instance_tasks[task_id] = task - tasks_to_launch[myvim_thread_id].append(task) - #network_id = vim.new_network(net_vim_name, net_type, sce_net.get('ip_profile',None)) - vim_id = task_id - auxNetDict['scenario'][sce_net['uuid']][datacenter_id] = task_id - rollbackList.append({'what':'network', 'where':'vim', 'vim_id':datacenter_id, 'uuid':task_id}) - sce_net["created"] = True + if lookfor_network and create_network: + # TODO create two tasks FIND + CREATE with their relationship + task_action = "FIND_CREATE" + task_params = (lookfor_filter, (net_vim_name, net_type, sce_net.get('ip_profile', None))) + elif lookfor_network: + task_action = "FIND" + task_params = (lookfor_filter,) + elif create_network: + task_action = "CREATE" + task_params = (net_vim_name, net_type, sce_net.get('ip_profile', None)) # fill database content net_uuid = str(uuid4()) @@ -2756,7 +2763,7 @@ def create_instance(mydb, tenant_id, instance_dict): sce_net2instance[sce_net['uuid']][datacenter_id] = net_uuid db_net = { "uuid": net_uuid, - 'vim_net_id': vim_id, + 'vim_net_id': None, "instance_scenario_id": instance_uuid, "sce_net_id": sce_net["uuid"], "created": create_network, @@ -2765,6 +2772,20 @@ def create_instance(mydb, tenant_id, instance_dict): 'status': 'BUILD' if create_network else "ACTIVE" } db_instance_nets.append(db_net) + db_vim_action = { + "instance_action_id": instance_action_id, + "status": "SCHEDULED", + "task_index": task_index, + "datacenter_vim_id": myvim_thread_id, + "action": task_action, + "item": "instance_nets", + "item_id": net_uuid, + "extra": yaml.safe_dump({"params": task_params}, default_flow_style=True, width=256) + } + net2task_id['scenario'][sce_net['uuid']][datacenter_id] = task_index + task_index += 1 + db_vim_actions.append(db_vim_action) + if 'ip_profile' in sce_net: db_ip_profile={ 'instance_net_id': net_uuid, @@ -2783,33 +2804,23 @@ def create_instance(mydb, tenant_id, instance_dict): for sce_vnf in scenarioDict['vnfs']: for net in sce_vnf['nets']: if sce_vnf.get("datacenter"): - vim = myvims[ sce_vnf["datacenter"] ] datacenter_id = sce_vnf["datacenter"] - myvim_thread_id = myvim_threads_id[ sce_vnf["datacenter"]] + myvim_thread_id = myvim_threads_id[sce_vnf["datacenter"]] else: - vim = myvims[ default_datacenter_id ] datacenter_id = default_datacenter_id myvim_thread_id = myvim_threads_id[default_datacenter_id] - descriptor_net = instance_dict.get("vnfs",{}).get(sce_vnf["name"],{}) + descriptor_net = instance_dict.get("vnfs", {}).get(sce_vnf["name"], {}) net_name = descriptor_net.get("name") if not net_name: - net_name = "%s.%s" %(instance_name, net["name"]) - net_name = net_name[:255] #limit length + net_name = "{}.{}".format(instance_name, net["name"]) + net_name = net_name[:255] # limit length net_type = net['type'] - task = new_task("new-net", (net_name, net_type, net.get('ip_profile',None))) - task_id = task["id"] - instance_tasks[task_id] = task - tasks_to_launch[myvim_thread_id].append(task) - # network_id = vim.new_network(net_name, net_type, net.get('ip_profile',None)) - vim_id = task_id + if sce_vnf['uuid'] not in vnf_net2instance: vnf_net2instance[sce_vnf['uuid']] = {} - vnf_net2instance[sce_vnf['uuid']][net['uuid']] = task_id - if sce_vnf['uuid'] not in auxNetDict: - auxNetDict[sce_vnf['uuid']] = {} - auxNetDict[sce_vnf['uuid']][net['uuid']] = task_id - rollbackList.append({'what':'network','where':'vim','vim_id':datacenter_id,'uuid':task_id}) - net["created"] = True + if sce_vnf['uuid'] not in net2task_id: + net2task_id[sce_vnf['uuid']] = {} + net2task_id[sce_vnf['uuid']][net['uuid']] = task_index # fill database content net_uuid = str(uuid4()) @@ -2817,7 +2828,7 @@ def create_instance(mydb, tenant_id, instance_dict): vnf_net2instance[sce_vnf['uuid']][net['uuid']] = net_uuid db_net = { "uuid": net_uuid, - 'vim_net_id': vim_id, + 'vim_net_id': None, "instance_scenario_id": instance_uuid, "net_id": net["uuid"], "created": True, @@ -2825,6 +2836,21 @@ def create_instance(mydb, tenant_id, instance_dict): 'datacenter_tenant_id': myvim_thread_id, } db_instance_nets.append(db_net) + + db_vim_action = { + "instance_action_id": instance_action_id, + "task_index": task_index, + "datacenter_vim_id": myvim_thread_id, + "status": "SCHEDULED", + "action": "CREATE", + "item": "instance_nets", + "item_id": net_uuid, + "extra": yaml.safe_dump({"params": (net_name, net_type, net.get('ip_profile',None))}, + default_flow_style=True, width=256) + } + task_index += 1 + db_vim_actions.append(db_vim_action) + if 'ip_profile' in net: db_ip_profile = { 'instance_net_id': net_uuid, @@ -2838,16 +2864,12 @@ def create_instance(mydb, tenant_id, instance_dict): } db_ip_profiles.append(db_ip_profile) - #print "vnf_net2instance:" - #print yaml.safe_dump(vnf_net2instance, indent=4, default_flow_style=False) + # print "vnf_net2instance:" + # print yaml.safe_dump(vnf_net2instance, indent=4, default_flow_style=False) # 3. Creating new vm instances in the VIM - db_instance_vnfs = [] - db_instance_vms = [] - db_instance_interfaces = [] - #myvim.new_vminstance(self,vimURI,tenant_id,name,description,image_id,flavor_id,net_dict) - sce_vnf_list = sorted(scenarioDict['vnfs'], key=lambda k: k['name']) - #for sce_vnf in scenarioDict['vnfs']: + # myvim.new_vminstance(self,vimURI,tenant_id,name,description,image_id,flavor_id,net_dict) + sce_vnf_list = sorted(scenarioDict['vnfs'], key=lambda k: k['name']) for sce_vnf in sce_vnf_list: vnf_availability_zones = [] for vm in sce_vnf['vms']: @@ -2889,25 +2911,25 @@ def create_instance(mydb, tenant_id, instance_dict): myVMDict['description'] = myVMDict['name'][0:99] # if not startvms: # myVMDict['start'] = "no" - myVMDict['name'] = myVMDict['name'][0:255] #limit name length + myVMDict['name'] = myVMDict['name'][0:255] # limit name length #create image at vim in case it not exist image_dict = mydb.get_table_by_uuid_name("images", vm['image_id']) image_id = create_or_use_image(mydb, {datacenter_id: vim}, image_dict, [], True) vm['vim_image_id'] = image_id - #create flavor at vim in case it not exist + # create flavor at vim in case it not exist flavor_dict = mydb.get_table_by_uuid_name("flavors", vm['flavor_id']) if flavor_dict['extended']!=None: - flavor_dict['extended']= yaml.load(flavor_dict['extended']) + flavor_dict['extended'] = yaml.load(flavor_dict['extended']) flavor_id = create_or_use_flavor(mydb, {datacenter_id: vim}, flavor_dict, rollbackList, True) - #Obtain information for additional disks + # Obtain information for additional disks extended_flavor_dict = mydb.get_rows(FROM='datacenters_flavors', SELECT=('extended',), WHERE={'vim_id': flavor_id}) if not extended_flavor_dict: raise NfvoException("flavor '{}' not found".format(flavor_id), HTTP_Not_Found) return - #extended_flavor_dict_yaml = yaml.load(extended_flavor_dict[0]) + # extended_flavor_dict_yaml = yaml.load(extended_flavor_dict[0]) myVMDict['disks'] = None extended_info = extended_flavor_dict[0]['extended'] if extended_info != None: @@ -2920,8 +2942,8 @@ def create_instance(mydb, tenant_id, instance_dict): myVMDict['flavorRef'] = vm['vim_flavor_id'] myVMDict['availability_zone'] = vm.get('availability_zone') myVMDict['networks'] = [] - task_depends = {} - #TODO ALF. connect_mgmt_interfaces. Connect management interfaces if this is true + task_depends_on = [] + # TODO ALF. connect_mgmt_interfaces. Connect management interfaces if this is true db_vm_ifaces = [] for iface in vm['interfaces']: netDict = {} @@ -2929,8 +2951,9 @@ def create_instance(mydb, tenant_id, instance_dict): netDict['type'] = iface['model'] elif "model" in iface and iface["model"]!=None: netDict['model']=iface['model'] - #TODO in future, remove this because mac_address will not be set, and the type of PV,VF is obtained from iterface table model - #discover type of interface looking at flavor + # TODO in future, remove this because mac_address will not be set, and the type of PV,VF + # is obtained from iterface table model + # discover type of interface looking at flavor for numa in flavor_dict.get('extended',{}).get('numas',[]): for flavor_iface in numa.get('interfaces',[]): if flavor_iface.get('name') == iface['internal_name']: @@ -2965,20 +2988,20 @@ def create_instance(mydb, tenant_id, instance_dict): netDict['name'] = iface['internal_name'] if iface['net_id'] is None: for vnf_iface in sce_vnf["interfaces"]: - #print iface - #print vnf_iface + # print iface + # print vnf_iface if vnf_iface['interface_id']==iface['uuid']: - netDict['net_id'] = auxNetDict['scenario'][ vnf_iface['sce_net_id'] ][datacenter_id] + netDict['net_id'] = "TASK-{}".format(net2task_id['scenario'][ vnf_iface['sce_net_id'] ][datacenter_id]) instance_net_id = sce_net2instance[ vnf_iface['sce_net_id'] ][datacenter_id] + task_depends_on.append(net2task_id['scenario'][ vnf_iface['sce_net_id'] ][datacenter_id]) break else: - netDict['net_id'] = auxNetDict[ sce_vnf['uuid'] ][ iface['net_id'] ] + netDict['net_id'] = "TASK-{}".format(net2task_id[ sce_vnf['uuid'] ][ iface['net_id'] ]) instance_net_id = vnf_net2instance[ sce_vnf['uuid'] ][ iface['net_id'] ] - if netDict.get('net_id') and is_task_id(netDict['net_id']): - task_depends[netDict['net_id']] = instance_tasks[netDict['net_id']] - #skip bridge ifaces not connected to any net - #if 'net_id' not in netDict or netDict['net_id']==None: - # continue + task_depends_on.append(net2task_id[sce_vnf['uuid'] ][ iface['net_id']]) + # skip bridge ifaces not connected to any net + if 'net_id' not in netDict or netDict['net_id']==None: + continue myVMDict['networks'].append(netDict) db_vm_iface={ # "uuid" @@ -3009,16 +3032,9 @@ def create_instance(mydb, tenant_id, instance_dict): vm_index_name = "" if vm.get('count', 1) > 1: vm_index_name += "." + chr(97 + vm_index) - task = new_task("new-vm", (myVMDict['name']+vm_index_name, myVMDict['description'], - myVMDict.get('start', None), myVMDict['imageRef'], - myVMDict['flavorRef'], myVMDict['networks'], - cloud_config_vm, myVMDict['disks'], av_index, - vnf_availability_zones), depends=task_depends) - instance_tasks[task["id"]] = task - tasks_to_launch[myvim_thread_id].append(task) - vm_id = task["id"] - vm['vim_id'] = vm_id - rollbackList.append({'what':'vm','where':'vim','vim_id':datacenter_id,'uuid':vm_id}) + task_params = (myVMDict['name']+vm_index_name, myVMDict['description'], myVMDict.get('start', None), + myVMDict['imageRef'], myVMDict['flavorRef'], myVMDict['networks'], cloud_config_vm, + myVMDict['disks'], av_index, vnf_availability_zones) # put interface uuid back to scenario[vnfs][vms[[interfaces] for net in myVMDict['networks']: if "vim_id" in net: @@ -3031,11 +3047,13 @@ def create_instance(mydb, tenant_id, instance_dict): db_vm = { "uuid": vm_uuid, 'instance_vnf_id': vnf_uuid, - "vim_vm_id": vm_id, + #TODO delete "vim_vm_id": vm_id, "vm_id": vm["uuid"], # "status": } db_instance_vms.append(db_vm) + + iface_index = 0 for db_vm_iface in db_vm_ifaces: iface_uuid = str(uuid4()) uuid_list.append(iface_uuid) @@ -3055,9 +3073,26 @@ def create_instance(mydb, tenant_id, instance_dict): except: db_vm_iface_instance["ip_address"] = None db_instance_interfaces.append(db_vm_iface_instance) + myVMDict['networks'][iface_index]["uuid"] = iface_uuid + iface_index += 1 + + db_vim_action = { + "instance_action_id": instance_action_id, + "task_index": task_index, + "datacenter_vim_id": myvim_thread_id, + "action": "CREATE", + "status": "SCHEDULED", + "item": "instance_vms", + "item_id": vm_uuid, + "extra": yaml.safe_dump({"params": task_params, "depends_on": task_depends_on}, + default_flow_style=True, width=256) + } + task_index += 1 + db_vim_actions.append(db_vim_action) scenarioDict["datacenter2tenant"] = myvim_threads_id + db_instance_action["number_tasks"] = task_index db_instance_scenario['datacenter_tenant_id'] = myvim_threads_id[default_datacenter_id] db_instance_scenario['datacenter_id'] = default_datacenter_id db_tables=[ @@ -3067,27 +3102,20 @@ def create_instance(mydb, tenant_id, instance_dict): {"ip_profiles": db_ip_profiles}, {"instance_vms": db_instance_vms}, {"instance_interfaces": db_instance_interfaces}, + {"instance_actions": db_instance_action}, + {"vim_actions": db_vim_actions} ] - logger.debug("create_instance Deployment done scenarioDict: %s", + logger.debug("create_instance done DB tables: %s", yaml.safe_dump(db_tables, indent=4, default_flow_style=False) ) mydb.new_rows(db_tables, uuid_list) - for myvim_thread_id,task_list in tasks_to_launch.items(): - for task in task_list: - vim_threads["running"][myvim_thread_id].insert_task(task) - - global_instance_tasks[instance_uuid] = instance_tasks - # Update database with those ended instance_tasks - # for task in instance_tasks.values(): - # if task["status"] == "ok": - # if task["name"] == "new-vm": - # mydb.update_rows("instance_vms", UPDATE={"vim_vm_id": task["result"]}, - # WHERE={"vim_vm_id": task["id"]}) - # elif task["name"] == "new-net": - # mydb.update_rows("instance_nets", UPDATE={"vim_net_id": task["result"]}, - # WHERE={"vim_net_id": task["id"]}) - return mydb.get_instance_scenario(instance_uuid) - except (NfvoException, vimconn.vimconnException,db_base_Exception) as e: + for myvim_thread_id in myvim_threads_id.values(): + vim_threads["running"][myvim_thread_id].insert_task(db_vim_actions) + + returned_instance = mydb.get_instance_scenario(instance_uuid) + returned_instance["action_id"] = instance_action_id + return returned_instance + except (NfvoException, vimconn.vimconnException, db_base_Exception) as e: message = rollback(mydb, myvims, rollbackList) if isinstance(e, db_base_Exception): error_text = "database Exception" @@ -3096,29 +3124,42 @@ def create_instance(mydb, tenant_id, instance_dict): else: error_text = "Exception" error_text += " {} {}. {}".format(type(e).__name__, str(e), message) - #logger.error("create_instance: %s", error_text) + # logger.error("create_instance: %s", error_text) raise NfvoException(error_text, e.http_code) def delete_instance(mydb, tenant_id, instance_id): - #print "Checking that the instance_id exists and getting the instance dictionary" + # print "Checking that the instance_id exists and getting the instance dictionary" instanceDict = mydb.get_instance_scenario(instance_id, tenant_id) - #print yaml.safe_dump(instanceDict, indent=4, default_flow_style=False) + # print yaml.safe_dump(instanceDict, indent=4, default_flow_style=False) tenant_id = instanceDict["tenant_id"] - #print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id" + # print "Checking that nfvo_tenant_id exists and getting the VIM URI and the VIM tenant_id" - #1. Delete from Database + # 1. Delete from Database message = mydb.delete_instance_scenario(instance_id, tenant_id) - #2. delete from VIM + # 2. delete from VIM error_msg = "" myvims = {} myvim_threads = {} + vimthread_affected = {} - #2.1 deleting VMs - #vm_fail_list=[] + task_index = 0 + instance_action_id = get_task_id() + db_vim_actions = [] + db_instance_action = { + "uuid": instance_action_id, # same uuid for the instance and the action on create + "tenant_id": tenant_id, + "instance_id": instance_id, + "description": "DELETE", + # "number_tasks": 0 # filled bellow + } + + # 2.1 deleting VMs + # vm_fail_list=[] for sce_vnf in instanceDict['vnfs']: datacenter_key = (sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"]) + vimthread_affected[sce_vnf["datacenter_tenant_id"]] = None if datacenter_key not in myvims: try: _,myvim_thread = get_vim_thread(mydb, tenant_id, sce_vnf["datacenter_id"], sce_vnf["datacenter_tenant_id"]) @@ -3141,26 +3182,20 @@ def delete_instance(mydb, tenant_id, instance_id): error_msg += "\n VM id={} cannot be deleted because datacenter={} not found".format(vm['vim_vm_id'], sce_vnf["datacenter_id"]) continue try: - task=None - if is_task_id(vm['vim_vm_id']): - task_id = vm['vim_vm_id'] - old_task = global_instance_tasks[instance_id].get(task_id) - if not old_task: - error_msg += "\n VM was scheduled for create, but task {} is not found".format(task_id) - continue - with task_lock: - if old_task["status"] == "enqueued": - old_task["status"] = "deleted" - elif old_task["status"] == "error": - continue - elif old_task["status"] == "processing": - task = new_task("del-vm", (task_id, vm["interfaces"]), depends={task_id: old_task}) - else: #ok - task = new_task("del-vm", (old_task["result"], vm["interfaces"])) - else: - task = new_task("del-vm", (vm['vim_vm_id'], vm["interfaces"]) ) - if task: - myvim_thread.insert_task(task) + db_vim_action = { + "instance_action_id": instance_action_id, + "task_index": task_index, + "datacenter_vim_id": sce_vnf["datacenter_tenant_id"], + "action": "DELETE", + "status": "SCHEDULED", + "item": "instance_vms", + "item_id": vm["uuid"], + "extra": yaml.safe_dump({"params": vm["interfaces"]}, + default_flow_style=True, width=256) + } + task_index += 1 + db_vim_actions.append(db_vim_action) + except vimconn.vimconnNotFoundException as e: error_msg+="\n VM VIM_id={} not found at datacenter={}".format(vm['vim_vm_id'], sce_vnf["datacenter_id"]) logger.warn("VM instance '%s'uuid '%s', VIM id '%s', from VNF_id '%s' not found", @@ -3170,11 +3205,13 @@ def delete_instance(mydb, tenant_id, instance_id): logger.error("Error %d deleting VM instance '%s'uuid '%s', VIM_id '%s', from VNF_id '%s': %s", e.http_code, vm['name'], vm['uuid'], vm['vim_vm_id'], sce_vnf['vnf_id'], str(e)) - #2.2 deleting NETS - #net_fail_list=[] + # 2.2 deleting NETS + # net_fail_list=[] for net in instanceDict['nets']: - if not net['created']: - continue #skip not created nets + # TODO if not net['created']: + # TODO continue #skip not created nets + + vimthread_affected[net["datacenter_tenant_id"]] = None datacenter_key = (net["datacenter_id"], net["datacenter_tenant_id"]) if datacenter_key not in myvims: try: @@ -3197,26 +3234,20 @@ def delete_instance(mydb, tenant_id, instance_id): error_msg += "\n Net VIM_id={} cannot be deleted because datacenter={} not found".format(net['vim_net_id'], net["datacenter_id"]) continue try: - task = None - if is_task_id(net['vim_net_id']): - task_id = net['vim_net_id'] - old_task = global_instance_tasks[instance_id].get(task_id) - if not old_task: - error_msg += "\n NET was scheduled for create, but task {} is not found".format(task_id) - continue - with task_lock: - if old_task["status"] == "enqueued": - old_task["status"] = "deleted" - elif old_task["status"] == "error": - continue - elif old_task["status"] == "processing": - task = new_task("del-net", task_id, depends={task_id: old_task}) - else: # ok - task = new_task("del-net", old_task["result"]) - else: - task = new_task("del-net", (net['vim_net_id'], net['sdn_net_id'])) - if task: - myvim_thread.insert_task(task) + db_vim_action = { + "instance_action_id": instance_action_id, + "task_index": task_index, + "datacenter_vim_id": net["datacenter_tenant_id"], + "action": "DELETE", + "status": "SCHEDULED", + "item": "instance_nets", + "item_id": net["uuid"], + "extra": yaml.safe_dump({"params": (net['vim_net_id'], net['sdn_net_id'])}, + default_flow_style=True, width=256) + } + task_index += 1 + db_vim_actions.append(db_vim_action) + except vimconn.vimconnNotFoundException as e: error_msg += "\n NET VIM_id={} not found at datacenter={}".format(net['vim_net_id'], net["datacenter_id"]) logger.warn("NET '%s', VIM_id '%s', from VNF_net_id '%s' not found", @@ -3227,10 +3258,24 @@ def delete_instance(mydb, tenant_id, instance_id): e.http_code, str(e)) logger.error("Error %d deleting NET '%s', VIM_id '%s', from VNF_net_id '%s': %s", e.http_code, net['uuid'], net['vim_net_id'], str(net['vnf_net_id']), str(e)) + + db_instance_action["number_tasks"] = task_index + db_tables = [ + {"instance_actions": db_instance_action}, + {"vim_actions": db_vim_actions} + ] + + logger.debug("delete_instance done DB tables: %s", + yaml.safe_dump(db_tables, indent=4, default_flow_style=False)) + mydb.new_rows(db_tables, ()) + for myvim_thread_id in vimthread_affected.keys(): + vim_threads["running"][myvim_thread_id].insert_task(db_vim_actions) + if len(error_msg) > 0: - return 'instance ' + message + ' deleted but some elements could not be deleted, or already deleted (error: 404) from VIM: ' + error_msg + return 'action_id={} instance {} deleted but some elements could not be deleted, or already deleted '\ + '(error: 404) from VIM: {}'.format(instance_action_id, message, error_msg) else: - return 'instance ' + message + ' deleted' + return "action_id={} instance {} deleted".format(instance_action_id, message) def refresh_instance(mydb, nfvo_tenant, instanceDict, datacenter=None, vim_tenant=None): @@ -3409,6 +3454,13 @@ def instance_action(mydb,nfvo_tenant,instance_id, action_dict): raise NfvoException("datacenter '{}' not found".format(str(instanceDict['datacenter_id'])), HTTP_Not_Found) myvim = vims.values()[0] + if action_dict.get("create-vdu"): + for vdu in action_dict["create-vdu"]: + vdu_id = vdu.get("vdu-id") + vdu_count = vdu.get("count", 1) + # get from database TODO + # insert tasks TODO + pass input_vnfs = action_dict.pop("vnfs", []) input_vms = action_dict.pop("vms", []) @@ -3420,7 +3472,7 @@ def instance_action(mydb,nfvo_tenant,instance_id, action_dict): for vm in sce_vnf['vms']: if not action_over_all: if sce_vnf['uuid'] not in input_vnfs and sce_vnf['vnf_name'] not in input_vnfs and \ - vm['uuid'] not in input_vms and vm['name'] not in input_vms: + vm['uuid'] not in input_vms and vm['name'] not in input_vms: continue try: data = myvim.action_vminstance(vm['vim_vm_id'], action_dict) @@ -3470,6 +3522,19 @@ def instance_action(mydb,nfvo_tenant,instance_id, action_dict): else: return vm_result +def instance_action_get(mydb, nfvo_tenant, instance_id, action_id): + filter={} + if nfvo_tenant and nfvo_tenant != "any": + filter["tenant_id"] = nfvo_tenant + if instance_id and instance_id != "any": + filter["instance_id"] = instance_id + if action_id: + filter["uuid"] = action_id + rows = mydb.get_rows(FROM="instance_actions", WHERE=filter) + if not rows and action_id: + raise NfvoException("Not found any action with this criteria", HTTP_Not_Found) + return {"ations": rows} + def create_or_use_console_proxy_thread(console_server, console_port): #look for a non-used port @@ -3741,7 +3806,7 @@ def deassociate_datacenter_to_tenant(mydb, tenant_id, datacenter, vim_tenant_id= pass # the error will be caused because dependencies, vim_tenant can not be deleted thread_id = tenant_datacenter_item["datacenter_tenant_id"] thread = vim_threads["running"][thread_id] - thread.insert_task(new_task("exit", None)) + thread.insert_task("exit") vim_threads["deleting"][thread_id] = thread return "datacenter {} detached. {}".format(datacenter_id, warning) diff --git a/osm_ro/nfvo_db.py b/osm_ro/nfvo_db.py index ccba5a31..cb345e5f 100644 --- a/osm_ro/nfvo_db.py +++ b/osm_ro/nfvo_db.py @@ -36,7 +36,8 @@ import time tables_with_createdat_field=["datacenters","instance_nets","instance_scenarios","instance_vms","instance_vnfs", "interfaces","nets","nfvo_tenants","scenarios","sce_interfaces","sce_nets", - "sce_vnfs","tenants_datacenters","datacenter_tenants","vms","vnfs", "datacenter_nets"] + "sce_vnfs","tenants_datacenters","datacenter_tenants","vms","vnfs", "datacenter_nets", + "instance_actions", "vim_actions"] class nfvo_db(db_base.db_base): @@ -553,10 +554,10 @@ class nfvo_db(db_base.db_base): # print "nfvo_db.get_instance_scenario DB Exception %d: %s" % (e.args[0], e.args[1]) # return self._format_error(e) - def get_scenario(self, scenario_id, tenant_id=None, datacenter_id=None): + def get_scenario(self, scenario_id, tenant_id=None, datacenter_vim_id=None, datacenter_id=None): '''Obtain the scenario information, filtering by one or serveral of the tenant, uuid or name scenario_id is the uuid or the name if it is not a valid uuid format - if datacenter_id is provided, it supply aditional vim_id fields with the matching vim uuid + if datacenter_vim_id,d datacenter_id is provided, it supply aditional vim_id fields with the matching vim uuid Only one scenario must mutch the filtering or an error is returned ''' tries = 2 @@ -608,14 +609,14 @@ class nfvo_db(db_base.db_base): vm["boot_data"] = yaml.safe_load(vm["boot_data"]) else: del vm["boot_data"] - if datacenter_id!=None: - cmd = "SELECT vim_id FROM datacenters_images WHERE image_id='{}' AND datacenter_id='{}'".format(vm['image_id'],datacenter_id) + if datacenter_vim_id!=None: + cmd = "SELECT vim_id FROM datacenters_images WHERE image_id='{}' AND datacenter_vim_id='{}'".format(vm['image_id'],datacenter_vim_id) self.logger.debug(cmd) self.cur.execute(cmd) if self.cur.rowcount==1: vim_image_dict = self.cur.fetchone() vm['vim_image_id']=vim_image_dict['vim_id'] - cmd = "SELECT vim_id FROM datacenters_flavors WHERE flavor_id='{}' AND datacenter_id='{}'".format(vm['flavor_id'],datacenter_id) + cmd = "SELECT vim_id FROM datacenters_flavors WHERE flavor_id='{}' AND datacenter_vim_id='{}'".format(vm['flavor_id'],datacenter_vim_id) self.logger.debug(cmd) self.cur.execute(cmd) if self.cur.rowcount==1: @@ -677,7 +678,7 @@ class nfvo_db(db_base.db_base): self.logger.debug(cmd) self.cur.execute(cmd) d_net = self.cur.fetchone() - if d_net==None or datacenter_id==None: + if d_net==None or datacenter_vim_id==None: #print "nfvo_db.get_scenario() WARNING external net %s not found" % net['name'] net['vim_id']=None else: @@ -895,7 +896,7 @@ class nfvo_db(db_base.db_base): try: with self.con: self.cur = self.con.cursor(mdb.cursors.DictCursor) - #instance table + # instance table where_list=[] if tenant_id is not None: where_list.append( "inst.tenant_id='" + tenant_id +"'" ) if db_base._check_valid_uuid(instance_id): @@ -922,7 +923,7 @@ class nfvo_db(db_base.db_base): instance_dict["cloud-config"] = yaml.load(instance_dict["cloud_config"]) del instance_dict["cloud_config"] - #instance_vnfs + # instance_vnfs cmd = "SELECT iv.uuid as uuid,sv.vnf_id as vnf_id,sv.name as vnf_name, sce_vnf_id, datacenter_id, datacenter_tenant_id"\ " FROM instance_vnfs as iv join sce_vnfs as sv on iv.sce_vnf_id=sv.uuid" \ " WHERE iv.instance_scenario_id='{}'" \ diff --git a/osm_ro/openmano_schemas.py b/osm_ro/openmano_schemas.py index fb12d9f1..1e83f4be 100644 --- a/osm_ro/openmano_schemas.py +++ b/osm_ro/openmano_schemas.py @@ -1098,6 +1098,31 @@ instance_scenario_action_schema = { "type": ["object","null"], }, "console": {"type": ["string", "null"], "enum": ["novnc", "xvpvnc", "rdp-html5", "spice-html5", None]}, + "create-vdu": { + "type": "list", + "items" :{ + "type": "object", + "properties":{ + "vdu-id": id_schema, + "count": integer1_schema, + }, + "additionalProperties": False, + "required": ["vdu-id"] + } + }, + "delete-vdu": { + "type": "list", + "items" :{ + "type": "object", + "properties":{ + "vdu-id": id_schema, + "transaction-id": id_schema, + }, + "additionalProperties": False, + "minProperties": 1, + "maxProperties": 1, + } + }, "vnfs":{"type": "array", "items":{"type":"string"}}, "vms":{"type": "array", "items":{"type":"string"}} }, diff --git a/osm_ro/vim_thread.py b/osm_ro/vim_thread.py index 0074dfe9..bbb81a58 100644 --- a/osm_ro/vim_thread.py +++ b/osm_ro/vim_thread.py @@ -22,8 +22,36 @@ ## """" -This is thread that interact with the host and the libvirt to manage VM -One thread will be launched per host +This is thread that interacts with a VIM. It processes TASKs sequentially against a single VIM. +The tasks are stored at database in table vim_actions +The task content is: + MD instance_action_id: reference a global action over an instance-scenario: database instance_actions + MD task_index: index number of the task. This with the previous are a key + MD datacenter_vim_id: should contain the uuid of the VIM managed by this thread + MD vim_id: id of the vm,net,etc at VIM + MD action: CREATE, DELETE, LOOK, TODO: LOOK_CREATE + MD item: database table name, can be instance_vms, instance_nets, TODO: datacenter_flavors, datacenter_images + MD item_id: uuid of the referenced entry in the preious table + MD status: SCHEDULED,BUILD,DONE,FAILED,SUPERSEDED + MD extra: text with yaml format at database, dict at memory with: + params: list with the params to be sent to the VIM for CREATE or LOOK. For DELETE the vim_id is taken from other related tasks + depends_on: list with the 'task_index'es of tasks that must be completed before. e.g. a vm depends on a net + sdn_net_id: used for net. + tries: + interfaces: used for VMs. Each key is the uuid of the instance_interfaces entry at database + iface_id: uuid of intance_interfaces + sdn_port_id: + sdn_net_id: + created: False if the VIM element is not created by other actions, and it should not be deleted + vim_status: VIM status of the element. Stored also at database in the instance_XXX + M depends: dict with task_index(from depends_on) to task class + M params: same as extra[params] but with the resolved dependencies + M vim_interfaces: similar to extra[interfaces] but with VIM information. Stored at database in the instance_XXX but not at vim_actions + M vim_info: Detailed information of a vm,net from the VIM. Stored at database in the instance_XXX but not at vim_actions + MD error_msg: descriptive text upon an error.Stored also at database instance_XXX + MD created_at: task creation time + MD modified_at: last task update time. On refresh it contains when this task need to be refreshed + """ import threading @@ -31,18 +59,23 @@ import time import Queue import logging import vimconn +import yaml from db_base import db_base_Exception from lib_osm_openvim.ovim import ovimException __author__ = "Alfonso Tierno, Pablo Montes" -__date__ = "$10-feb-2017 12:07:15$" +__date__ = "$28-Sep-2017 12:07:15$" # from logging import Logger # import auxiliary_functions as af def is_task_id(task_id): - return True if task_id[:5] == "TASK." else False + return task_id.startswith("TASK-") + + +class VimThreadException(Exception): + pass class vim_thread(threading.Thread): @@ -58,12 +91,6 @@ class vim_thread(threading.Thread): 'host','user': host ip or name to manage and user 'db', 'db_lock': database class and lock to use it in exclusion """ - self.tasksResult = {} - """ It will contain a dictionary with - task_id: - status: enqueued,done,error,deleted,processing - result: VIM result, - """ threading.Thread.__init__(self) self.vim = vimconn self.datacenter_name = datacenter_name @@ -80,35 +107,86 @@ class vim_thread(threading.Thread): self.task_lock = task_lock self.task_queue = Queue.Queue(2000) - self.refresh_list = [] + + self.refresh_tasks = [] """Contains time ordered task list for refreshing the status of VIM VMs and nets""" + self.pending_tasks = [] + """Contains time ordered task list for creation, deletion of VIM VMs and nets""" + + self.grouped_tasks = {} + """ It contains all the creation/deletion pending tasks grouped by its concrete vm, net, etc + : + - # e.g. CREATE task + # e.g. DELETE task + """ + + def _reload_vim_actions(self): + """ + Read actions from database and reload them at memory. Fill self.refresh_list, pending_list, vim_actions + :return: None + """ + action_completed = False + task_list = [] + old_action_key = None + + with self.db_lock: + vim_actions = self.db.get_rows(FROM="vim_actions", + WHERE={"datacenter_vim_id": self.datacenter_tenant_id }, + ORDER_BY=("item", "item_id", "created_at",)) + for task in vim_actions: + item = task["item"] + item_id = task["item_id"] + action_key = item + item_id + if old_action_key != action_key: + if not action_completed and task_list: + # This will fill needed task parameters into memory, and insert the task if needed in + # self.pending_tasks or self.refresh_tasks + self._insert_pending_tasks(task_list) + task_list = [] + old_action_key = action_key + action_completed = False + elif action_completed: + continue + + if task["status"] == "SCHEDULED" or task["action"] == "CREATE" or task["action"] == "FIND": + task_list.append(task) + elif task["action"] == "DELETE": + # action completed because deleted and status is not SCHEDULED. Not needed anything + action_completed = True + + # Last actions group need to be inserted too + if not action_completed and task_list: + self._insert_pending_tasks(task_list) + def _refres_elements(self): """Call VIM to get VMs and networks status until 10 elements""" now = time.time() + nb_processed = 0 vm_to_refresh_list = [] net_to_refresh_list = [] vm_to_refresh_dict = {} net_to_refresh_dict = {} items_to_refresh = 0 - while self.refresh_list: - task = self.refresh_list[0] + while self.refresh_tasks: + task = self.refresh_tasks[0] with self.task_lock: - if task['status'] == 'deleted': - self.refresh_list.pop(0) + if task['status'] == 'SUPERSEDED': + self.refresh_tasks.pop(0) continue - if task['time'] > now: + if task['modified_at'] > now: break - task["status"] = "processing" - self.refresh_list.pop(0) - if task["name"] == 'get-vm': + # task["status"] = "processing" + nb_processed += 1 + self.refresh_tasks.pop(0) + if task["item"] == 'instance_vms': vm_to_refresh_list.append(task["vim_id"]) vm_to_refresh_dict[task["vim_id"]] = task - elif task["name"] == 'get-net': + elif task["item"] == 'instance_nets': net_to_refresh_list.append(task["vim_id"]) net_to_refresh_dict[task["vim_id"]] = task else: - error_text = "unknown task {}".format(task["name"]) + error_text = "unknown task {}".format(task["item"]) self.logger.error(error_text) items_to_refresh += 1 if items_to_refresh == 10: @@ -116,110 +194,100 @@ class vim_thread(threading.Thread): if vm_to_refresh_list: try: + now = time.time() vim_dict = self.vim.refresh_vms_status(vm_to_refresh_list) for vim_id, vim_info in vim_dict.items(): - #look for task + # look for task + task_need_update = False task = vm_to_refresh_dict[vim_id] self.logger.debug("get-vm vm_id=%s result=%s", task["vim_id"], str(vim_info)) # update database + task_vim_info = task.get("vim_info") + task_error_msg = task.get("error_msg") + task_vim_status = task["extra"].get("vim_status") if vim_info.get("error_msg"): vim_info["error_msg"] = self._format_vim_error_msg(vim_info["error_msg"]) - if task["vim_info"].get("status") != vim_info["status"] or \ - task["vim_info"].get("error_msg") != vim_info.get("error_msg") or \ - task["vim_info"].get("vim_info") != vim_info["vim_info"]: + if task_vim_status != vim_info["status"] or task_error_msg != vim_info.get("error_msg") or \ + task_vim_info != vim_info.get("vim_info"): with self.db_lock: temp_dict = {"status": vim_info["status"], "error_msg": vim_info.get("error_msg"), - "vim_info": vim_info["vim_info"]} - self.db.update_rows('instance_vms', UPDATE=temp_dict, WHERE={"vim_vm_id": vim_id}) - for interface in vim_info["interfaces"]: - for task_interface in task["vim_info"]["interfaces"]: - if task_interface["vim_net_id"] == interface["vim_net_id"]: - break - else: - task_interface = {"vim_net_id": interface["vim_net_id"]} - task["vim_info"]["interfaces"].append(task_interface) - if task_interface != interface: - #delete old port + "vim_info": vim_info.get("vim_info")} + self.db.update_rows('instance_vms', UPDATE=temp_dict, WHERE={"uuid": task["item_id"]}) + task["extra"]["vim_status"] = vim_info["status"] + task["error_msg"] = vim_info.get("error_msg") + task["vim_info"] = vim_info.get("vim_info") + task_need_update = True + for interface in vim_info.get("interfaces", ()): + vim_interface_id = interface["vim_interface_id"] + if vim_interface_id not in task["extra"]["interfaces"]: + self.logger.critical("Interface not found {} on task info {}".format( + vim_interface_id, task["extra"]["interfaces"]), exc_info=True) + continue + task_interface = task["extra"]["interfaces"][vim_interface_id] + task_vim_interface = task["vim_interfaces"].get(vim_interface_id) + if task_vim_interface != interface: + # delete old port if task_interface.get("sdn_port_id"): try: with self.db_lock: self.ovim.delete_port(task_interface["sdn_port_id"]) task_interface["sdn_port_id"] = None + task_need_update = True except ovimException as e: self.logger.error("ovimException deleting external_port={} ".format( task_interface["sdn_port_id"]) + str(e), exc_info=True) # TODO Set error_msg at instance_nets - vim_net_id = interface["vim_net_id"] - sdn_net_id = None - sdn_port_name = None - with self.db_lock: - where_= {'iv.vim_vm_id': vim_id, "ine.vim_net_id": vim_net_id, - 'ine.datacenter_tenant_id': self.datacenter_tenant_id} - # TODO check why vim_interface_id is not present at database - # if interface.get("vim_interface_id"): - # where_["vim_interface_id"] = interface["vim_interface_id"] - db_ifaces = self.db.get_rows( - FROM="instance_interfaces as ii left join instance_nets as ine on " - "ii.instance_net_id=ine.uuid left join instance_vms as iv on " - "ii.instance_vm_id=iv.uuid", - SELECT=("ii.uuid as iface_id", "ine.uuid as net_id", "iv.uuid as vm_id", "sdn_net_id", "vim_net_id"), - WHERE=where_) - if len(db_ifaces)>1: - self.logger.critical("Refresing interfaces. " - "Found more than one interface at database for '{}'".format(where_)) - elif len(db_ifaces)==0: - self.logger.critical("Refresing interfaces. " - "Not found any interface at database for '{}'".format(where_)) - continue - else: - db_iface = db_ifaces[0] - # If there is no sdn_net_id, check if it is because an already created vim network is being used - # in that case, the sdn_net_id will be in that entry of the instance_nets table - if not db_iface.get("sdn_net_id"): + + # Create SDN port + sdn_net_id = task_interface.get("sdn_net_id") + if sdn_net_id and interface.get("compute_node") and interface.get("pci"): + sdn_port_name = sdn_net_id + "." + task["vim_id"] + sdn_port_name = sdn_port_name[:63] + try: with self.db_lock: - result = self.db.get_rows( - SELECT=('sdn_net_id',), FROM='instance_nets', - WHERE={'vim_net_id': db_iface.get("vim_net_id"), - 'instance_scenario_id': None, - 'datacenter_tenant_id': self.datacenter_tenant_id}) - if len(result) == 1: - db_iface["sdn_net_id"] = result[0]['sdn_net_id'] - - if db_iface.get("sdn_net_id") and interface.get("compute_node") and interface.get("pci"): - sdn_net_id = db_iface["sdn_net_id"] - sdn_port_name = sdn_net_id + "." + db_iface["vm_id"] - sdn_port_name = sdn_port_name[:63] - try: - with self.db_lock: - sdn_port_id = self.ovim.new_external_port( - {"compute_node": interface["compute_node"], - "pci": interface["pci"], - "vlan": interface.get("vlan"), - "net_id": sdn_net_id, - "region": self.vim["config"]["datacenter_id"], - "name": sdn_port_name, - "mac": interface.get("mac_address")}) - interface["sdn_port_id"] = sdn_port_id - except (ovimException, Exception) as e: - self.logger.error( - "ovimException creating new_external_port compute_node={} " \ - "pci={} vlan={} ".format( - interface["compute_node"], - interface["pci"], - interface.get("vlan")) + str(e), - exc_info=True) - # TODO Set error_msg at instance_nets - with self.db_lock: - vim_net_id = interface.pop("vim_net_id") - self.db.update_rows('instance_interfaces', UPDATE=interface, - WHERE={'uuid': db_iface["iface_id"]}) - interface["vim_net_id"] = vim_net_id - # TODO insert instance_id - - task["vim_info"] = vim_info - if task["vim_info"]["status"] == "BUILD": + sdn_port_id = self.ovim.new_external_port( + {"compute_node": interface["compute_node"], + "pci": interface["pci"], + "vlan": interface.get("vlan"), + "net_id": sdn_net_id, + "region": self.vim["config"]["datacenter_id"], + "name": sdn_port_name, + "mac": interface.get("mac_address")}) + task_interface["sdn_port_id"] = sdn_port_id + task_need_update = True + except (ovimException, Exception) as e: + self.logger.error( + "ovimException creating new_external_port compute_node={} " + "pci={} vlan={} ".format( + interface["compute_node"], + interface["pci"], + interface.get("vlan")) + str(e), + exc_info=True) + # TODO Set error_msg at instance_nets + with self.db_lock: + self.db.update_rows( + 'instance_interfaces', + UPDATE={"mac_address": interface.get("mac_address"), + "ip_address": interface.get("ip_address"), + "vim_info": interface.get("vim_info"), + "sdn_port_id": task_interface.get("sdn_port_id"), + "compute_node": interface.get("compute_node"), + "pci": interface.get("pci"), + "vlan": interface.get("vlan"), + }, + WHERE={'uuid': task_interface["iface_id"]}) + task["vim_interfaces"][vim_interface_id] = interface + if task_need_update: + with self.db_lock: + self.db.update_rows( + 'vim_actions', + UPDATE={"extra": yaml.safe_dump(task["extra"], default_flow_style=True, width=256), + "error_msg": task.get("error_msg"), "modified_at": now}, + WHERE={'instance_action_id': task['instance_action_id'], + 'task_index': task['task_index']}) + if task["extra"].get("vim_status") == "BUILD": self._insert_refresh(task, now + self.REFRESH_BUILD) else: self._insert_refresh(task, now + self.REFRESH_ACTIVE) @@ -229,65 +297,61 @@ class vim_thread(threading.Thread): if net_to_refresh_list: try: + now = time.time() vim_dict = self.vim.refresh_nets_status(net_to_refresh_list) for vim_id, vim_info in vim_dict.items(): - #look for task + # look for task task = net_to_refresh_dict[vim_id] self.logger.debug("get-net net_id=%s result=%s", task["vim_id"], str(vim_info)) - #get database info - where_ = {"vim_net_id": vim_id, 'datacenter_tenant_id': self.datacenter_tenant_id} - with self.db_lock: - db_nets = self.db.get_rows( - FROM="instance_nets", - SELECT=("uuid as net_id", "sdn_net_id"), - WHERE=where_) - if len(db_nets) > 1: - self.logger.critical("Refresing networks. " - "Found more than one instance-networks at database for '{}'".format(where_)) - elif len(db_nets) == 0: - self.logger.critical("Refresing networks. " - "Not found any instance-network at database for '{}'".format(where_)) - continue - else: - db_net = db_nets[0] - if db_net.get("sdn_net_id"): - # get ovim status - try: - with self.db_lock: - sdn_net = self.ovim.show_network(db_net["sdn_net_id"]) - if sdn_net["status"] == "ERROR": - if not vim_info.get("error_msg"): - vim_info["error_msg"] = sdn_net["error_msg"] - else: - vim_info["error_msg"] = "VIM_ERROR: {} && SDN_ERROR: {}".format( - self._format_vim_error_msg(vim_info["error_msg"], 1024//2-14), - self._format_vim_error_msg(sdn_net["error_msg"], 1024//2-14)) - if vim_info["status"] == "VIM_ERROR": - vim_info["status"] = "VIM_SDN_ERROR" - else: - vim_info["status"] = "SDN_ERROR" - - except (ovimException, Exception) as e: - self.logger.error( - "ovimException getting network infor snd_net_id={}".format(db_net["sdn_net_id"]), - exc_info=True) - # TODO Set error_msg at instance_nets + task_vim_info = task.get("vim_info") + task_vim_status = task["extra"].get("vim_status") + task_error_msg = task.get("error_msg") + task_sdn_net_id = task["extra"].get("sdn_net_id") + + # get ovim status + if task_sdn_net_id: + try: + with self.db_lock: + sdn_net = self.ovim.show_network(task_sdn_net_id) + if sdn_net["status"] == "ERROR": + if not vim_info.get("error_msg"): + vim_info["error_msg"] = sdn_net["error_msg"] + else: + vim_info["error_msg"] = "VIM_ERROR: {} && SDN_ERROR: {}".format( + self._format_vim_error_msg(vim_info["error_msg"], 1024//2-14), + self._format_vim_error_msg(sdn_net["error_msg"], 1024//2-14)) + if vim_info["status"] == "VIM_ERROR": + vim_info["status"] = "VIM_SDN_ERROR" + else: + vim_info["status"] = "SDN_ERROR" + + except (ovimException, Exception) as e: + self.logger.error( + "ovimException getting network infor snd_net_id={}".format(task_sdn_net_id), + exc_info=True) + # TODO Set error_msg at instance_nets # update database if vim_info.get("error_msg"): vim_info["error_msg"] = self._format_vim_error_msg(vim_info["error_msg"]) - if task["vim_info"].get("status") != vim_info["status"] or \ - task["vim_info"].get("error_msg") != vim_info.get("error_msg") or \ - task["vim_info"].get("vim_info") != vim_info["vim_info"]: - with self.db_lock: - temp_dict = {"status": vim_info["status"], + if task_vim_status != vim_info["status"] or task_error_msg != vim_info.get("error_msg") or \ + task_vim_info != vim_info["vim_info"]: + task["extra"]["vim_status"] = vim_info["status"] + task["error_msg"] = vim_info.get("error_msg") + task["vim_info"] = vim_info["vim_info"] + temp_dict = {"status": vim_info["status"], "error_msg": vim_info.get("error_msg"), "vim_info": vim_info["vim_info"]} - self.db.update_rows('instance_nets', UPDATE=temp_dict, WHERE={"vim_net_id": vim_id}) - - task["vim_info"] = vim_info - if task["vim_info"]["status"] == "BUILD": + with self.db_lock: + self.db.update_rows('instance_nets', UPDATE=temp_dict, WHERE={"uuid": task["item_id"]}) + self.db.update_rows( + 'vim_actions', + UPDATE={"extra": yaml.safe_dump(task["extra"], default_flow_style=True, width=256), + "error_msg": task.get("error_msg"), "modified_at": now}, + WHERE={'instance_action_id': task['instance_action_id'], + 'task_index': task['task_index']}) + if task["extra"].get("vim_status") == "BUILD": self._insert_refresh(task, now + self.REFRESH_BUILD) else: self._insert_refresh(task, now + self.REFRESH_ACTIVE) @@ -295,23 +359,26 @@ class vim_thread(threading.Thread): self.logger.error("vimconnException Exception when trying to refresh nets " + str(e)) self._insert_refresh(task, now + self.REFRESH_ACTIVE) - if not items_to_refresh: - time.sleep(1) + return nb_processed - def _insert_refresh(self, task, threshold_time): - """Insert a task at list of refreshing elements. The refreshing list is ordered by threshold_time (task['time'] + def _insert_refresh(self, task, threshold_time=None): + """Insert a task at list of refreshing elements. The refreshing list is ordered by threshold_time (task['modified_at'] It is assumed that this is called inside this thread """ - task["time"] = threshold_time - for index in range(0, len(self.refresh_list)): - if self.refresh_list[index]["time"] > threshold_time: - self.refresh_list.insert(index, task) + if not threshold_time: + threshold_time = time.time() + task["modified_at"] = threshold_time + task_name = task["item"][9:] + "-" + task["action"] + task_id = task["instance_action_id"] + "." + str(task["task_index"]) + for index in range(0, len(self.refresh_tasks)): + if self.refresh_tasks[index]["modified_at"] > threshold_time: + self.refresh_tasks.insert(index, task) break else: - index = len(self.refresh_list) - self.refresh_list.append(task) - self.logger.debug("new refresh task={} name={}, time={} index={}".format( - task["id"], task["name"], task["time"], index)) + index = len(self.refresh_tasks) + self.refresh_tasks.append(task) + self.logger.debug("new refresh task={} name={}, modified_at={} index={}".format( + task_id, task_name, task["modified_at"], index)) def _remove_refresh(self, task_name, vim_id): """Remove a task with this name and vim_id from the list of refreshing elements. @@ -320,27 +387,165 @@ class vim_thread(threading.Thread): Return False if not found """ index_to_delete = None - for index in range(0, len(self.refresh_list)): - if self.refresh_list[index]["name"] == task_name and self.refresh_list[index]["vim_id"] == vim_id: + for index in range(0, len(self.refresh_tasks)): + if self.refresh_tasks[index]["name"] == task_name and self.refresh_tasks[index]["vim_id"] == vim_id: index_to_delete = index break else: return False if index_to_delete != None: - del self.refresh_list[index_to_delete] + del self.refresh_tasks[index_to_delete] return True + def _proccess_pending_tasks(self): + nb_created = 0 + nb_processed = 0 + while self.pending_tasks: + task = self.pending_tasks.pop(0) + nb_processed += 1 + if task["status"] == "SUPERSEDED": + # not needed to do anything but update database with the new status + result = True + database_update = None + elif task["item"] == 'instance_vms': + if task["action"] == "CREATE": + result, database_update = self.new_vm(task) + nb_created += 1 + elif task["action"] == "DELETE": + result, database_update = self.del_vm(task) + else: + raise vimconn.vimconnException(self.name + "unknown task action {}".format(task["action"])) + elif task["item"] == 'instance_nets': + if task["action"] == "CREATE": + result, database_update = self.new_net(task) + nb_created += 1 + elif task["action"] == "DELETE": + result, database_update = self.del_net(task) + elif task["action"] == "FIND": + result, database_update = self.get_net(task) + else: + raise vimconn.vimconnException(self.name + "unknown task action {}".format(task["action"])) + else: + raise vimconn.vimconnException(self.name + "unknown task item {}".format(task["item"])) + # TODO + + if task["status"] == "SCHEDULED": + # This is because a depend task is not completed. Moved to the end. NOT USED YET + if task["extra"].get("tries", 0) > 3: + task["status"] == "FAILED" + else: + task["extra"]["tries"] = task["extra"].get("tries", 0) + 1 + self.pending_tasks.append(task) + elif task["action"] == "DELETE": + action_key = task["item"] + task["item_id"] + del self.grouped_tasks[action_key] + elif task["action"] in ("CREATE", "FIND") and task["status"] in ("DONE", "BUILD"): + self._insert_refresh(task) + + self.logger.debug("vim_action id={}.{} item={} action={} result={}:{} params={}".format( + task["instance_action_id"], task["task_index"], task["item"], task["action"], + task["status"], task["vim_id"] if task["status"] == "DONE" else task.get("error_msg"), + task["params"])) + try: + now = time.time() + with self.db_lock: + self.db.update_rows( + table="vim_actions", + UPDATE={"status": task["status"], "vim_id": task["vim_id"], "modified_at": now, + "error_msg": task["error_msg"], + "extra": yaml.safe_dump(task["extra"], default_flow_style=True, width=256)}, + WHERE={"instance_action_id": task["instance_action_id"], "task_index": task["task_index"]}) + if result is not None: + self.db.update_rows( + table="instance_actions", + UPDATE={("number_done" if result else "number_failed"): {"INCREMENT": 1}, + "modified_at": now}, + WHERE={"uuid": task["instance_action_id"]}) + if database_update: + self.db.update_rows(table=task["item"], + UPDATE=database_update, + WHERE={"uuid": task["item_id"]}) + except db_base_Exception as e: + self.logger.error("Error updating database %s", str(e), exc_info=True) + + if nb_created == 10: + break + return nb_processed + + def _insert_pending_tasks(self, vim_actions_list): + now = time.time() + for task in vim_actions_list: + if task["datacenter_vim_id"] != self.datacenter_tenant_id: + continue + item = task["item"] + item_id = task["item_id"] + action_key = item + item_id + if action_key not in self.grouped_tasks: + self.grouped_tasks[action_key] = [] + task["params"] = None + task["depends"] = {} + if task["extra"]: + extra = yaml.load(task["extra"]) + task["extra"] = extra + task["params"] = extra.get("params") + depends_on_list = extra.get("depends_on") + if depends_on_list: + for index in depends_on_list: + if index < len(vim_actions_list) and vim_actions_list[index]["task_index"] == index and\ + vim_actions_list[index]["instance_action_id"] == task["instance_action_id"]: + task["depends"]["TASK-" + str(index)] = vim_actions_list[index] + if extra.get("interfaces"): + task["vim_interfaces"] = {} + else: + task["extra"] = {} + if "error_msg" not in task: + task["error_msg"] = None + if "vim_id" not in task: + task["vim_id"] = None + + if task["action"] == "DELETE": + need_delete_action = False + for to_supersede in self.grouped_tasks.get(action_key, ()): + if to_supersede["action"] == "FIND" and to_supersede.get("vim_id"): + task["vim_id"] = to_supersede["vim_id"] + if to_supersede["action"] == "CREATE" and to_supersede.get("vim_id"): + need_delete_action = True + task["vim_id"] = to_supersede["vim_id"] + if to_supersede["extra"].get("sdn_vim_id"): + task["extra"]["sdn_vim_id"] = to_supersede["extra"]["sdn_vim_id"] + if to_supersede["extra"].get("interfaces"): + task["extra"]["interfaces"] = to_supersede["extra"]["interfaces"] + # Mark task as SUPERSEDED. + # If task is in self.pending_tasks, it will be removed and database will be update + # If task is in self.refresh_tasks, it will be removed + to_supersede["status"] = "SUPERSEDED" + if not need_delete_action: + task["status"] = "SUPERSEDED" + + self.grouped_tasks[action_key].append(task) + self.pending_tasks.append(task) + elif task["status"] == "SCHEDULED": + self.grouped_tasks[action_key].append(task) + self.pending_tasks.append(task) + elif task["action"] in ("CREATE", "FIND"): + self.grouped_tasks[action_key].append(task) + if task["status"] in ("DONE", "BUILD"): + self._insert_refresh(task) + # TODO add VM reset, get console, etc... + else: + raise vimconn.vimconnException(self.name + "unknown vim_action action {}".format(task["action"])) + def insert_task(self, task): try: self.task_queue.put(task, False) - return task["id"] + return None except Queue.Full: raise vimconn.vimconnException(self.name + ": timeout inserting a task") def del_task(self, task): with self.task_lock: - if task["status"] == "enqueued": - task["status"] == "deleted" + if task["status"] == "SCHEDULED": + task["status"] == "SUPERSEDED" return True else: # task["status"] == "processing" self.task_lock.release() @@ -349,50 +554,28 @@ class vim_thread(threading.Thread): def run(self): self.logger.debug("Starting") while True: - #TODO reload service + self._reload_vim_actions() + reload_thread = False while True: try: - if not self.task_queue.empty(): + while not self.task_queue.empty(): task = self.task_queue.get() - self.task_lock.acquire() - if task["status"] == "deleted": - self.task_lock.release() - continue - task["status"] = "processing" - self.task_lock.release() - else: - self._refres_elements() - continue - self.logger.debug("processing task id={} name={} params={}".format(task["id"], task["name"], - str(task["params"]))) - if task["name"] == 'exit' or task["name"] == 'reload': - result, content = self.terminate(task) - elif task["name"] == 'new-vm': - result, content = self.new_vm(task) - elif task["name"] == 'del-vm': - result, content = self.del_vm(task) - elif task["name"] == 'new-net': - result, content = self.new_net(task) - elif task["name"] == 'del-net': - result, content = self.del_net(task) - else: - error_text = "unknown task {}".format(task["name"]) - self.logger.error(error_text) - result = False - content = error_text - self.logger.debug("task id={} name={} result={}:{} params={}".format(task["id"], task["name"], - result, content, - str(task["params"]))) - - with self.task_lock: - task["status"] = "done" if result else "error" - task["result"] = content - self.task_queue.task_done() - - if task["name"] == 'exit': - return 0 - elif task["name"] == 'reload': + if isinstance(task, list): + self._insert_pending_tasks(task) + elif isinstance(task, str): + if task == 'exit': + return 0 + elif task == 'reload': + reload_thread = True + break + self.task_queue.task_done() + if reload_thread: break + nb_processed = self._proccess_pending_tasks() + nb_processed += self._refres_elements() + if not nb_processed: + time.sleep(1) + except Exception as e: self.logger.critical("Unexpected exception at run: " + str(e), exc_info=True) @@ -401,6 +584,26 @@ class vim_thread(threading.Thread): def terminate(self, task): return True, None + def _look_for_task(self, instance_action_id, task_id): + task_index = task_id.split("-")[-1] + with self.db_lock: + tasks = self.db.get_rows(FROM="vim_actions", WHERE={"instance_action_id": instance_action_id, + "task_index": task_index}) + if not tasks: + return None + task = tasks[0] + task["params"] = None + task["depends"] = {} + if task["extra"]: + extra = yaml.load(task["extra"]) + task["extra"] = extra + task["params"] = extra.get("params") + if extra.get("interfaces"): + task["vim_interfaces"] = {} + else: + task["extra"] = {} + return task + def _format_vim_error_msg(self, error_text, max_length=1024): if error_text and len(error_text) >= max_length: return error_text[:max_length//2-3] + " ... " + error_text[-max_length//2+3:] @@ -408,9 +611,9 @@ class vim_thread(threading.Thread): def new_net(self, task): try: - task_id = task["id"] + task_id = task["instance_action_id"] + "." + str(task["task_index"]) params = task["params"] - net_id = self.vim.new_network(*params) + vim_net_id = self.vim.new_network(*params) net_name = params[0] net_type = params[1] @@ -421,7 +624,7 @@ class vim_thread(threading.Thread): if sdn_controller and (net_type == "data" or net_type == "ptp"): network = {"name": net_name, "type": net_type, "region": self.vim["config"]["datacenter_id"]} - vim_net = self.vim.get_network(net_id) + vim_net = self.vim.get_network(vim_net_id) if vim_net.get('encapsulation') != 'vlan': raise vimconn.vimconnException( "net '{}' defined as type '{}' has not vlan encapsulation '{}'".format( @@ -432,165 +635,170 @@ class vim_thread(threading.Thread): sdn_net_id = self.ovim.new_network(network) except (ovimException, Exception) as e: self.logger.error("task=%s cannot create SDN network vim_net_id=%s input='%s' ovimException='%s'", - str(task_id), net_id, str(network), str(e)) - with self.db_lock: - self.db.update_rows("instance_nets", UPDATE={"vim_net_id": net_id, "sdn_net_id": sdn_net_id}, - WHERE={"vim_net_id": task_id}) - new_refresh_task = {"status": "enqueued", - "id": task_id, - "name": "get-net", - "vim_id": net_id, - "vim_info": {} } - self._insert_refresh(new_refresh_task, time.time()) - return True, net_id - except db_base_Exception as e: - self.logger.error("Error updating database %s", str(e)) - return True, net_id + str(task_id), vim_net_id, str(network), str(e)) + task["status"] = "DONE" + task["extra"]["vim_info"] = {} + task["extra"]["sdn_net_id"] = sdn_net_id + task["error_msg"] = None + task["vim_id"] = vim_net_id + instance_element_update = {"vim_net_id": vim_net_id, "sdn_net_id": sdn_net_id, "status": "BUILD", "error_msg": None} + return True, instance_element_update except vimconn.vimconnException as e: self.logger.error("Error creating NET, task=%s: %s", str(task_id), str(e)) - try: - with self.db_lock: - self.db.update_rows("instance_nets", - UPDATE={"error_msg": self._format_vim_error_msg(str(e)), "status": "VIM_ERROR"}, - WHERE={"vim_net_id": task_id}) - except db_base_Exception as e: - self.logger.error("Error updating database %s", str(e)) - return False, str(e) - #except ovimException as e: - # self.logger.error("Error creating NET in ovim, task=%s: %s", str(task_id), str(e)) - # return False, str(e) + task["status"] = "FAILED" + task["vim_id"] = None + task["error_msg"] = self._format_vim_error_msg(str(e)) + instance_element_update = {"vim_net_id": None, "sdn_net_id": None, "status": "VIM_ERROR", "error_msg": task["error_msg"]} + return False, instance_element_update def new_vm(self, task): try: params = task["params"] - task_id = task["id"] + task_id = task["instance_action_id"] + "." + str(task["task_index"]) depends = task.get("depends") net_list = params[5] error_text = "" for net in net_list: if "net_id" in net and is_task_id(net["net_id"]): # change task_id into network_id - try: + if net["net_id"] in depends: task_net = depends[net["net_id"]] - with self.task_lock: - if task_net["status"] == "error": - error_text = "Cannot create VM because depends on a network that cannot be created: " +\ - str(task_net["result"]) - break - elif task_net["status"] == "enqueued" or task_net["status"] == "processing": - error_text = "Cannot create VM because depends on a network still not created" - break - network_id = task_net["result"] - net["net_id"] = network_id - except Exception as e: - error_text = "Error trying to map from task_id={} to task result: {}".format( - net["net_id"],str(e)) - break - if not error_text: - vm_id = self.vim.new_vminstance(*params) - try: - with self.db_lock: - if error_text: - update = self.db.update_rows("instance_vms", - UPDATE={"status": "VIM_ERROR", "error_msg": error_text}, - WHERE={"vim_vm_id": task_id}) else: - update = self.db.update_rows("instance_vms", UPDATE={"vim_vm_id": vm_id}, WHERE={"vim_vm_id": task_id}) - if not update: - self.logger.error("task id={} name={} database not updated vim_vm_id={}".format( - task["id"], task["name"], vm_id)) - except db_base_Exception as e: - self.logger.error("Error updating database %s", str(e)) - if error_text: - return False, error_text - new_refresh_task = {"status": "enqueued", - "id": task_id, - "name": "get-vm", - "vim_id": vm_id, - "vim_info": {"interfaces":[]} } - self._insert_refresh(new_refresh_task, time.time()) - return True, vm_id - except vimconn.vimconnException as e: - self.logger.error("Error creating VM, task=%s: %s", str(task_id), str(e)) - try: + task_net = self._look_for_task(task["instance_action_id"], net["net_id"]) + if not task_net: + raise VimThreadException( + "Error trying to get depending task from task_index={}".format(net["net_id"])) + network_id = task_net.get("vim_id") + if not network_id: + raise VimThreadException( + "Cannot create VM because depends on a network not created or found: " + + str(task_net["error_msg"])) + net["net_id"] = network_id + vim_vm_id = self.vim.new_vminstance(*params) + + # fill task_interfaces. Look for snd_net_id at database for each interface + task_interfaces = {} + for iface in net_list: + task_interfaces[iface["vim_id"]] = {"iface_id": iface["uuid"]} with self.db_lock: - self.db.update_rows("instance_vms", - UPDATE={"error_msg": self._format_vim_error_msg(str(e)), "status": "VIM_ERROR"}, - WHERE={"vim_vm_id": task_id}) - except db_base_Exception as edb: - self.logger.error("Error updating database %s", str(edb)) - return False, str(e) + result = self.db.get_rows(SELECT=('sdn_net_id',), + FROM='instance_nets as ine join instance_interfaces as ii on ii.instance_net_id=ine.uuid', + WHERE={'ii.uuid': iface["uuid"]}) + if result: + task_interfaces[iface["vim_id"]]["sdn_net_id"] = result[0]['sdn_net_id'] + else: + self.logger.critical("Error creating VM, task=%s Network {} not found at DB", task_id, + iface["uuid"], exc_info=True) + + task["vim_info"] = {} + task["vim_interfaces"] = {} + task["extra"]["interfaces"] = task_interfaces + task["error_msg"] = None + task["status"] = "DONE" + task["vim_id"] = vim_vm_id + instance_element_update = {"status": "BUILD", "vim_vm_id": vim_vm_id, "error_msg": None} + return True, instance_element_update + + except (vimconn.vimconnException, VimThreadException) as e: + self.logger.error("Error creating VM, task=%s: %s", task_id, str(e)) + error_text = self._format_vim_error_msg(str(e)) + task["error_msg"] = error_text + task["status"] = "FAILED" + task["vim_id"] = None + instance_element_update = {"status": "VIM_ERROR", "vim_vm_id": None, "error_msg": error_text} + return False, instance_element_update def del_vm(self, task): - vm_id = task["params"][0] - interfaces = task["params"][1] - if is_task_id(vm_id): - try: - task_create = task["depends"][vm_id] - with self.task_lock: - if task_create["status"] == "error": - return True, "VM was not created. It has error: " + str(task_create["result"]) - elif task_create["status"] == "enqueued" or task_create["status"] == "processing": - return False, "Cannot delete VM vim_id={} because still creating".format(vm_id) - vm_id = task_create["result"] - except Exception as e: - return False, "Error trying to get task_id='{}':".format(vm_id, str(e)) + vm_vim_id = task["vim_id"] + interfaces = task["extra"].get("interfaces", ()) try: - self._remove_refresh("get-vm", vm_id) - for iface in interfaces: + for iface in interfaces.values(): if iface.get("sdn_port_id"): try: with self.db_lock: self.ovim.delete_port(iface["sdn_port_id"]) except ovimException as e: self.logger.error("ovimException deleting external_port={} at VM vim_id={} deletion ".format( - iface["sdn_port_id"], vm_id) + str(e), exc_info=True) + iface["sdn_port_id"], vm_vim_id) + str(e), exc_info=True) # TODO Set error_msg at instance_nets - return True, self.vim.delete_vminstance(vm_id) + self.vim.delete_vminstance(vm_vim_id) + task["status"] = "DONE" + task["error_msg"] = None + return True, None + except vimconn.vimconnException as e: - return False, str(e) + task["error_msg"] = self._format_vim_error_msg(str(e)) + if isinstance(e, vimconn.vimconnNotFoundException): + # If not found mark as Done and fill error_msg + task["status"] = "DONE" + return True, None + task["status"] = "FAILED" + return False, None def del_net(self, task): - net_id = task["params"][0] - sdn_net_id = task["params"][1] - if is_task_id(net_id): - try: - task_create = task["depends"][net_id] - with self.task_lock: - if task_create["status"] == "error": - return True, "net was not created. It has error: " + str(task_create["result"]) - elif task_create["status"] == "enqueued" or task_create["status"] == "processing": - return False, "Cannot delete net because still creating" - net_id = task_create["result"] - except Exception as e: - return False, "Error trying to get task_id='{}':".format(net_id, str(e)) + net_vim_id = task["vim_id"] + sdn_net_id = task["extra"].get("sdn_net_id") try: - self._remove_refresh("get-net", net_id) - result = self.vim.delete_network(net_id) if sdn_net_id: - # Delete any attached port to this sdn network - # At this point, there will be ports associated to this network in case it was manually done using 'openmano vim-net-sdn-attach' - try: - with self.db_lock: - port_list = self.ovim.get_ports(columns={'uuid'}, filter={'name': 'external_port', 'net_id': sdn_net_id}) - except ovimException as e: - raise vimconn.vimconnException( - "ovimException obtaining external ports for net {}. ".format(sdn_net_id) + str(e)) - - for port in port_list: - try: - with self.db_lock: - self.ovim.delete_port(port['uuid']) - except ovimException as e: - raise vimconn.vimconnException( - "ovimException deleting port {} for net {}. ".format(port['uuid'], sdn_net_id) + str(e)) + # Delete any attached port to this sdn network. There can be ports associated to this network in case + # it was manually done using 'openmano vim-net-sdn-attach' with self.db_lock: + port_list = self.ovim.get_ports(columns={'uuid'}, + filter={'name': 'external_port', 'net_id': sdn_net_id}) + for port in port_list: + self.ovim.delete_port(port['uuid']) self.ovim.delete_network(sdn_net_id) - return True, result - except vimconn.vimconnException as e: - return False, str(e) + self.vim.delete_network(net_vim_id) + task["status"] = "DONE" + task["error_msg"] = None + return True, None except ovimException as e: - logging.error("Error deleting network from ovim. net_id: {}, sdn_net_id: {}".format(net_id, sdn_net_id)) - return False, str(e) - - + task["error_msg"] = self._format_vim_error_msg("ovimException obtaining and deleting external " + "ports for net {}: {}".format(sdn_net_id, str(e))) + except vimconn.vimconnException as e: + task["error_msg"] = self._format_vim_error_msg(str(e)) + if isinstance(e, vimconn.vimconnNotFoundException): + # If not found mark as Done and fill error_msg + task["status"] = "DONE" + return True, None + task["status"] = "FAILED" + return False, None + + def get_net(self, task): + try: + task_id = task["instance_action_id"] + "." + str(task["task_index"]) + params = task["params"] + filter = params[0] + vim_nets = self.vim.get_network_list(filter) + if not vim_nets: + raise VimThreadException("Network not found with this criteria: '{}'".format(filter)) + elif len(vim_nets) > 1: + raise VimThreadException("More than one network found with this criteria: '{}'".format(filter)) + vim_net_id = vim_nets[0]["id"] + + # Discover if this network is managed by a sdn controller + sdn_net_id = None + with self.db_lock: + result = self.db.get_rows(SELECT=('sdn_net_id',), FROM='instance_nets', + WHERE={'vim_net_id': vim_net_id, 'instance_scenario_id': None, + 'datacenter_tenant_id': self.datacenter_tenant_id}) + if result: + sdn_net_id = result[0]['sdn_net_id'] + + task["status"] = "DONE" + task["extra"]["vim_info"] = {} + task["extra"]["created"] = False + task["extra"]["sdn_net_id"] = sdn_net_id + task["error_msg"] = None + task["vim_id"] = vim_net_id + instance_element_update = {"vim_net_id": vim_net_id, "created": False, "status": "BUILD", + "error_msg": None} + return True, instance_element_update + except (vimconn.vimconnException, VimThreadException) as e: + self.logger.error("Error looking for NET, task=%s: %s", str(task_id), str(e)) + task["status"] = "FAILED" + task["vim_id"] = None + task["error_msg"] = self._format_vim_error_msg(str(e)) + instance_element_update = {"vim_net_id": None, "status": "VIM_ERROR", + "error_msg": task["error_msg"]} + return False, instance_element_update -- 2.25.1