Added LICENSE file to root folder
[osm/openvim.git] / osm_openvim / host_thread.py
index 620f25c..ed6551f 100644 (file)
@@ -1,7 +1,7 @@
 # -*- coding: utf-8 -*-
 
 ##
-# Copyright 2015 Telefónica Investigación y Desarrollo, S.A.U.
+# Copyright 2015 Telefonica Investigacion y Desarrollo, S.A.U.
 # This file is part of openvim
 # All Rights Reserved.
 #
@@ -34,7 +34,7 @@ import threading
 import time
 import Queue
 import paramiko
-import subprocess
+import subprocess
 # import libvirt
 import imp
 import random
@@ -43,29 +43,31 @@ import logging
 from jsonschema import validate as js_v, exceptions as js_e
 from vim_schema import localinfo_schema, hostinfo_schema
 
+class RunCommandException(Exception):
+    pass
 
 class host_thread(threading.Thread):
     lvirt_module = None
 
-    def __init__(self, name, host, user, db, db_lock, test, image_path, host_id, version, develop_mode,
-                 develop_bridge_iface, password=None, keyfile = None, logger_name=None, debug=None):
-        '''Init a thread.
-        Arguments:
-            'id' number of thead
-            'name' name of thread
-            'host','user':  host ip or name to manage and user
-            'db', 'db_lock': database class and lock to use it in exclusion
-        '''
+    def __init__(self, name, host, user, db, test, image_path, host_id, version, develop_mode,
+                 develop_bridge_iface, password=None, keyfile = None, logger_name=None, debug=None, hypervisors=None):
+        """Init a thread to communicate with compute node or ovs_controller.
+        :param host_id: host identity
+        :param name: name of the thread
+        :param host: host ip or name to manage and user
+        :param user, password, keyfile: user and credentials to connect to host
+        :param db: database class, threading safe
+        """
         threading.Thread.__init__(self)
         self.name = name
         self.host = host
         self.user = user
         self.db = db
-        self.db_lock = db_lock
         self.test = test
         self.password = password
-        self.keyfile =  keyfile
+        self.keyfile = keyfile
         self.localinfo_dirty = False
+        self.connectivity = True
 
         if not test and not host_thread.lvirt_module:
             try:
@@ -85,26 +87,114 @@ class host_thread(threading.Thread):
         self.develop_mode = develop_mode
         self.develop_bridge_iface = develop_bridge_iface
         self.image_path = image_path
+        self.empty_image_path = image_path
         self.host_id = host_id
         self.version = version
         
         self.xml_level = 0
-        #self.pending ={}
+        # self.pending ={}
         
         self.server_status = {} #dictionary with pairs server_uuid:server_status 
         self.pending_terminate_server =[] #list  with pairs (time,server_uuid) time to send a terminate for a server being destroyed
         self.next_update_server_status = 0 #time when must be check servers status
         
+#######        self.hypervisor = "kvm" #hypervisor flag (default: kvm)
+        if hypervisors:
+            self.hypervisors = hypervisors
+        else:
+            self.hypervisors = "kvm"
+
+        self.xen_hyp = True if "xen" in self.hypervisors else False
+
         self.hostinfo = None 
         
         self.queueLock = threading.Lock()
         self.taskQueue = Queue.Queue(2000)
         self.ssh_conn = None
-        self.lvirt_conn_uri = "qemu+ssh://{user}@{host}/system?no_tty=1&no_verify=1".format(
-            user=self.user, host=self.host)
+        self.run_command_session = None
+        self.error = None
+        self.localhost = True if host == 'localhost' else False
+
+        if self.xen_hyp:
+            self.lvirt_conn_uri = "xen+ssh://{user}@{host}/?no_tty=1&no_verify=1".format(
+                user=self.user, host=self.host)
+        else:
+            self.lvirt_conn_uri = "qemu+ssh://{user}@{host}/system?no_tty=1&no_verify=1".format(
+                user=self.user, host=self.host)
         if keyfile:
             self.lvirt_conn_uri += "&keyfile=" + keyfile
 
+        self.remote_ip = None
+        self.local_ip = None
+
+    def run_command(self, command, keep_session=False, ignore_exit_status=False):
+        """Run a command passed as a str on a localhost or at remote machine.
+        :param command: text with the command to execute.
+        :param keep_session: if True it returns a <stdin> for sending input with '<stdin>.write("text\n")'.
+                A command with keep_session=True MUST be followed by a command with keep_session=False in order to
+                close the session and get the output
+        :param ignore_exit_status: Return stdout and not raise an exepction in case of error.
+        :return: the output of the command if 'keep_session=False' or the <stdin> object if 'keep_session=True'
+        :raises: RunCommandException if command fails
+        """
+        if self.run_command_session and keep_session:
+            raise RunCommandException("Internal error. A command with keep_session=True must be followed by another "
+                                      "command with keep_session=False to close session")
+        try:
+            if self.localhost:
+                if self.run_command_session:
+                    p = self.run_command_session
+                    self.run_command_session = None
+                    (output, outerror) = p.communicate()
+                    returncode = p.returncode
+                    p.stdin.close()
+                elif keep_session:
+                    p = subprocess.Popen(('bash', "-c", command), stdin=subprocess.PIPE, stdout=subprocess.PIPE,
+                                         stderr=subprocess.PIPE)
+                    self.run_command_session = p
+                    return p.stdin
+                else:
+                    if not ignore_exit_status:
+                        output = subprocess.check_output(('bash', "-c", command))
+                        returncode = 0
+                    else:
+                        out = None
+                        p = subprocess.Popen(('bash', "-c", command), stdout=subprocess.PIPE)
+                        out, err = p.communicate()
+                        return out
+            else:
+                if self.run_command_session:
+                    (i, o, e) = self.run_command_session
+                    self.run_command_session = None
+                    i.channel.shutdown_write()
+                else:
+                    if not self.ssh_conn:
+                        self.ssh_connect()
+                    (i, o, e) = self.ssh_conn.exec_command(command, timeout=10)
+                    if keep_session:
+                        self.run_command_session = (i, o, e)
+                        return i
+                returncode = o.channel.recv_exit_status()
+                output = o.read()
+                outerror = e.read()
+            if returncode != 0 and not ignore_exit_status:
+                text = "run_command='{}' Error='{}'".format(command, outerror)
+                self.logger.error(text)
+                raise RunCommandException(text)
+
+            self.logger.debug("run_command='{}' result='{}'".format(command, output))
+            return output
+
+        except RunCommandException:
+            raise
+        except subprocess.CalledProcessError as e:
+            text = "run_command Exception '{}' '{}'".format(str(e), e.output)
+        except (paramiko.ssh_exception.SSHException, Exception) as e:
+            text = "run_command='{}' Exception='{}'".format(command, str(e))
+        self.ssh_conn = None
+        self.run_command_session = None
+        raise RunCommandException(text)
+
     def ssh_connect(self):
         try:
             # Connect SSH
@@ -112,42 +202,38 @@ class host_thread(threading.Thread):
             self.ssh_conn.set_missing_host_key_policy(paramiko.AutoAddPolicy())
             self.ssh_conn.load_system_host_keys()
             self.ssh_conn.connect(self.host, username=self.user, password=self.password, key_filename=self.keyfile,
-                                  timeout=10) #, None)
-        except paramiko.ssh_exception.SSHException as e:
-            text = e.args[0]
-            self.logger.error("ssh_connect ssh Exception: " + text)
+                                        timeout=10) # auth_timeout=10)
+            self.remote_ip = self.ssh_conn.get_transport().sock.getpeername()[0]
+            self.local_ip = self.ssh_conn.get_transport().sock.getsockname()[0]
+        except (paramiko.ssh_exception.SSHException, Exception) as e:
+            text = 'ssh connect Exception: {}'.format(e)
+            self.ssh_conn = None
+            self.error = text
+            raise
+
+    def check_connectivity(self):
+        if not self.test:
+            try:
+                command = 'sudo brctl show'
+                self.run_command(command)
+            except RunCommandException as e:
+                self.connectivity = False
+                self.logger.error("check_connectivity Exception: " + str(e))
 
     def load_localinfo(self):
         if not self.test:
             try:
-                # Connect SSH
-                self.ssh_connect()
-
-                command = 'mkdir -p ' +  self.image_path
-                # print self.name, ': command:', command
-                (_, stdout, stderr) = self.ssh_conn.exec_command(command)
-                content = stderr.read()
-                if len(content) > 0:
-                    self.logger.error("command: '%s' stderr: '%s'", command, content)
-
-                command = 'cat ' +  self.image_path + '/.openvim.yaml'
-                # print self.name, ': command:', command
-                (_, stdout, stderr) = self.ssh_conn.exec_command(command)
-                content = stdout.read()
-                if len(content) == 0:
-                    self.logger.error("command: '%s' stderr='%s'", command, stderr.read())
-                    raise paramiko.ssh_exception.SSHException("Error empty file, command: '{}'".format(command))
-                self.localinfo = yaml.load(content)
+                self.run_command('sudo mkdir -p ' + self.image_path)
+                result = self.run_command('cat {}/.openvim.yaml'.format(self.image_path))
+                self.localinfo = yaml.load(result)
                 js_v(self.localinfo, localinfo_schema)
                 self.localinfo_dirty = False
                 if 'server_files' not in self.localinfo:
                     self.localinfo['server_files'] = {}
-                self.logger.debug("localinfo load from host")
+                self.logger.debug("localinfo loaded from host")
                 return
-
-            except paramiko.ssh_exception.SSHException as e:
-                text = e.args[0]
-                self.logger.error("load_localinfo ssh Exception: " + text)
+            except RunCommandException as e:
+                self.logger.error("load_localinfo Exception: " + str(e))
             except host_thread.lvirt_module.libvirtError as e:
                 text = e.get_error_message()
                 self.logger.error("load_localinfo libvirt Exception: " + text)
@@ -165,34 +251,22 @@ class host_thread(threading.Thread):
                 text = str(e)
                 self.logger.error("load_localinfo Exception: " + text)
         
-        #not loaded, insert a default data and force saving by activating dirty flag
+        # not loaded, insert a default data and force saving by activating dirty flag
         self.localinfo = {'files':{}, 'server_files':{} } 
-        #self.localinfo_dirty=True
+        # self.localinfo_dirty=True
         self.localinfo_dirty=False
 
     def load_hostinfo(self):
         if self.test:
-            return;
+            return
         try:
-            #Connect SSH
-            self.ssh_connect()
-
-
-            command = 'cat ' +  self.image_path + '/hostinfo.yaml'
-            #print self.name, ': command:', command
-            (_, stdout, stderr) = self.ssh_conn.exec_command(command)
-            content = stdout.read()
-            if len(content) == 0:
-                self.logger.error("command: '%s' stderr: '%s'", command, stderr.read())
-                raise paramiko.ssh_exception.SSHException("Error empty file ")
-            self.hostinfo = yaml.load(content)
+            result = self.run_command('cat {}/hostinfo.yaml'.format(self.image_path))
+            self.hostinfo = yaml.load(result)
             js_v(self.hostinfo, hostinfo_schema)
-            self.logger.debug("hostlinfo load from host " + str(self.hostinfo))
+            self.logger.debug("hostinfo load from host " + str(self.hostinfo))
             return
-
-        except paramiko.ssh_exception.SSHException as e:
-            text = e.args[0]
-            self.logger.error("load_hostinfo ssh Exception: " + text)
+        except RunCommandException as e:
+            self.logger.error("load_hostinfo ssh Exception: " + str(e))
         except host_thread.lvirt_module.libvirtError as e:
             text = e.get_error_message()
             self.logger.error("load_hostinfo libvirt Exception: " + text)
@@ -205,7 +279,7 @@ class host_thread(threading.Thread):
         except js_e.ValidationError as e:
             text = ""
             if len(e.path)>0: text=" at '" + ":".join(map(str, e.path))+"'"
-            self.logger.error("load_hostinfo format Exception: %s %s", text, e.message)
+            self.logger.error("load_hostinfo format Exception: %s %s", text, str(e))
         except Exception as e:
             text = str(e)
             self.logger.error("load_hostinfo Exception: " + text)
@@ -222,18 +296,17 @@ class host_thread(threading.Thread):
             tries-=1
             
             try:
-                command = 'cat > ' +  self.image_path + '/.openvim.yaml'
-                self.logger.debug("command:" + command)
-                (stdin, _, _) = self.ssh_conn.exec_command(command)
-                yaml.safe_dump(self.localinfo, stdin, explicit_start=True, indent=4, default_flow_style=False, tags=False, encoding='utf-8', allow_unicode=True)
+                command = 'cat > {}/.openvim.yaml'.format(self.image_path)
+                in_stream = self.run_command(command, keep_session=True)
+                yaml.safe_dump(self.localinfo, in_stream, explicit_start=True, indent=4, default_flow_style=False,
+                               tags=False, encoding='utf-8', allow_unicode=True)
+                result = self.run_command(command, keep_session=False)   # to end session
+
                 self.localinfo_dirty = False
                 break #while tries
-    
-            except paramiko.ssh_exception.SSHException as e:
-                text = e.args[0]
-                self.logger.error("save_localinfo ssh Exception: " + text)
-                if "SSH session not active" in text:
-                    self.ssh_connect()
+
+            except RunCommandException as e:
+                self.logger.error("save_localinfo ssh Exception: " + str(e))
             except host_thread.lvirt_module.libvirtError as e:
                 text = e.get_error_message()
                 self.logger.error("save_localinfo libvirt Exception: " + text)
@@ -248,9 +321,7 @@ class host_thread(threading.Thread):
                 self.logger.error("save_localinfo Exception: " + text)
 
     def load_servers_from_db(self):
-        self.db_lock.acquire()
         r,c = self.db.get_table(SELECT=('uuid','status', 'image_id'), FROM='instances', WHERE={'host_id': self.host_id})
-        self.db_lock.release()
 
         self.server_status = {}
         if r<0:
@@ -283,7 +354,7 @@ class host_thread(threading.Thread):
                     try:
                         self.logger.debug("deleting file '%s' of unused server '%s'", localfile['source file'], uuid)
                         self.delete_file(localfile['source file'])
-                    except paramiko.ssh_exception.SSHException as e:
+                    except RunCommandException as e:
                         self.logger.error("Exception deleting file '%s': %s", localfile['source file'], str(e))
                 del self.localinfo['server_files'][uuid]
                 self.localinfo_dirty = True
@@ -428,8 +499,13 @@ class host_thread(threading.Thread):
             bus_ide = True if bus=='ide' else False
             
         self.xml_level = 0
+        hypervisor = server.get('hypervisor', 'kvm')
+        os_type_img = server.get('os_image_type', 'other')
 
-        text = "<domain type='kvm'>"
+        if hypervisor[:3] == 'xen':
+            text = "<domain type='xen'>"
+        else:
+            text = "<domain type='kvm'>"
     #get topology
         topo = server_metadata.get('topology', None)
         if topo == None and 'metadata' in dev_list[0]:
@@ -503,12 +579,26 @@ class host_thread(threading.Thread):
             if dev['type']=='cdrom' :
                 boot_cdrom = True
                 break
-        text += self.tab()+ '<os>' + \
-            self.inc_tab() + "<type arch='x86_64' machine='pc'>hvm</type>"
-        if boot_cdrom:
-            text +=  self.tab() + "<boot dev='cdrom'/>" 
-        text +=  self.tab() + "<boot dev='hd'/>" + \
-            self.dec_tab()+'</os>'
+        if hypervisor == 'xenhvm':
+            text += self.tab()+ '<os>' + \
+                self.inc_tab() + "<type arch='x86_64' machine='xenfv'>hvm</type>"
+            text += self.tab() + "<loader type='rom'>/usr/lib/xen/boot/hvmloader</loader>"
+            if boot_cdrom:
+                text +=  self.tab() + "<boot dev='cdrom'/>" 
+            text +=  self.tab() + "<boot dev='hd'/>" + \
+                self.dec_tab()+'</os>'
+        elif hypervisor == 'xen-unik':
+            text += self.tab()+ '<os>' + \
+                self.inc_tab() + "<type arch='x86_64' machine='xenpv'>xen</type>"
+            text +=  self.tab() + "<kernel>" + str(dev_list[0]['source file']) + "</kernel>" + \
+                self.dec_tab()+'</os>'
+        else:
+            text += self.tab()+ '<os>' + \
+                self.inc_tab() + "<type arch='x86_64' machine='pc'>hvm</type>"
+            if boot_cdrom:
+                text +=  self.tab() + "<boot dev='cdrom'/>" 
+            text +=  self.tab() + "<boot dev='hd'/>" + \
+                self.dec_tab()+'</os>'
     #features
         text += self.tab()+'<features>'+\
             self.inc_tab()+'<acpi/>' +\
@@ -527,14 +617,29 @@ class host_thread(threading.Thread):
             self.tab() + "<on_poweroff>preserve</on_poweroff>" + \
             self.tab() + "<on_reboot>restart</on_reboot>" + \
             self.tab() + "<on_crash>restart</on_crash>"
-        text += self.tab() + "<devices>" + \
-            self.inc_tab() + "<emulator>/usr/libexec/qemu-kvm</emulator>" + \
-            self.tab() + "<serial type='pty'>" +\
-            self.inc_tab() + "<target port='0'/>" + \
-            self.dec_tab() + "</serial>" +\
-            self.tab() + "<console type='pty'>" + \
-            self.inc_tab()+ "<target type='serial' port='0'/>" + \
-            self.dec_tab()+'</console>'
+        if hypervisor == 'xenhvm':
+            text += self.tab() + "<devices>" + \
+                self.inc_tab() + "<emulator>/usr/bin/qemu-system-i386</emulator>" + \
+                self.tab() + "<serial type='pty'>" +\
+                self.inc_tab() + "<target port='0'/>" + \
+                self.dec_tab() + "</serial>" +\
+                self.tab() + "<console type='pty'>" + \
+                self.inc_tab()+ "<target type='serial' port='0'/>" + \
+                self.dec_tab()+'</console>' #In some libvirt version may be: <emulator>/usr/lib64/xen/bin/qemu-dm</emulator> (depends on distro)
+        elif hypervisor == 'xen-unik':
+            text += self.tab() + "<devices>" + \
+                self.tab() + "<console type='pty'>" + \
+                self.inc_tab()+ "<target type='xen' port='0'/>" + \
+                self.dec_tab()+'</console>'
+        else:
+            text += self.tab() + "<devices>" + \
+                self.inc_tab() + "<emulator>/usr/libexec/qemu-kvm</emulator>" + \
+                self.tab() + "<serial type='pty'>" +\
+                self.inc_tab() + "<target port='0'/>" + \
+                self.dec_tab() + "</serial>" +\
+                self.tab() + "<console type='pty'>" + \
+                self.inc_tab()+ "<target type='serial' port='0'/>" + \
+                self.dec_tab()+'</console>'
         if windows_os:
             text += self.tab() + "<controller type='usb' index='0'/>" + \
                 self.tab() + "<controller type='ide' index='0'/>" + \
@@ -545,6 +650,15 @@ class host_thread(threading.Thread):
                 self.dec_tab() + "</video>" + \
                 self.tab() + "<memballoon model='virtio'/>" + \
                 self.tab() + "<input type='tablet' bus='usb'/>" #TODO revisar
+        elif hypervisor == 'xen-unik':
+            pass
+        else:
+            text += self.tab() + "<controller type='ide' index='0'/>" + \
+                self.tab() + "<input type='mouse' bus='ps2'/>" + \
+                self.tab() + "<input type='keyboard' bus='ps2'/>" + \
+                self.tab() + "<video>" + \
+                self.inc_tab() + "<model type='cirrus' vram='9216' heads='1'/>" + \
+                self.dec_tab() + "</video>"
 
 #>             self.tab()+'<alias name=\'hostdev0\'/>\n' +\
 #>             self.dec_tab()+'</hostdev>\n' +\
@@ -561,7 +675,7 @@ class host_thread(threading.Thread):
         vd_index = 'a'
         for dev in dev_list:
             bus_ide_dev = bus_ide
-            if dev['type']=='cdrom' or dev['type']=='disk':
+            if (dev['type']=='cdrom' or dev['type']=='disk') and hypervisor != 'xen-unik':
                 if dev['type']=='cdrom':
                     bus_ide_dev = True
                 text += self.tab() + "<disk type='file' device='"+dev['type']+"'>"
@@ -574,7 +688,7 @@ class host_thread(threading.Thread):
                 #else:
                 #    return -1, 'Unknown disk type ' + v['type']
                 vpci = dev.get('vpci',None)
-                if vpci == None:
+                if vpci == None and 'metadata' in dev:
                     vpci = dev['metadata'].get('vpci',None)
                 text += self.pci2xml(vpci)
                
@@ -596,6 +710,8 @@ class host_thread(threading.Thread):
                     dev_text = dev_text.replace('__dev__', vd_index)
                     vd_index = chr(ord(vd_index)+1)
                 text += dev_text
+            elif hypervisor == 'xen-unik':
+                pass
             else:
                 return -1, 'Unknown device type ' + dev['type']
 
@@ -603,9 +719,7 @@ class host_thread(threading.Thread):
         bridge_interfaces = server.get('networks', [])
         for v in bridge_interfaces:
             #Get the brifge name
-            self.db_lock.acquire()
             result, content = self.db.get_table(FROM='nets', SELECT=('provider',),WHERE={'uuid':v['net_id']} )
-            self.db_lock.release()
             if result <= 0:
                 self.logger.error("create_xml_server ERROR %d getting nets %s", result, content)
                 return -1, content
@@ -636,6 +750,8 @@ class host_thread(threading.Thread):
                 vlan = content[0]['provider'].replace('OVS:', '')
                 text += self.tab() + "<interface type='bridge'>" + \
                         self.inc_tab() + "<source bridge='ovim-" + str(vlan) + "'/>"
+                if hypervisor == 'xenhvm' or hypervisor == 'xen-unik':
+                    text += self.tab() + "<script path='vif-openvswitch'/>"
             else:
                 return -1, 'Unknown Bridge net provider ' + content[0]['provider']
             if model!=None:
@@ -730,18 +846,14 @@ class host_thread(threading.Thread):
         Create a bridge in compute OVS to allocate VMs
         :return: True if success
         """
-        if self.test:
+        if self.test or not self.connectivity:
             return True
+
         try:
-            command = 'sudo ovs-vsctl --may-exist add-br br-int -- set Bridge br-int stp_enable=true'
-            self.logger.debug("command: " + command)
-            (_, stdout, _) = self.ssh_conn.exec_command(command)
-            content = stdout.read()
-            if len(content) == 0:
-                return True
-            else:
-                return False
-        except paramiko.ssh_exception.SSHException as e:
+            self.run_command('sudo ovs-vsctl --may-exist add-br br-int -- set Bridge br-int stp_enable=true')
+
+            return True
+        except RunCommandException as e:
             self.logger.error("create_ovs_bridge ssh Exception: " + str(e))
             if "SSH session not active" in str(e):
                 self.ssh_connect()
@@ -755,22 +867,15 @@ class host_thread(threading.Thread):
         :return:
         """
 
-        if self.test:
+        if self.test or not self.connectivity:
             return True
         try:
-            port_name = 'ovim-' + str(vlan)
-            command = 'sudo ovs-vsctl del-port br-int ' + port_name
-            self.logger.debug("command: " + command)
-            (_, stdout, _) = self.ssh_conn.exec_command(command)
-            content = stdout.read()
-            if len(content) == 0:
-                return True
-            else:
-                return False
-        except paramiko.ssh_exception.SSHException as e:
-            self.logger.error("delete_port_to_ovs_bridge ssh Exception: " + str(e))
-            if "SSH session not active" in str(e):
-                self.ssh_connect()
+            port_name = 'ovim-{}'.format(str(vlan))
+            command = 'sudo ovs-vsctl del-port br-int {}'.format(port_name)
+            self.run_command(command)
+            return True
+        except RunCommandException as e:
+            self.logger.error("delete_port_to_ovs_bridge ssh Exception: {}".format(str(e)))
             return False
 
     def delete_dhcp_server(self, vlan, net_uuid, dhcp_path):
@@ -781,33 +886,23 @@ class host_thread(threading.Thread):
         :param dhcp_path: conf fiel path that live in namespace side
         :return:
         """
-        if self.test:
+        if self.test or not self.connectivity:
             return True
         if not self.is_dhcp_port_free(vlan, net_uuid):
             return True
         try:
-            net_namespace = 'ovim-' + str(vlan)
-            dhcp_path = os.path.join(dhcp_path, net_namespace)
+            dhcp_namespace = '{}-dnsmasq'.format(str(vlan))
+            dhcp_path = os.path.join(dhcp_path, dhcp_namespace)
             pid_file = os.path.join(dhcp_path, 'dnsmasq.pid')
 
-            command = 'sudo ip netns exec ' + net_namespace + ' cat ' + pid_file
-            self.logger.debug("command: " + command)
-            (_, stdout, _) = self.ssh_conn.exec_command(command)
-            content = stdout.read()
-
-            command = 'sudo ip netns exec ' + net_namespace + ' kill -9 ' + content
-            self.logger.debug("command: " + command)
-            (_, stdout, _) = self.ssh_conn.exec_command(command)
-            content = stdout.read()
+            command = 'sudo ip netns exec {} cat {}'.format(dhcp_namespace, pid_file)
+            content = self.run_command(command, ignore_exit_status=True)
+            dns_pid = content.replace('\n', '')
+            command = 'sudo ip netns exec {} kill -9 {}'.format(dhcp_namespace, dns_pid)
+            self.run_command(command, ignore_exit_status=True)
 
-            # if len(content) == 0:
-            #     return True
-            # else:
-            #     return False
-        except paramiko.ssh_exception.SSHException as e:
+        except RunCommandException as e:
             self.logger.error("delete_dhcp_server ssh Exception: " + str(e))
-            if "SSH session not active" in str(e):
-                self.ssh_connect()
             return False
 
     def is_dhcp_port_free(self, host_id, net_uuid):
@@ -817,12 +912,10 @@ class host_thread(threading.Thread):
         :param net_uuid: network id
         :return: True if is not free
         """
-        self.db_lock.acquire()
         result, content = self.db.get_table(
             FROM='ports',
             WHERE={'type': 'instance:ovs', 'net_id': net_uuid}
         )
-        self.db_lock.release()
 
         if len(content) > 0:
             return False
@@ -837,12 +930,10 @@ class host_thread(threading.Thread):
         :return: True if is not free
         """
 
-        self.db_lock.acquire()
         result, content = self.db.get_table(
             FROM='ports as p join instances as i on p.instance_id=i.uuid',
             WHERE={"i.host_id": self.host_id, 'p.type': 'instance:ovs', 'p.net_id': net_uuid}
         )
-        self.db_lock.release()
 
         if len(content) > 0:
             return False
@@ -859,22 +950,15 @@ class host_thread(threading.Thread):
         if self.test:
             return True
         try:
-            port_name = 'ovim-' + str(vlan)
-            command = 'sudo ovs-vsctl add-port br-int ' + port_name + ' tag=' + str(vlan)
-            self.logger.debug("command: " + command)
-            (_, stdout, _) = self.ssh_conn.exec_command(command)
-            content = stdout.read()
-            if len(content) == 0:
-                return True
-            else:
-                return False
-        except paramiko.ssh_exception.SSHException as e:
-            self.logger.error("add_port_to_ovs_bridge ssh Exception: " + str(e))
-            if "SSH session not active" in str(e):
-                self.ssh_connect()
+            port_name = 'ovim-{}'.format(str(vlan))
+            command = 'sudo ovs-vsctl add-port br-int {} tag={}'.format(port_name, str(vlan))
+            self.run_command(command)
+            return True
+        except RunCommandException as e:
+            self.logger.error("add_port_to_ovs_bridge Exception: " + str(e))
             return False
 
-    def delete_dhcp_port(self, vlan, net_uuid):
+    def delete_dhcp_port(self, vlan, net_uuid, dhcp_path):
         """
         Delete from an existing OVS bridge a linux bridge port attached and the linux bridge itself.
         :param vlan: segmentation id
@@ -887,7 +971,7 @@ class host_thread(threading.Thread):
 
         if not self.is_dhcp_port_free(vlan, net_uuid):
             return True
-        self.delete_dhcp_interfaces(vlan)
+        self.delete_dhcp_interfaces(vlan, dhcp_path)
         return True
 
     def delete_bridge_port_attached_to_ovs(self, vlan, net_uuid):
@@ -916,26 +1000,53 @@ class host_thread(threading.Thread):
         if self.test:
             return True
         try:
-            port_name = 'ovim-' + str(vlan)
-            command = 'sudo ip link set dev veth0-' + str(vlan) + ' down'
-            self.logger.debug("command: " + command)
-            (_, stdout, _) = self.ssh_conn.exec_command(command)
-            # content = stdout.read()
-            #
-            # if len(content) != 0:
-            #     return False
-            command = 'sudo ifconfig ' + port_name + ' down &&  sudo brctl delbr ' + port_name
-            self.logger.debug("command: " + command)
-            (_, stdout, _) = self.ssh_conn.exec_command(command)
-            content = stdout.read()
-            if len(content) == 0:
-                return True
-            else:
-                return False
-        except paramiko.ssh_exception.SSHException as e:
-            self.logger.error("delete_linux_bridge ssh Exception: " + str(e))
-            if "SSH session not active" in str(e):
-                self.ssh_connect()
+            port_name = 'ovim-{}'.format(str(vlan))
+            command = 'sudo ip link set dev ovim-{} down'.format(str(vlan))
+            self.run_command(command)
+
+            command = 'sudo  ip link delete  {}  &&  sudo brctl delbr {}'.format(port_name, port_name)
+            self.run_command(command)
+            return True
+        except RunCommandException as e:
+            self.logger.error("delete_linux_bridge Exception: {}".format(str(e)))
+            return False
+
+    def remove_link_bridge_to_ovs(self, vlan, link):
+        """
+        Delete a linux provider net connection to tenatn net
+        :param vlan: vlan port id
+        :param link: link name
+        :return: True if success
+        """
+
+        if self.test:
+            return True
+        try:
+            br_tap_name = '{}-vethBO'.format(str(vlan))
+            br_ovs_name = '{}-vethOB'.format(str(vlan))
+
+            # Delete ovs veth pair
+            command = 'sudo ip link set dev {} down'.format(br_ovs_name)
+            self.run_command(command, ignore_exit_status=True)
+
+            command = 'sudo ovs-vsctl del-port br-int {}'.format(br_ovs_name)
+            self.run_command(command)
+
+            # Delete br veth pair
+            command = 'sudo ip link set dev {} down'.format(br_tap_name)
+            self.run_command(command, ignore_exit_status=True)
+
+            # Delete br veth interface form bridge
+            command = 'sudo brctl delif {} {}'.format(link, br_tap_name)
+            self.run_command(command)
+
+            # Delete br veth pair
+            command = 'sudo ip link set dev {} down'.format(link)
+            self.run_command(command, ignore_exit_status=True)
+
+            return True
+        except RunCommandException as e:
+            self.logger.error("remove_link_bridge_to_ovs Exception: {}".format(str(e)))
             return False
 
     def create_ovs_bridge_port(self, vlan):
@@ -959,51 +1070,24 @@ class host_thread(threading.Thread):
         if self.test:
             return True
         try:
-            port_name = 'ovim-' + str(vlan)
-            command = 'sudo brctl show | grep ' + port_name
-            self.logger.debug("command: " + command)
-            (_, stdout, _) = self.ssh_conn.exec_command(command)
-            content = stdout.read()
-
-            # if exist nothing to create
-            # if len(content) == 0:
-            #     return False
-
-            command = 'sudo brctl addbr ' + port_name
-            self.logger.debug("command: " + command)
-            (_, stdout, _) = self.ssh_conn.exec_command(command)
-            content = stdout.read()
-
-            # if len(content) == 0:
-            #     return True
-            # else:
-            #     return False
-
-            command = 'sudo brctl stp ' + port_name + ' on'
-            self.logger.debug("command: " + command)
-            (_, stdout, _) = self.ssh_conn.exec_command(command)
-            content = stdout.read()
-
-            # if len(content) == 0:
-            #     return True
-            # else:
-            #     return False
-            command = 'sudo ip link set dev ' + port_name + ' up'
-            self.logger.debug("command: " + command)
-            (_, stdout, _) = self.ssh_conn.exec_command(command)
-            content = stdout.read()
-
-            if len(content) == 0:
-                return True
-            else:
-                return False
-        except paramiko.ssh_exception.SSHException as e:
-            self.logger.error("create_linux_bridge ssh Exception: " + str(e))
-            if "SSH session not active" in str(e):
-                self.ssh_connect()
+            port_name = 'ovim-{}'.format(str(vlan))
+            command = 'sudo brctl show | grep {}'.format(port_name)
+            result = self.run_command(command, ignore_exit_status=True)
+            if not result:
+                command = 'sudo brctl addbr {}'.format(port_name)
+                self.run_command(command)
+
+                command = 'sudo brctl stp {} on'.format(port_name)
+                self.run_command(command)
+
+            command = 'sudo ip link set dev {} up'.format(port_name)
+            self.run_command(command)
+            return True
+        except RunCommandException as e:
+            self.logger.error("create_linux_bridge ssh Exception: {}".format(str(e)))
             return False
 
-    def set_mac_dhcp_server(self, ip, mac, vlan, netmask, dhcp_path):
+    def set_mac_dhcp_server(self, ip, mac, vlan, netmask, first_ip, dhcp_path):
         """
         Write into dhcp conf file a rule to assigned a fixed ip given to an specific MAC address
         :param ip: IP address asigned to a VM
@@ -1017,34 +1101,42 @@ class host_thread(threading.Thread):
         if self.test:
             return True
 
-        net_namespace = 'ovim-' + str(vlan)
-        dhcp_path = os.path.join(dhcp_path, net_namespace)
-        dhcp_hostsdir = os.path.join(dhcp_path, net_namespace)
+        dhcp_namespace = '{}-dnsmasq'.format(str(vlan))
+        dhcp_path = os.path.join(dhcp_path, dhcp_namespace)
+        dhcp_hostsdir = os.path.join(dhcp_path, dhcp_namespace)
+        ns_interface = '{}-vethDO'.format(str(vlan))
 
         if not ip:
             return False
         try:
-            ip_data = mac.upper() + ',' + ip
-
-            command = 'sudo  ip netns exec ' + net_namespace + ' touch ' + dhcp_hostsdir
-            self.logger.debug("command: " + command)
-            (_, stdout, _) = self.ssh_conn.exec_command(command)
-            content = stdout.read()
-
-            command = 'sudo  ip netns exec ' + net_namespace + ' sudo bash -ec "echo ' + ip_data + ' >> ' + dhcp_hostsdir + '"'
+            command = 'sudo ip netns exec {} cat /sys/class/net/{}/address'.format(dhcp_namespace, ns_interface)
+            iface_listen_mac = self.run_command(command, ignore_exit_status=True)
+
+            if iface_listen_mac > 0:
+                command = 'sudo ip netns exec {} cat {} | grep -i {}'.format(dhcp_namespace,
+                                                                          dhcp_hostsdir,
+                                                                          iface_listen_mac)
+                content = self.run_command(command, ignore_exit_status=True)
+                if content == '':
+                    ip_data = iface_listen_mac.upper().replace('\n', '') + ',' + first_ip
+                    dhcp_hostsdir = os.path.join(dhcp_path, dhcp_namespace)
+
+                    command = 'sudo  ip netns exec {} sudo bash -ec "echo {} >> {}"'.format(dhcp_namespace,
+                                                                                            ip_data,
+                                                                                            dhcp_hostsdir)
+                    self.run_command(command)
+
+                ip_data = mac.upper() + ',' + ip
+                command = 'sudo  ip netns exec {} sudo bash -ec "echo {} >> {}"'.format(dhcp_namespace,
+                                                                                        ip_data,
+                                                                                        dhcp_hostsdir)
+                self.run_command(command, ignore_exit_status=False)
 
-            self.logger.debug("command: " + command)
-            (_, stdout, _) = self.ssh_conn.exec_command(command)
-            content = stdout.read()
-
-            if len(content) == 0:
                 return True
-            else:
-                return False
-        except paramiko.ssh_exception.SSHException as e:
+
+            return False
+        except RunCommandException as e:
             self.logger.error("set_mac_dhcp_server ssh Exception: " + str(e))
-            if "SSH session not active" in str(e):
-                self.ssh_connect()
             return False
 
     def delete_mac_dhcp_server(self, ip, mac, vlan, dhcp_path):
@@ -1061,32 +1153,24 @@ class host_thread(threading.Thread):
         if self.test:
             return False
         try:
-            net_namespace = 'ovim-' + str(vlan)
-            dhcp_path = os.path.join(dhcp_path, net_namespace)
-            dhcp_hostsdir = os.path.join(dhcp_path, net_namespace)
+            dhcp_namespace = str(vlan) + '-dnsmasq'
+            dhcp_path = os.path.join(dhcp_path, dhcp_namespace)
+            dhcp_hostsdir = os.path.join(dhcp_path, dhcp_namespace)
 
             if not ip:
                 return False
 
             ip_data = mac.upper() + ',' + ip
 
-            command = 'sudo  ip netns exec ' + net_namespace + ' sudo sed -i \'/' + ip_data + '/d\' ' + dhcp_hostsdir
-            self.logger.debug("command: " + command)
-            (_, stdout, _) = self.ssh_conn.exec_command(command)
-            content = stdout.read()
-
-            if len(content) == 0:
-                return True
-            else:
-                return False
+            command = 'sudo  ip netns exec ' + dhcp_namespace + ' sudo sed -i \'/' + ip_data + '/d\' ' + dhcp_hostsdir
+            self.run_command(command)
 
-        except paramiko.ssh_exception.SSHException as e:
-            self.logger.error("set_mac_dhcp_server ssh Exception: " + str(e))
-            if "SSH session not active" in str(e):
-                self.ssh_connect()
+            return True
+        except RunCommandException as e:
+            self.logger.error("delete_mac_dhcp_server Exception: " + str(e))
             return False
 
-    def launch_dhcp_server(self, vlan, ip_range, netmask, dhcp_path, gateway):
+    def launch_dhcp_server(self, vlan, ip_range, netmask, dhcp_path, gateway, dns_list=None, routes=None):
         """
         Generate a linux bridge and attache the port to a OVS bridge
         :param self:
@@ -1095,86 +1179,107 @@ class host_thread(threading.Thread):
         :param netmask: network netmask
         :param dhcp_path: dhcp conf file path that live in namespace side
         :param gateway: Gateway address for dhcp net
+        :param dns_list: dns list for dhcp server
+        :param routes: routes list for dhcp server
         :return: True if success
         """
 
         if self.test:
             return True
         try:
-            interface = 'tap-' + str(vlan)
-            net_namespace = 'ovim-' + str(vlan)
-            dhcp_path = os.path.join(dhcp_path, net_namespace)
+            ns_interface = str(vlan) + '-vethDO'
+            dhcp_namespace = str(vlan) + '-dnsmasq'
+            dhcp_path = os.path.join(dhcp_path, dhcp_namespace, '')
             leases_path = os.path.join(dhcp_path, "dnsmasq.leases")
             pid_file = os.path.join(dhcp_path, 'dnsmasq.pid')
 
             dhcp_range = ip_range[0] + ',' + ip_range[1] + ',' + netmask
 
-            command = 'sudo ip netns exec ' + net_namespace + ' mkdir -p ' + dhcp_path
-            self.logger.debug("command: " + command)
-            (_, stdout, _) = self.ssh_conn.exec_command(command)
-            content = stdout.read()
+            command = 'sudo ip netns exec {} mkdir -p {}'.format(dhcp_namespace, dhcp_path)
+            self.run_command(command)
 
+            # check if dnsmasq process is running
+            dnsmasq_is_runing = False
             pid_path = os.path.join(dhcp_path, 'dnsmasq.pid')
-            command = 'sudo  ip netns exec ' + net_namespace + ' cat ' + pid_path
-            self.logger.debug("command: " + command)
-            (_, stdout, _) = self.ssh_conn.exec_command(command)
-            content = stdout.read()
+            command = 'sudo  ip netns exec ' + dhcp_namespace + ' ls ' + pid_path
+            content = self.run_command(command, ignore_exit_status=True)
+
             # check if pid is runing
-            pid_status_path = content
             if content:
-                command = "ps aux | awk '{print $2 }' | grep " + pid_status_path
-                self.logger.debug("command: " + command)
-                (_, stdout, _) = self.ssh_conn.exec_command(command)
-                content = stdout.read()
-            if not content:
-                command = 'sudo  ip netns exec ' + net_namespace + ' /usr/sbin/dnsmasq --strict-order --except-interface=lo ' \
-                  '--interface=' + interface + ' --bind-interfaces --dhcp-hostsdir=' + dhcp_path + \
-                  ' --dhcp-range ' + dhcp_range + ' --pid-file=' + pid_file + ' --dhcp-leasefile=' + leases_path + \
-                  '  --listen-address ' + gateway
-
-            self.logger.debug("command: " + command)
-            (_, stdout, _) = self.ssh_conn.exec_command(command)
-            content = stdout.readline()
-
-            if len(content) == 0:
+                pid_path = content.replace('\n', '')
+                command = "ps aux | awk '{print $2 }' | grep {}" + pid_path
+                dnsmasq_is_runing = self.run_command(command, ignore_exit_status=True)
+
+            gateway_option = ' --dhcp-option=3,' + gateway
+
+            dhcp_route_option = ''
+            if routes:
+                dhcp_route_option = ' --dhcp-option=121'
+                for key, value in routes.iteritems():
+                        if 'default' == key:
+                            gateway_option = ' --dhcp-option=3,' + value
+                        else:
+                            dhcp_route_option += ',' + key + ',' + value
+            dns_data = ''
+            if dns_list:
+                dns_data = ' --dhcp-option=6'
+                for dns in dns_list:
+                    dns_data += ',' + dns
+
+            if not dnsmasq_is_runing:
+                command = 'sudo  ip netns exec ' + dhcp_namespace + ' /usr/sbin/dnsmasq --strict-order --except-interface=lo ' \
+                          '--interface=' + ns_interface + \
+                          ' --bind-interfaces --dhcp-hostsdir=' + dhcp_path + \
+                          ' --dhcp-range ' + dhcp_range + \
+                          ' --pid-file=' + pid_file + \
+                          ' --dhcp-leasefile=' + leases_path + \
+                          ' --listen-address ' + ip_range[0] + \
+                          gateway_option + \
+                          dhcp_route_option + \
+                          dns_data
+
+                self.run_command(command)
                 return True
-            else:
-                return False
-        except paramiko.ssh_exception.SSHException as e:
+        except RunCommandException as e:
             self.logger.error("launch_dhcp_server ssh Exception: " + str(e))
-            if "SSH session not active" in str(e):
-                self.ssh_connect()
             return False
 
-    def delete_dhcp_interfaces(self, vlan):
+    def delete_dhcp_interfaces(self, vlan, dhcp_path):
         """
-        Create a linux bridge with STP active
+        Delete a linux dnsmasq bridge and namespace
         :param vlan: netowrk vlan id
+        :param dhcp_path: 
         :return:
         """
-
         if self.test:
             return True
         try:
-            net_namespace = 'ovim-' + str(vlan)
-            command = 'sudo ovs-vsctl del-port br-int ovs-tap-' + str(vlan)
-            self.logger.debug("command: " + command)
-            (_, stdout, _) = self.ssh_conn.exec_command(command)
-            content = stdout.read()
-
-            command = 'sudo ip netns exec ' + net_namespace + ' ip link set dev tap-' + str(vlan) + ' down'
-            self.logger.debug("command: " + command)
-            (_, stdout, _) = self.ssh_conn.exec_command(command)
-            content = stdout.read()
-
-            command = 'sudo ip link set dev ovs-tap-' + str(vlan) + ' down'
-            self.logger.debug("command: " + command)
-            (_, stdout, _) = self.ssh_conn.exec_command(command)
-            content = stdout.read()
-        except paramiko.ssh_exception.SSHException as e:
-            self.logger.error("delete_dhcp_interfaces ssh Exception: " + str(e))
-            if "SSH session not active" in str(e):
-                self.ssh_connect()
+            br_veth_name ='{}-vethDO'.format(str(vlan))
+            ovs_veth_name = '{}-vethOD'.format(str(vlan))
+            dhcp_namespace = '{}-dnsmasq'.format(str(vlan))
+
+            dhcp_path = os.path.join(dhcp_path, dhcp_namespace)
+            command = 'sudo ovs-vsctl del-port br-int {}'.format(ovs_veth_name)
+            self.run_command(command, ignore_exit_status=True)  # to end session
+
+            command = 'sudo ip link set dev {} down'.format(ovs_veth_name)
+            self.run_command(command, ignore_exit_status=True)  # to end session
+
+            command = 'sudo ip link delete {} '.format(ovs_veth_name)
+            self.run_command(command, ignore_exit_status=True)
+
+            command = 'sudo ip netns exec {} ip link set dev {} down'.format(dhcp_namespace, br_veth_name)
+            self.run_command(command, ignore_exit_status=True)
+
+            command = 'sudo rm -rf {}'.format(dhcp_path)
+            self.run_command(command)
+
+            command = 'sudo ip netns del {}'.format(dhcp_namespace)
+            self.run_command(command)
+
+            return True
+        except RunCommandException as e:
+            self.logger.error("delete_dhcp_interfaces ssh Exception: {}".format(str(e)))
             return False
 
     def create_dhcp_interfaces(self, vlan, ip_listen_address, netmask):
@@ -1185,64 +1290,292 @@ class host_thread(threading.Thread):
         :param netmask: dhcp net CIDR
         :return: True if success
         """
+        if self.test:
+            return True
+        try:
+            ovs_veth_name = '{}-vethOD'.format(str(vlan))
+            ns_veth = '{}-vethDO'.format(str(vlan))
+            dhcp_namespace = '{}-dnsmasq'.format(str(vlan))
+
+            command = 'sudo ip netns add {}'.format(dhcp_namespace)
+            self.run_command(command)
+
+            command = 'sudo ip link add {} type veth peer name {}'.format(ns_veth, ovs_veth_name)
+            self.run_command(command)
+
+            command = 'sudo ip link set {} netns {}'.format(ns_veth, dhcp_namespace)
+            self.run_command(command)
+
+            command = 'sudo ip netns exec {} ip link set dev {} up'.format(dhcp_namespace, ns_veth)
+            self.run_command(command)
+
+            command = 'sudo ovs-vsctl add-port br-int {} tag={}'.format(ovs_veth_name, str(vlan))
+            self.run_command(command, ignore_exit_status=True)
+
+            command = 'sudo ip link set dev {} up'.format(ovs_veth_name)
+            self.run_command(command)
+
+            command = 'sudo ip netns exec {} ip link set dev lo up'.format(dhcp_namespace)
+            self.run_command(command)
+
+            command = 'sudo  ip netns exec {} ifconfig {} {} netmask {}'.format(dhcp_namespace,
+                                                                                ns_veth,
+                                                                                ip_listen_address,
+                                                                                netmask)
+            self.run_command(command)
+            return True
+        except RunCommandException as e:
+            self.logger.error("create_dhcp_interfaces ssh Exception: {}".format(str(e)))
+            return False
+
+    def delete_qrouter_connection(self, vlan, link):
+        """
+        Delete qrouter Namesapce with all veth interfaces need it
+        :param vlan: 
+        :param link: 
+        :return: 
+        """
+
+        if self.test:
+            return True
+        try:
+            ns_qouter = '{}-qrouter'.format(str(vlan))
+            qrouter_ovs_veth = '{}-vethOQ'.format(str(vlan))
+            qrouter_ns_veth = '{}-vethQO'.format(str(vlan))
+            qrouter_br_veth = '{}-vethBQ'.format(str(vlan))
+            qrouter_ns_router_veth = '{}-vethQB'.format(str(vlan))
+
+            command = 'sudo ovs-vsctl del-port br-int {}'.format(qrouter_ovs_veth)
+            self.run_command(command, ignore_exit_status=True)
+
+            # down ns veth
+            command = 'sudo ip netns exec {} ip link set dev {} down'.format(ns_qouter, qrouter_ns_veth)
+            self.run_command(command, ignore_exit_status=True)
+
+            command = 'sudo ip netns exec {}  ip link delete {} '.format(ns_qouter, qrouter_ns_veth)
+            self.run_command(command, ignore_exit_status=True)
+
+            command = 'sudo ip netns del ' + ns_qouter
+            self.run_command(command)
+
+            # down ovs veth interface
+            command = 'sudo ip link set dev {} down'.format(qrouter_br_veth)
+            self.run_command(command, ignore_exit_status=True)
+
+            # down br veth interface
+            command = 'sudo ip link set dev {} down'.format(qrouter_ovs_veth)
+            self.run_command(command, ignore_exit_status=True)
+
+            # delete  veth interface
+            command = 'sudo ip link delete {} '.format(link, qrouter_ovs_veth)
+            self.run_command(command, ignore_exit_status=True)
+
+            # down br veth interface
+            command = 'sudo ip link set dev {} down'.format(qrouter_ns_router_veth)
+            self.run_command(command, ignore_exit_status=True)
+
+            # delete  veth interface
+            command = 'sudo ip link delete {} '.format(link, qrouter_ns_router_veth)
+            self.run_command(command, ignore_exit_status=True)
+
+            # down br veth interface
+            command = 'sudo brctl delif {} {}'.format(link, qrouter_br_veth)
+            self.run_command(command)
+
+            # delete NS
+            return True
+        except RunCommandException as e:
+            self.logger.error("delete_qrouter_connection ssh Exception: {}".format(str(e)))
+            return False
+
+    def create_qrouter_ovs_connection(self, vlan, gateway, dhcp_cidr):
+        """
+        Create qrouter Namesapce with all veth interfaces need it between NS and OVS
+        :param vlan: 
+        :param gateway: 
+        :return: 
+        """
+
+        if self.test:
+            return True
+
+        try:
+            ns_qouter = '{}-qrouter'.format(str(vlan))
+            qrouter_ovs_veth ='{}-vethOQ'.format(str(vlan))
+            qrouter_ns_veth = '{}-vethQO'.format(str(vlan))
+
+            # Create NS
+            command = 'sudo ip netns add {}'.format(ns_qouter)
+            self.run_command(command)
+
+            # Create pait veth
+            command = 'sudo ip link add {} type veth peer name {}'.format(qrouter_ns_veth, qrouter_ovs_veth)
+            self.run_command(command,  ignore_exit_status=True)
+
+            # up ovs veth interface
+            command = 'sudo ip link set dev {} up'.format(qrouter_ovs_veth)
+            self.run_command(command)
+
+            # add ovs veth to ovs br-int
+            command = 'sudo ovs-vsctl add-port br-int {} tag={}'.format(qrouter_ovs_veth, vlan)
+            self.run_command(command)
+
+            # add veth to ns
+            command = 'sudo ip link set {} netns {}'.format(qrouter_ns_veth, ns_qouter)
+            self.run_command(command)
+
+            # up ns loopback
+            command = 'sudo ip netns exec {} ip link set dev lo up'.format(ns_qouter)
+            self.run_command(command)
+
+            # up ns veth
+            command = 'sudo ip netns exec {} ip link set dev {} up'.format(ns_qouter, qrouter_ns_veth)
+            self.run_command(command)
+
+            from netaddr import IPNetwork
+            ip_tools = IPNetwork(dhcp_cidr)
+            cidr_len = ip_tools.prefixlen
+
+            # set gw to ns veth
+            command = 'sudo ip netns exec {} ip address add {}/{} dev {}'.format(ns_qouter, gateway, cidr_len, qrouter_ns_veth)
+            self.run_command(command)
+
+            return True
+
+        except RunCommandException as e:
+            self.logger.error("Create_dhcp_interfaces ssh Exception: {}".format(str(e)))
+            return False
+
+    def add_ns_routes(self, vlan, routes):
+        """
+        
+        :param vlan: 
+        :param routes: 
+        :return: 
+        """
 
         if self.test:
             return True
+
         try:
-            net_namespace = 'ovim-' + str(vlan)
-            namespace_interface = 'tap-' + str(vlan)
-
-            command = 'sudo ip netns add ' + net_namespace
-            self.logger.debug("command: " + command)
-            (_, stdout, _) = self.ssh_conn.exec_command(command)
-            content = stdout.read()
-
-            command = 'sudo ip link add tap-' + str(vlan) + ' type veth peer name ovs-tap-' + str(vlan)
-            self.logger.debug("command: " + command)
-            (_, stdout, _) = self.ssh_conn.exec_command(command)
-            content = stdout.read()
-
-            command = 'sudo ovs-vsctl add-port br-int ovs-tap-' + str(vlan) + ' tag=' + str(vlan)
-            self.logger.debug("command: " + command)
-            (_, stdout, _) = self.ssh_conn.exec_command(command)
-            content = stdout.read()
-
-            command = 'sudo ip link set tap-' + str(vlan) + ' netns ' + net_namespace
-            self.logger.debug("command: " + command)
-            (_, stdout, _) = self.ssh_conn.exec_command(command)
-            content = stdout.read()
-
-            command = 'sudo ip netns exec ' + net_namespace + ' ip link set dev tap-' + str(vlan) + ' up'
-            self.logger.debug("command: " + command)
-            (_, stdout, _) = self.ssh_conn.exec_command(command)
-            content = stdout.read()
-
-            command = 'sudo ip link set dev ovs-tap-' + str(vlan) + ' up'
-            self.logger.debug("command: " + command)
-            (_, stdout, _) = self.ssh_conn.exec_command(command)
-            content = stdout.read()
-
-            command = 'sudo ip netns exec ' + net_namespace + ' ip link set dev lo up'
-            self.logger.debug("command: " + command)
-            (_, stdout, _) = self.ssh_conn.exec_command(command)
-            content = stdout.read()
-
-            command = 'sudo  ip netns exec ' + net_namespace + ' ' + ' ifconfig  ' + namespace_interface \
-                      + ' ' + ip_listen_address + ' netmask ' + netmask
-            self.logger.debug("command: " + command)
-            (_, stdout, _) = self.ssh_conn.exec_command(command)
-            content = stdout.read()
-
-            if len(content) == 0:
+            ns_qouter = '{}-qrouter'.format(str(vlan))
+            qrouter_ns_router_veth = '{}-vethQB'.format(str(vlan))
+
+            for key, value in routes.iteritems():
+                # up ns veth
+                if key == 'default':
+                    command = 'sudo ip netns exec {} ip route add {} via {} '.format(ns_qouter,  key, value)
+                else:
+                    command = 'sudo ip netns exec {} ip route add {} via {} dev {}'.format(ns_qouter, key, value,
+                                                                                           qrouter_ns_router_veth)
+
+                self.run_command(command)
+
+                return True
+
+        except RunCommandException as e:
+            self.logger.error("add_ns_routes, error adding routes to namesapce, {}".format(str(e)))
+            return False
+
+    def create_qrouter_br_connection(self, vlan, cidr, link):
+        """
+        Create veth interfaces between user bridge (link) and OVS
+        :param vlan: 
+        :param link: 
+        :return: 
+        """
+
+        if self.test:
+            return True
+
+        try:
+            ns_qouter = '{}-qrouter'.format(str(vlan))
+            qrouter_ns_router_veth = '{}-vethQB'.format(str(vlan))
+            qrouter_br_veth = '{}-vethBQ'.format(str(vlan))
+
+            command = 'sudo brctl show | grep {}'.format(link['iface'])
+            content = self.run_command(command, ignore_exit_status=True)
+
+            if content > '':
+                # Create pait veth
+                command = 'sudo ip link add {} type veth peer name {}'.format(qrouter_br_veth, qrouter_ns_router_veth)
+                self.run_command(command)
+
+                # up ovs veth interface
+                command = 'sudo ip link set dev {} up'.format(qrouter_br_veth)
+                self.run_command(command)
+
+                # add veth to ns
+                command = 'sudo ip link set {} netns {}'.format(qrouter_ns_router_veth, ns_qouter)
+                self.run_command(command)
+
+                # up ns veth
+                command = 'sudo ip netns exec {} ip link set dev {} up'.format(ns_qouter, qrouter_ns_router_veth)
+                self.run_command(command)
+
+                command = 'sudo ip netns exec {} ip address add {} dev {}'.format(ns_qouter,
+                                                                                  link['nat'],
+                                                                                  qrouter_ns_router_veth)
+                self.run_command(command)
+
+                # up ns veth
+                command = 'sudo brctl addif {} {}'.format(link['iface'], qrouter_br_veth)
+                self.run_command(command)
+
+                # up ns veth
+                command = 'sudo ip netns exec {} iptables -t nat -A POSTROUTING -o {} -s {} -d {} -j MASQUERADE' \
+                    .format(ns_qouter, qrouter_ns_router_veth, link['nat'], cidr)
+                self.run_command(command)
+
                 return True
             else:
+
+                self.logger.error('create_qrouter_br_connection, Bridge {} given by user not exist'.format(qrouter_br_veth))
                 return False
-        except paramiko.ssh_exception.SSHException as e:
-            self.logger.error("create_dhcp_interfaces ssh Exception: " + str(e))
-            if "SSH session not active" in str(e):
-                self.ssh_connect()
+
+        except RunCommandException as e:
+            self.logger.error("Error creating qrouter, {}".format(str(e)))
             return False
 
+    def create_link_bridge_to_ovs(self, vlan, link):
+        """
+        Create interfaces to connect a linux bridge with tenant net
+        :param vlan: segmentation id
+        :return: True if success
+        """
+        if self.test:
+            return True
+        try:
+
+            br_tap_name = '{}-vethBO'.format(str(vlan))
+            br_ovs_name = '{}-vethOB'.format(str(vlan))
+
+            # is a bridge or a interface
+            command = 'sudo brctl show | grep {}'.format(link)
+            content = self.run_command(command, ignore_exit_status=True)
+            if content > '':
+                command = 'sudo ip link add {} type veth peer name {}'.format(br_tap_name, br_ovs_name)
+                self.run_command(command)
+
+                command = 'sudo ip link set dev {}  up'.format(br_tap_name)
+                self.run_command(command)
+
+                command = 'sudo ip link set dev {}  up'.format(br_ovs_name)
+                self.run_command(command)
+
+                command = 'sudo ovs-vsctl add-port br-int {} tag={}'.format(br_ovs_name, str(vlan))
+                self.run_command(command)
+
+                command = 'sudo brctl addif ' + link + ' {}'.format(br_tap_name)
+                self.run_command(command)
+                return True
+            else:
+                self.logger.error('Link is not present, please check {}'.format(link))
+                return False
+
+        except RunCommandException as e:
+            self.logger.error("create_link_bridge_to_ovs, Error creating link to ovs, {}".format(str(e)))
+            return False
 
     def create_ovs_vxlan_tunnel(self, vxlan_interface, remote_ip):
         """
@@ -1251,24 +1584,23 @@ class host_thread(threading.Thread):
         :param remote_ip: tunnel endpoint remote compute ip.
         :return:
         """
-        if self.test:
+        if self.test or not self.connectivity:
             return True
+        if remote_ip == 'localhost':
+            if self.localhost:
+                return True # TODO: Cannot create a vxlan between localhost and localhost
+            remote_ip = self.local_ip
         try:
-            command = 'sudo ovs-vsctl add-port br-int ' + vxlan_interface + \
-                      ' -- set Interface ' + vxlan_interface + '  type=vxlan options:remote_ip=' + remote_ip + \
-                      ' -- set Port ' + vxlan_interface + ' other_config:stp-path-cost=10'
-            self.logger.debug("command: " + command)
-            (_, stdout, _) = self.ssh_conn.exec_command(command)
-            content = stdout.read()
-            # print content
-            if len(content) == 0:
-                return True
-            else:
-                return False
-        except paramiko.ssh_exception.SSHException as e:
-            self.logger.error("create_ovs_vxlan_tunnel ssh Exception: " + str(e))
-            if "SSH session not active" in str(e):
-                self.ssh_connect()
+
+            command = 'sudo ovs-vsctl add-port br-int {} -- set Interface {} type=vxlan options:remote_ip={} ' \
+                      '-- set Port {} other_config:stp-path-cost=10'.format(vxlan_interface,
+                                                                            vxlan_interface,
+                                                                            remote_ip,
+                                                                            vxlan_interface)
+            self.run_command(command)
+            return True
+        except RunCommandException as e:
+            self.logger.error("create_ovs_vxlan_tunnel, error creating vxlan tunnel, {}".format(str(e)))
             return False
 
     def delete_ovs_vxlan_tunnel(self, vxlan_interface):
@@ -1277,22 +1609,14 @@ class host_thread(threading.Thread):
         :param vxlan_interface: vlxan name to be delete it.
         :return: True if success.
         """
-        if self.test:
+        if self.test or not self.connectivity:
             return True
         try:
-            command = 'sudo ovs-vsctl del-port br-int ' + vxlan_interface
-            self.logger.debug("command: " + command)
-            (_, stdout, _) = self.ssh_conn.exec_command(command)
-            content = stdout.read()
-            # print content
-            if len(content) == 0:
-                return True
-            else:
-                return False
-        except paramiko.ssh_exception.SSHException as e:
-            self.logger.error("delete_ovs_vxlan_tunnel ssh Exception: " + str(e))
-            if "SSH session not active" in str(e):
-                self.ssh_connect()
+            command = 'sudo ovs-vsctl del-port br-int {}'.format(vxlan_interface)
+            self.run_command(command)
+            return True
+        except RunCommandException as e:
+            self.logger.error("delete_ovs_vxlan_tunnel, error deleting vxlan tunenl, {}".format(str(e)))
             return False
 
     def delete_ovs_bridge(self):
@@ -1300,62 +1624,60 @@ class host_thread(threading.Thread):
         Delete a OVS bridge from  a compute.
         :return: True if success
         """
-        if self.test:
+        if self.test or not self.connectivity:
             return True
         try:
             command = 'sudo ovs-vsctl del-br br-int'
-            self.logger.debug("command: " + command)
-            (_, stdout, _) = self.ssh_conn.exec_command(command)
-            content = stdout.read()
-            if len(content) == 0:
-                return True
-            else:
-                return False
-        except paramiko.ssh_exception.SSHException as e:
-            self.logger.error("delete_ovs_bridge ssh Exception: " + str(e))
-            if "SSH session not active" in str(e):
-                self.ssh_connect()
+            self.run_command(command)
+            return True
+        except RunCommandException as e:
+            self.logger.error("delete_ovs_bridge ssh Exception: {}".format(str(e)))
             return False
 
     def get_file_info(self, path):
         command = 'ls -lL --time-style=+%Y-%m-%dT%H:%M:%S ' + path
-        self.logger.debug("command: " + command)
-        (_, stdout, _) = self.ssh_conn.exec_command(command)
-        content = stdout.read()
-        if len(content) == 0:
-            return None  # file does not exist
-        else:
+        try:
+            content = self.run_command(command)
             return content.split(" ")  # (permission, 1, owner, group, size, date, file)
+        except RunCommandException as e:
+            return None  # file does not exist
 
     def qemu_get_info(self, path):
         command = 'qemu-img info ' + path
-        self.logger.debug("command: " + command)
-        (_, stdout, stderr) = self.ssh_conn.exec_command(command)
-        content = stdout.read()
-        if len(content) == 0:
-            error = stderr.read()
-            self.logger.error("get_qemu_info error " + error)
-            raise paramiko.ssh_exception.SSHException("Error getting qemu_info: " + error)
-        else:
-            try: 
-                return yaml.load(content)
-            except yaml.YAMLError as exc:
-                text = ""
-                if hasattr(exc, 'problem_mark'):
-                    mark = exc.problem_mark
-                    text = " at position: (%s:%s)" % (mark.line+1, mark.column+1)
-                self.logger.error("get_qemu_info yaml format Exception " + text)
-                raise paramiko.ssh_exception.SSHException("Error getting qemu_info yaml format" + text)
+        content = self.run_command(command)
+        try:
+            return yaml.load(content)
+        except yaml.YAMLError as exc:
+            text = ""
+            if hasattr(exc, 'problem_mark'):
+                mark = exc.problem_mark
+                text = " at position: (%s:%s)" % (mark.line+1, mark.column+1)
+            self.logger.error("get_qemu_info yaml format Exception " + text)
+            raise RunCommandException("Error getting qemu_info yaml format" + text)
 
     def qemu_change_backing(self, inc_file, new_backing_file):
-        command = 'qemu-img rebase -u -b ' + new_backing_file + ' ' + inc_file 
-        self.logger.debug("command: " + command)
-        (_, _, stderr) = self.ssh_conn.exec_command(command)
-        content = stderr.read()
-        if len(content) == 0:
+        command = 'qemu-img rebase -u -b {} {}'.format(new_backing_file, inc_file)
+        try:
+            self.run_command(command)
             return 0
-        else:
-            self.logger.error("qemu_change_backing error: " + content)
+        except RunCommandException as e:
+            self.logger.error("qemu_change_backing error: " + str(e))
+            return -1
+
+    def qemu_create_empty_disk(self, dev):
+
+        if not dev and 'source' not in dev and 'file format' not in dev and 'image_size' not in dev:
+            self.logger.error("qemu_create_empty_disk error: missing image parameter")
+            return -1
+
+        empty_disk_path = dev['source file']
+
+        command = 'qemu-img create -f qcow2 {} {}G'.format(empty_disk_path, dev['image_size'])
+        try:
+            self.run_command(command)
+            return 0
+        except RunCommandException as e:
+            self.logger.error("qemu_create_empty_disk error: " + str(e))
             return -1
     
     def get_notused_filename(self, proposed_name, suffix=''):
@@ -1399,12 +1721,8 @@ class host_thread(threading.Thread):
 
     
     def delete_file(self, file_name):
-        command = 'rm -f '+file_name
-        self.logger.debug("command: " + command)
-        (_, _, stderr) = self.ssh_conn.exec_command(command)
-        error_msg = stderr.read()
-        if len(error_msg) > 0:
-            raise paramiko.ssh_exception.SSHException("Error deleting file: " + error_msg)
+        command = 'rm -f ' + file_name
+        self.run_command(command)
 
     def copy_file(self, source, destination, perserve_time=True):
         if source[0:4]=="http":
@@ -1414,12 +1732,8 @@ class host_thread(threading.Thread):
             command = 'cp --no-preserve=mode'
             if perserve_time:
                 command += ' --preserve=timestamps'
-            command +=  " '{}' '{}'".format(source, destination)
-        self.logger.debug("command: " + command)
-        (_, _, stderr) = self.ssh_conn.exec_command(command)
-        error_msg = stderr.read()
-        if len(error_msg) > 0:
-            raise paramiko.ssh_exception.SSHException("Error copying image to local host: " + error_msg)
+            command += " '{}' '{}'".format(source, destination)
+        self.run_command(command)
 
     def copy_remote_file(self, remote_file, use_incremental):
         ''' Copy a file from the repository to local folder and recursively 
@@ -1502,19 +1816,21 @@ class host_thread(threading.Thread):
                 #self.server_status[server_id] = 'ACTIVE'
                 return 0, 'Success'
 
-            self.db_lock.acquire()
             result, server_data = self.db.get_instance(server_id)
-            self.db_lock.release()
             if result <= 0:
                 self.logger.error("launch_server ERROR getting server from DB %d %s", result, server_data)
                 return result, server_data
     
+            self.hypervisor = str(server_data['hypervisor'])
+
         #0: get image metadata
             server_metadata = server.get('metadata', {})
             use_incremental = None
              
             if "use_incremental" in server_metadata:
                 use_incremental = False if server_metadata["use_incremental"] == "no" else True
+            if self.xen_hyp == True:
+                use_incremental = False
 
             server_host_files = self.localinfo['server_files'].get( server['uuid'], {})
             if rebuild:
@@ -1528,31 +1844,43 @@ class host_thread(threading.Thread):
             devices = [  {"type":"disk", "image_id":server['image_id'], "vpci":server_metadata.get('vpci', None) } ] 
             if 'extended' in server_data and server_data['extended']!=None and "devices" in server_data['extended']:
                 devices += server_data['extended']['devices']
-
+            empty_path = None
             for dev in devices:
-                if dev['image_id'] == None:
+                image_id = dev.get('image_id')
+                if not image_id:
+                    import uuid
+                    uuid_empty = str(uuid.uuid4())
+                    empty_path = self.empty_image_path + uuid_empty + '.qcow2' # local path for empty disk
+
+                    dev['source file'] = empty_path
+                    dev['file format'] = 'qcow2'
+                    self.qemu_create_empty_disk(dev)
+                    server_host_files[uuid_empty] = {'source file': empty_path,
+                                                     'file format': dev['file format']}
+
                     continue
-                
-                self.db_lock.acquire()
-                result, content = self.db.get_table(FROM='images', SELECT=('path', 'metadata'),
-                                                    WHERE={'uuid': dev['image_id']})
-                self.db_lock.release()
-                if result <= 0:
-                    error_text = "ERROR", result, content, "when getting image", dev['image_id']
-                    self.logger.error("launch_server " + error_text)
-                    return -1, error_text
-                if content[0]['metadata'] is not None:
-                    dev['metadata'] = json.loads(content[0]['metadata'])
                 else:
-                    dev['metadata'] = {}
-                
-                if dev['image_id'] in server_host_files:
-                    dev['source file'] = server_host_files[ dev['image_id'] ] ['source file'] #local path
-                    dev['file format'] = server_host_files[ dev['image_id'] ] ['file format'] # raw or qcow2
-                    continue
+                    result, content = self.db.get_table(FROM='images', SELECT=('path', 'metadata'),
+                                                        WHERE={'uuid': image_id})
+                    if result <= 0:
+                        error_text = "ERROR", result, content, "when getting image", dev['image_id']
+                        self.logger.error("launch_server " + error_text)
+                        return -1, error_text
+                    if content[0]['metadata'] is not None:
+                        dev['metadata'] = json.loads(content[0]['metadata'])
+                    else:
+                        dev['metadata'] = {}
+
+                    if image_id in server_host_files:
+                        dev['source file'] = server_host_files[image_id]['source file'] #local path
+                        dev['file format'] = server_host_files[image_id]['file format'] # raw or qcow2
+                        continue
                 
             #2: copy image to host
-                remote_file = content[0]['path']
+                if image_id:
+                    remote_file = content[0]['path']
+                else:
+                    remote_file = empty_path
                 use_incremental_image = use_incremental
                 if dev['metadata'].get("use_incremental") == "no":
                     use_incremental_image = False
@@ -1561,14 +1889,10 @@ class host_thread(threading.Thread):
                 #create incremental image
                 if use_incremental_image:
                     local_file_inc = self.get_notused_filename(local_file, '.inc')
-                    command = 'qemu-img create -f qcow2 '+local_file_inc+ ' -o backing_file='+ local_file
-                    self.logger.debug("command: " + command)
-                    (_, _, stderr) = self.ssh_conn.exec_command(command)
-                    error_msg = stderr.read()
-                    if len(error_msg) > 0:
-                        raise paramiko.ssh_exception.SSHException("Error creating incremental file: " + error_msg)
+                    command = 'qemu-img create -f qcow2 {} -o backing_file={}'.format(local_file_inc, local_file)
+                    self.run_command(command)
                     local_file = local_file_inc
-                    qemu_info = {'file format':'qcow2'}
+                    qemu_info = {'file format': 'qcow2'}
                 
                 server_host_files[ dev['image_id'] ] = {'source file': local_file, 'file format': qemu_info['file format']}
 
@@ -1661,9 +1985,7 @@ class host_thread(threading.Thread):
             STATUS={'progress':100, 'status':new_status}
             if new_status == 'ERROR':
                 STATUS['last_error'] = 'machine has crashed'
-            self.db_lock.acquire()
             r,_ = self.db.update_rows('instances', STATUS, {'uuid':server_id}, log=False)
-            self.db_lock.release()
             if r>=0:
                 self.server_status[server_id] = new_status
                         
@@ -1869,22 +2191,18 @@ class host_thread(threading.Thread):
             elif 'terminate' in req['action']:
                 #PUT a log in the database
                 self.logger.error("PANIC deleting server id='%s' %s", server_id, last_error)
-                self.db_lock.acquire()
-                self.db.new_row('logs', 
+                self.db.new_row('logs',
                             {'uuid':server_id, 'tenant_id':req['tenant_id'], 'related':'instances','level':'panic',
                              'description':'PANIC deleting server from host '+self.name+': '+last_error}
                         )
-                self.db_lock.release()
                 if server_id in self.server_status:
                     del self.server_status[server_id]
                 return -1
             else:
                 UPDATE['last_error'] = last_error
         if new_status != 'deleted' and (new_status != old_status or new_status == 'ERROR') :
-            self.db_lock.acquire()
             self.db.update_rows('instances', UPDATE, {'uuid':server_id}, log=True)
             self.server_status[server_id] = new_status
-            self.db_lock.release()
         if new_status == 'ERROR':
             return -1
         return 1
@@ -1971,21 +2289,17 @@ class host_thread(threading.Thread):
                     self.logger.error("create_image id='%s' Exception: %s", server_id, error_text)
 
                 #TODO insert a last_error at database
-        self.db_lock.acquire()
-        self.db.update_rows('images', {'status':image_status, 'progress': 100, 'path':file_dst}, 
+        self.db.update_rows('images', {'status':image_status, 'progress': 100, 'path':file_dst},
                 {'uuid':req['new_image']['uuid']}, log=True)
-        self.db_lock.release()
-  
+
     def edit_iface(self, port_id, old_net, new_net):
         #This action imply remove and insert interface to put proper parameters
         if self.test:
             time.sleep(1)
         else:
         #get iface details
-            self.db_lock.acquire()
             r,c = self.db.get_table(FROM='ports as p join resources_port as rp on p.uuid=rp.port_id',
                                     WHERE={'port_id': port_id})
-            self.db_lock.release()
             if r<0:
                 self.logger.error("edit_iface %s DDBB error: %s", port_id, c)
                 return
@@ -2030,7 +2344,7 @@ class host_thread(threading.Thread):
                 if conn is not None: conn.close()
 
 
-def create_server(server, db, db_lock, only_of_ports):
+def create_server(server, db, only_of_ports):
     extended = server.get('extended', None)
     requirements={}
     requirements['numa']={'memory':0, 'proc_req_type': 'threads', 'proc_req_nb':0, 'port_list':[], 'sriov_list':[]}
@@ -2115,11 +2429,10 @@ def create_server(server, db, db_lock, only_of_ports):
     elif requirements['vcpus']==0:
         return (-1, "Processor information not set neither at extended field not at vcpus")    
 
+    if 'hypervisor' in server: requirements['hypervisor'] = server['hypervisor']   #Unikernels extension
 
-    db_lock.acquire()
     result, content = db.get_numas(requirements, server.get('host_id', None), only_of_ports)
-    db_lock.release()
-    
+
     if result == -1:
         return (-1, content)
     
@@ -2130,11 +2443,9 @@ def create_server(server, db, db_lock, only_of_ports):
     cpu_pinning = []
     reserved_threads=[]
     if requirements['numa']['proc_req_nb']>0:
-        db_lock.acquire()
-        result, content = db.get_table(FROM='resources_core', 
+        result, content = db.get_table(FROM='resources_core',
                                        SELECT=('id','core_id','thread_id'),
                                        WHERE={'numa_id':numa_id,'instance_id': None, 'status':'ok'} )
-        db_lock.release()
         if result <= 0:
             #print content
             return -1, content
@@ -2218,9 +2529,7 @@ def create_server(server, db, db_lock, only_of_ports):
         #Get the source pci addresses for the selected numa
         used_sriov_ports = []
         for port in requirements['numa']['sriov_list']:
-            db_lock.acquire()
             result, content = db.get_table(FROM='resources_port', SELECT=('id', 'pci', 'mac'),WHERE={'numa_id':numa_id,'root_id': port['port_id'], 'port_id': None, 'Mbps_used': 0} )
-            db_lock.release()
             if result <= 0:
                 #print content
                 return -1, content
@@ -2242,9 +2551,7 @@ def create_server(server, db, db_lock, only_of_ports):
                 port['mac_address'] = port['mac']
                 del port['mac']
                 continue
-            db_lock.acquire()
             result, content = db.get_table(FROM='resources_port', SELECT=('id', 'pci', 'mac', 'Mbps'),WHERE={'numa_id':numa_id,'root_id': port['port_id'], 'port_id': None, 'Mbps_used': 0} )
-            db_lock.release()
             if result <= 0:
                 #print content
                 return -1, content
@@ -2283,13 +2590,11 @@ def create_server(server, db, db_lock, only_of_ports):
     for control_iface in server.get('networks', []):
         control_iface['net_id']=control_iface.pop('uuid')
         #Get the brifge name
-        db_lock.acquire()
         result, content = db.get_table(FROM='nets',
-                                       SELECT=('name', 'type', 'vlan', 'provider', 'enable_dhcp',
-                                                 'dhcp_first_ip', 'dhcp_last_ip', 'cidr'),
+                                       SELECT=('name', 'type', 'vlan', 'provider', 'enable_dhcp','dhcp_first_ip',
+                                               'dhcp_last_ip', 'cidr', 'gateway_ip', 'dns', 'links', 'routes'),
                                        WHERE={'uuid': control_iface['net_id']})
-        db_lock.release()
-        if result < 0: 
+        if result < 0:
             pass
         elif result==0:
             return -1, "Error at field netwoks: Not found any network wit uuid %s" % control_iface['net_id']
@@ -2311,6 +2616,13 @@ def create_server(server, db, db_lock, only_of_ports):
                     control_iface["dhcp_first_ip"] = network["dhcp_first_ip"]
                     control_iface["dhcp_last_ip"] = network["dhcp_last_ip"]
                     control_iface["cidr"] = network["cidr"]
+
+                if network.get("dns"):
+                    control_iface["dns"] = yaml.safe_load(network.get("dns"))
+                if network.get("links"):
+                    control_iface["links"] = yaml.safe_load(network.get("links"))
+                if network.get("routes"):
+                    control_iface["routes"] = yaml.safe_load(network.get("routes"))
             else:
                 if network['type']!='data' and network['type']!='ptp':
                     return -1, "Error at field netwoks: network uuid %s for dataplane interface is not of type data or ptp" % control_iface['net_id']
@@ -2345,6 +2657,8 @@ def create_server(server, db, db_lock, only_of_ports):
     
     if 'description' in server: resources['description'] = server['description']
     if 'name' in server: resources['name'] = server['name']
+    if 'hypervisor' in server: resources['hypervisor'] = server['hypervisor']
+    if 'os_image_type' in server: resources['os_image_type'] = server['os_image_type']
     
     resources['extended'] = {}                          #optional
     resources['extended']['numas'] = []