Пример #1
0
 def _boot_from_hd(self):
     # Temporary attach cloud-init no-cloud iso if we have to
     if (
             self.environment[ohostedcons.VMEnv.BOOT] == 'disk' and
             self.environment[ohostedcons.VMEnv.CDROM]
     ):
         self.environment[
             ohostedcons.VMEnv.SUBST
         ]['@CDROM@'] = self.environment[
             ohostedcons.VMEnv.CDROM
         ]
     created = False
     while not created:
         try:
             self._create_vm()
             created = True
         except socket.error as e:
             self.logger.debug(
                 'Error talking with VDSM (%s), reconnecting.' % str(e),
                 exc_info=True
             )
             cli = vdscli.connect(
                 timeout=ohostedcons.Const.VDSCLI_SSL_TIMEOUT
             )
             self.environment[ohostedcons.VDSMEnv.VDS_CLI] = cli
Пример #2
0
 def start(self):
     self.vdscli = vdscli.connect()
     self.netinfo = self._get_netinfo()
     if config.get('vars', 'net_persistence') == 'unified':
         self.config = RunningConfig()
     else:
         self.config = None
Пример #3
0
 def get_fc_lun_tuple_list(self):
     # workaround for vdsm check before use vdscli:
     if os.system("service vdsmd status|grep 'active (running)' &>/dev/null"):
         os.system("service sanlock stop")
         os.system("service libvirtd stop")
         os.system("service supervdsmd stop")
         os.system("vdsm-tool configure")
         os.system("service vdsmd restart")
         # workaround for imageio-daemon start success
         os.system("service ovirt-imageio-daemon restart")
     connecting = True
     fc_lun_list = []
     FC_DOMAIN = 2
     while connecting:
         try:
             cli = vdscli.connect(timeout=900)
             devices = cli.getDeviceList(FC_DOMAIN)
             connecting = False
         except socket_error as serr:
             if serr.errno == errno.ECONNREFUSED:
                 time.sleep(2)
             else:
                 raise serr
     if devices['status']['code']:
         raise RuntimeError(devices['status']['message'])
     for device in devices['devList']:
         device_info = "%s  %sGiB\n%s %s  status: %s" % (
                 device["GUID"], int(device['capacity']) / pow(2, 30),
                 device['vendorID'], device['productID'], device["status"],
             )
         fc_lun_list.append((device_info, None))
     return fc_lun_list
Пример #4
0
 def start(self):
     self.vdscli = vdscli.connect()
     self.netinfo = self._get_netinfo()
     if config.get("vars", "net_persistence") == "unified":
         self.config = RunningConfig()
     else:
         self.config = None
Пример #5
0
    def _setupVdsConnection(self):
        if self.hibernating:
            return

        hostPort = vdscli.cannonizeHostPort(
            self._dst,
            config.getint('addresses', 'management_port'))
        self.remoteHost, port = hostPort.rsplit(':', 1)

        try:
            client = self._createClient(port)
            requestQueues = config.get('addresses', 'request_queues')
            requestQueue = requestQueues.split(",")[0]
            self._destServer = jsonrpcvdscli.connect(requestQueue, client)
            self.log.debug('Initiating connection with destination')
            self._destServer.ping()

        except (JsonRpcBindingsError, JsonRpcNoResponseError):
            if config.getboolean('vars', 'ssl'):
                self._destServer = vdscli.connect(
                    hostPort,
                    useSSL=True,
                    TransportClass=kaxmlrpclib.TcpkeepSafeTransport)
            else:
                self._destServer = kaxmlrpclib.Server('http://' + hostPort)

        self.log.debug('Destination server is: ' + hostPort)
Пример #6
0
    def _setupVdsConnection(self):
        if self.hibernating:
            return

        # FIXME: The port will depend on the binding being used.
        # This assumes xmlrpc
        hostPort = vdscli.cannonizeHostPort(
            self._dst,
            config.getint('addresses', 'management_port'))
        self.remoteHost, _ = hostPort.rsplit(':', 1)

        if config.getboolean('vars', 'ssl'):
            self._destServer = vdscli.connect(
                hostPort,
                useSSL=True,
                TransportClass=kaxmlrpclib.TcpkeepSafeTransport)
        else:
            self._destServer = kaxmlrpclib.Server('http://' + hostPort)
        self.log.debug('Destination server is: ' + hostPort)
        try:
            self.log.debug('Initiating connection with destination')
            status = self._destServer.getVmStats(self._vm.id)
            if not status['status']['code']:
                self.log.error("Machine already exists on the destination")
                self.status = errCode['exist']
        except Exception:
            self.log.exception("Error initiating connection")
            self.status = errCode['noConPeer']
Пример #7
0
    def _setupVdsConnection(self):
        if self.hibernating:
            return

        hostPort = vdscli.cannonizeHostPort(
            self._dst, config.getint('addresses', 'management_port'))
        self.remoteHost, port = hostPort.rsplit(':', 1)

        try:
            client = self._createClient(port)
            requestQueues = config.get('addresses', 'request_queues')
            requestQueue = requestQueues.split(",")[0]
            self._destServer = jsonrpcvdscli.connect(requestQueue, client)
            self.log.debug('Initiating connection with destination')
            self._destServer.ping()

        except (JsonRpcBindingsError, JsonRpcNoResponseError):
            if config.getboolean('vars', 'ssl'):
                self._destServer = vdscli.connect(
                    hostPort,
                    useSSL=True,
                    TransportClass=kaxmlrpclib.TcpkeepSafeTransport)
            else:
                self._destServer = kaxmlrpclib.Server('http://' + hostPort)

        self.log.debug('Destination server is: ' + hostPort)
Пример #8
0
def get_domain_path(config_):
    """
    Return path of storage domain holding engine vm
    """
    vdsm = vdscli.connect()
    sd_uuid = config_.get(config.ENGINE, config.SD_UUID)
    dom_type = config_.get(config.ENGINE, config.DOMAIN_TYPE)
    parent = constants.SD_MOUNT_PARENT
    if dom_type == "glusterfs":
        parent = os.path.join(parent, "glusterSD")

    if dom_type.startswith("nfs"):
        response = vdsm.getStorageDomainInfo(sd_uuid)
        if response["status"]["code"] == 0:
            try:
                local_path = response["info"]["remotePath"].replace("/", "_")
                path = os.path.join(parent, local_path, sd_uuid)
                if os.access(path, os.F_OK):
                    return path
            # don't have remotePath? so fallback to old logic
            except KeyError:
                pass

    # fallback in case of getStorageDomainInfo call fails
    # please note that this code will get stuck if some of
    # the storage domains is not accessible rhbz#1140824
    for dname in os.listdir(parent):
        path = os.path.join(parent, dname, sd_uuid)
        if os.access(path, os.F_OK):
            return path
    raise Exception("path to storage domain {0} not found in {1}".format(sd_uuid, parent))
Пример #9
0
 def start(self):
     self.vdscli = vdscli.connect()
     self.netinfo = self._get_netinfo()
     if config.get('vars', 'net_persistence') == 'unified':
         self.config = RunningConfig()
     else:
         self.config = None
Пример #10
0
    def _setupVdsConnection(self):
        if self._mode == 'file':
            return

        # FIXME: The port will depend on the binding being used.
        # This assumes xmlrpc
        hostPort = vdscli.cannonizeHostPort(
            self._dst, self._vm.cif.bindings['xmlrpc'].serverPort)
        self.remoteHost, self.remotePort = hostPort.rsplit(':', 1)

        if config.getboolean('vars', 'ssl'):
            self.destServer = vdscli.connect(
                hostPort,
                useSSL=True,
                TransportClass=kaxmlrpclib.TcpkeepSafeTransport)
        else:
            self.destServer = kaxmlrpclib.Server('http://' + hostPort)
        self.log.debug('Destination server is: ' + hostPort)
        try:
            self.log.debug('Initiating connection with destination')
            status = self.destServer.getVmStats(self._vm.id)
            if not status['status']['code']:
                self.log.error("Machine already exists on the destination")
                self.status = errCode['exist']
        except Exception:
            self.log.error("Error initiating connection", exc_info=True)
            self.status = errCode['noConPeer']
Пример #11
0
def sync_mgmt():
    """Guess mgmt interface and update TUI config
       FIXME: Autoinstall should write MANAGED_BY and MANAGED_IFNAMES
       into /etc/defaults/ovirt
    """
    engine_data = None
    cfg = NodeManagement().retrieve()

    mgmtIface = []

    try:
        cli = vdscli.connect()
        networks = cli.getVdsCapabilities()['info']['networks']

        for net in networks:
            if net in ('ovirtmgmt', 'rhevm'):
                if 'bridge' in networks[net]:
                    mgmtIface = [networks[net]['bridge']]
                else:
                    mgmtIface = [networks[net]['iface']]
    except socket_error as err:
        if err.errno == errno.ECONNREFUSED:
            LOGGER.debug("Connection refused with VDSM", exc_info=True)
        elif err.errno == errno.ENETUNREACH:
            LOGGER.debug("Network is unreachable to reach VDSM", exc_info=True)
        else:
            LOGGER.error("Catching exception:", exc_info=True)
    except KeyError as err:
        LOGGER.error("Cannot collect network data!", exc_info=True)
    except Exception as err:
        if 'No permission to read file:' in str(err):
            LOGGER.debug("pem files not available yet!", exc_info=True)
        else:
            LOGGER.error("Catching exception:", exc_info=True)

    if cfg["mserver"] is not None and validate_server(cfg["mserver"]):
        cfg["mserver"], cfg["mport"] = cfg["mserver"].split(":")

    if cfg["mserver"] is not None and cfg["mserver"] != "None" and \
            cfg["mserver"] != "":
        server_url = [
            unicode(info) for info in [cfg["mserver"], cfg["mport"]] if info
        ]

        port, sslPort = compatiblePort(cfg["mport"])
        if sslPort:
            proto = "https"
        else:
            proto = "http"

        engine_data = '"%s %s://%s"' % (config.engine_name, proto,
                                        ":".join(server_url))

    if cfg['mserver'] == 'None' or cfg['mserver'] is None:
        cfg['mserver'] = ""
    if cfg['mport'] == 'None':
        cfg['mport'] = config.ENGINE_PORT

    # Update the /etc/defaults/ovirt file
    _hack_to_workaround_pyaug_issues(mgmtIface, cfg, engine_data)
Пример #12
0
Файл: vm.py Проект: ekohl/vdsm
 def _setupVdsConnection(self):
     if self._mode == 'file': return
     self.remoteHost = self._dst.split(':')[0]
     # FIXME: The port will depend on the binding being used.
     # This assumes xmlrpc
     self.remotePort = self._vm.cif.bindings['xmlrpc'].serverPort
     try:
         self.remotePort = self._dst.split(':')[1]
     except:
         pass
     serverAddress = self.remoteHost + ':' + self.remotePort
     if config.getboolean('vars', 'ssl'):
         self.destServer = vdscli.connect(serverAddress, useSSL=True,
                 TransportClass=kaxmlrpclib.TcpkeepSafeTransport)
     else:
         self.destServer = kaxmlrpclib.Server('http://' + serverAddress)
     self.log.debug('Destination server is: ' + serverAddress)
     try:
         self.log.debug('Initiating connection with destination')
         status = self.destServer.getVmStats(self._vm.id)
         if not status['status']['code']:
             self.log.error("Machine already exists on the destination")
             self.status = errCode['exist']
     except:
         self.log.error("Error initiating connection", exc_info=True)
         self.status = errCode['noConPeer']
Пример #13
0
 def start(self):
     self.vdscli = vdscli.connect()
     self.netinfo = \
         netinfo.NetInfo(self.vdscli.getVdsCapabilities()['info'])
     if config.get('vars', 'net_persistence') == 'unified':
         self.config = RunningConfig()
     else:
         self.config = None
Пример #14
0
 def __init__(self):
     self.vdscli = vdscli.connect()
     self.netinfo = \
         netinfo.NetInfo(self.vdscli.getVdsCapabilities()['info'])
     if config.get('vars', 'net_persistence') == 'unified':
         self.config = RunningConfig()
     else:
         self.config = None
Пример #15
0
def _connect_to_server(host, port, use_ssl):
    host_port = "%s:%s" % (host, port)
    try:
        return vdscli.connect(host_port, use_ssl)
    except socket.error as e:
        if e[0] == errno.ECONNREFUSED:
            raise ConnectionRefusedError(
                "Connection to %s refused" % (host_port,))
        raise
Пример #16
0
def _connect_to_server(host, port, use_ssl):
    host_port = "%s:%s" % (host, port)
    try:
        return vdscli.connect(host_port, use_ssl)
    except socket.error as e:
        if e[0] == errno.ECONNREFUSED:
            raise ConnectionRefusedError("Connection to %s refused" %
                                         (host_port, ))
        raise
Пример #17
0
 def __init__(self):
     super(XmlRpcVdsmInterface, self).__init__()
     try:
         self.vdsm_api = vdscli.connect()
         response = self.vdsm_api.ping()
         self._check_status(response)
     except socket.error as e:
         self.handle_connection_error(e)
     except vdsmException, e:
         e.handle_exception()
Пример #18
0
 def __init__(self):
     self.logger = logging.getLogger('mom.vdsmInterface')
     try:
         self.vdsm_api = vdscli.connect()
         response = self.vdsm_api.ping()
         self._check_status(response)
     except socket.error as e:
         self.handle_connection_error(e)
     except vdsmException, e:
         e.handle_exception()
Пример #19
0
 def __init__(self):
     self.logger = logging.getLogger('mom.vdsmInterface')
     try:
         self.vdsm_api = vdscli.connect()
         response = self.vdsm_api.ping()
         self._check_status(response)
     except socket.error as e:
         self.handle_connection_error(e)
     except vdsmException, e:
         e.handle_exception()
Пример #20
0
 def __init__(self):
     super(XmlRpcVdsmInterface, self).__init__()
     try:
         self.vdsm_api = vdscli.connect()
         response = self.vdsm_api.ping()
         self._check_status(response)
     except socket.error as e:
         self.handle_connection_error(e)
     except vdsmException as e:
         e.handle_exception()
Пример #21
0
def setupclient(useSSL, tsPath, timeout=sslutils.SOCKET_DEFAULT_TIMEOUT):
    server = TestServer(useSSL, tsPath)
    server.start()
    hostPort = '0:' + str(server.port)
    client = vdscli.connect(hostPort=hostPort,
                            useSSL=useSSL,
                            tsPath=tsPath,
                            timeout=timeout)
    try:
        yield client
    finally:
        server.stop()
Пример #22
0
 def start(self):
     if _JSONRPC_ENABLED:
         requestQueues = config.get('addresses', 'request_queues')
         requestQueue = requestQueues.split(",")[0]
         self.vdscli = jsonrpcvdscli.connect(requestQueue, xml_compat=False)
     else:
         self.vdscli = vdscli.connect()
     self.netinfo = self._get_netinfo()
     if config.get('vars', 'net_persistence') == 'unified':
         self.config = RunningConfig()
     else:
         self.config = None
Пример #23
0
 def _misc(self):
     self.logger.info(_('Configuring the management bridge'))
     conn = vdscli.connect()
     networks = {
         self.environment[ohostedcons.NetworkEnv.BRIDGE_NAME]:
         vds_info.network(
             vds_info.capabilities(conn),
             self.environment[ohostedcons.NetworkEnv.BRIDGE_IF]
         )
     }
     _setupNetworks(conn, networks, {}, {'connectivityCheck': False})
     _setSafeNetworkConfig(conn)
Пример #24
0
 def start(self):
     if _JSONRPC_ENABLED:
         requestQueues = config.get('addresses', 'request_queues')
         requestQueue = requestQueues.split(",")[0]
         self.vdscli = jsonrpcvdscli.connect(requestQueue, xml_compat=False)
     else:
         self.vdscli = vdscli.connect()
     self.netinfo = self._get_netinfo()
     if config.get('vars', 'net_persistence') == 'unified':
         self.config = RunningConfig()
     else:
         self.config = None
Пример #25
0
def setupclient(useSSL, tsPath,
                timeout=sslutils.SOCKET_DEFAULT_TIMEOUT):
    server = TestServer(useSSL, tsPath)
    server.start()
    hostPort = '0:' + str(server.port)
    client = vdscli.connect(hostPort=hostPort,
                            useSSL=useSSL,
                            tsPath=tsPath,
                            timeout=timeout)
    try:
        yield client
    finally:
        server.stop()
 def get_fc_lun_tuple_list(self):
     cli = vdscli.connect(timeout=900)
     fc_lun_list = []
     FC_DOMAIN = 2
     devices = cli.getDeviceList(FC_DOMAIN)
     if devices['status']['code'] != 0:
         raise RuntimeError(devices['status']['message'])
     for device in devices['devList']:
         device_info = "%s  %sGiB\n%s %s  status: %s" % (
                 device["GUID"], int(device['capacity']) / pow(2, 30),
                 device['vendorID'], device['productID'], device["status"],
             )
         fc_lun_list.append((device_info, None))
     return fc_lun_list
Пример #27
0
 def _boot_from_hd(self):
     # Temporary attach cloud-init no-cloud iso if we have to
     if (self.environment[ohostedcons.VMEnv.BOOT] == 'disk'
             and self.environment[ohostedcons.VMEnv.CDROM]):
         self.environment[ohostedcons.VMEnv.SUBST][
             '@CDROM@'] = self.environment[ohostedcons.VMEnv.CDROM]
     created = False
     while not created:
         try:
             self._create_vm()
             created = True
         except socket.error as e:
             self.logger.debug(
                 'Error talking with VDSM (%s), reconnecting.' % str(e),
                 exc_info=True)
             cli = vdscli.connect(
                 timeout=ohostedcons.Const.VDSCLI_SSL_TIMEOUT)
             self.environment[ohostedcons.VDSMEnv.VDS_CLI] = cli
Пример #28
0
 def _connect(self):
     cli = vdscli.connect(timeout=ohostedcons.Const.VDSCLI_SSL_TIMEOUT)
     self.environment[ohostedcons.VDSMEnv.VDS_CLI] = cli
     vdsmReady = False
     retry = 0
     while not vdsmReady and retry < self.MAX_RETRY:
         retry += 1
         try:
             hwinfo = cli.getVdsHardwareInfo()
             self.logger.debug(str(hwinfo))
             if hwinfo['status']['code'] == 0:
                 vdsmReady = True
             else:
                 self.logger.info(_('Waiting for VDSM hardware info'))
                 time.sleep(1)
         except socket.error:
             self.logger.info(_('Waiting for VDSM hardware info'))
             time.sleep(1)
 def _connect(self):
     cli = vdscli.connect(timeout=ohostedcons.Const.VDSCLI_SSL_TIMEOUT)
     self.environment[ohostedcons.VDSMEnv.VDS_CLI] = cli
     vdsmReady = False
     retry = 0
     while not vdsmReady and retry < self.MAX_RETRY:
         retry += 1
         try:
             hwinfo = cli.getVdsHardwareInfo()
             self.logger.debug(str(hwinfo))
             if hwinfo['status']['code'] == 0:
                 vdsmReady = True
             else:
                 self.logger.info(_('Waiting for VDSM hardware info'))
                 time.sleep(1)
         except socket.error:
             self.logger.info(_('Waiting for VDSM hardware info'))
             time.sleep(1)
Пример #30
0
 def _boot_from_install_media(self):
     # Need to be done after firewall closeup for allowing the user to
     # connect from remote.
     os_installed = False
     self._create_vm()
     while not os_installed:
         try:
             os_installed = check_liveliness.manualSetupDispatcher(
                 self,
                 check_liveliness.MSD_OS_INSTALLED,
             )
         except socket.error as e:
             self.logger.debug(
                 'Error talking with VDSM (%s), reconnecting.' % str(e),
                 exc_info=True)
             cli = vdscli.connect(
                 timeout=ohostedcons.Const.VDSCLI_SSL_TIMEOUT)
             self.environment[ohostedcons.VDSMEnv.VDS_CLI] = cli
Пример #31
0
    def _setupVdsConnection(self):
        if self.hibernating:
            return

        # FIXME: The port will depend on the binding being used.
        # This assumes xmlrpc
        hostPort = vdscli.cannonizeHostPort(
            self._dst,
            config.getint('addresses', 'management_port'))
        self.remoteHost, _ = hostPort.rsplit(':', 1)

        if config.getboolean('vars', 'ssl'):
            self._destServer = vdscli.connect(
                hostPort,
                useSSL=True,
                TransportClass=kaxmlrpclib.TcpkeepSafeTransport)
        else:
            self._destServer = kaxmlrpclib.Server('http://' + hostPort)
        self.log.debug('Destination server is: ' + hostPort)
Пример #32
0
    def testKSM(self):
        run = 1
        pages_to_scan = random.randint(100, 200)

        # Set a simple MOM policy to change KSM paramters unconditionally.
        testPolicyStr = """
            (Host.Control "ksm_run" %d)
            (Host.Control "ksm_pages_to_scan" %d)""" % \
            (run, pages_to_scan)
        s = vdscli.connect()
        r = s.setMOMPolicy(testPolicyStr)
        self.assertEqual(r['status']['code'], 0, str(r))

        # Wait for the policy taking effect
        time.sleep(10)

        hostStats = s.getVdsStats()['info']
        self.assertEqual(bool(run), hostStats['ksmState'])
        self.assertEqual(pages_to_scan, hostStats['ksmPages'])
Пример #33
0
 def _boot_from_install_media(self):
     # Need to be done after firewall closeup for allowing the user to
     # connect from remote.
     os_installed = False
     self._create_vm()
     while not os_installed:
         try:
             os_installed = check_liveliness.manualSetupDispatcher(
                 self,
                 check_liveliness.MSD_OS_INSTALLED,
             )
         except socket.error as e:
             self.logger.debug(
                 'Error talking with VDSM (%s), reconnecting.' % str(e),
                 exc_info=True
             )
             cli = vdscli.connect(
                 timeout=ohostedcons.Const.VDSCLI_SSL_TIMEOUT
             )
             self.environment[ohostedcons.VDSMEnv.VDS_CLI] = cli
Пример #34
0
def sync_mgmt():
    """Guess mgmt interface and update TUI config
       FIXME: Autoinstall should write MANAGED_BY and MANAGED_IFNAMES
       into /etc/defaults/ovirt
    """
    engine_data = None
    cfg = NodeManagement().retrieve()

    mgmtIface = []

    try:
        cli = vdscli.connect()
        networks = cli.getVdsCapabilities()['info']['networks']

        for net in networks:
            if net in ('ovirtmgmt', 'rhevm'):
                if 'bridge' in networks[net]:
                    mgmtIface = [networks[net]['bridge']]
                else:
                    mgmtIface = [networks[net]['iface']]
    except socket_error as err:
        if err.errno == errno.ECONNREFUSED:
            LOGGER.debug("Connection refused with VDSM", exc_info=True)
        elif err.errno == errno.ENETUNREACH:
            LOGGER.debug("Network is unreachable to reach VDSM", exc_info=True)
        else:
            LOGGER.error("Catching exception:", exc_info=True)
    except KeyError as err:
        LOGGER.error("Cannot collect network data!", exc_info=True)
    except Exception as err:
        if 'No permission to read file:' in str(err):
            LOGGER.debug("pem files not available yet!", exc_info=True)
        else:
            LOGGER.error("Catching exception:", exc_info=True)

    if cfg["mserver"] is not None and validate_server(cfg["mserver"]):
        cfg["mserver"], cfg["mport"] = cfg["mserver"].split(":")

    if cfg["mserver"] is not None and cfg["mserver"] != "None" and \
            cfg["mserver"] != "":
        server_url = [unicode(info) for info in [cfg["mserver"],
                                                 cfg["mport"]] if info]

        port, sslPort = compatiblePort(cfg["mport"])
        if sslPort:
            proto = "https"
        else:
            proto = "http"

        engine_data = '"%s %s://%s"' % (
            config.engine_name,
            proto,
            ":".join(server_url)
        )

    if cfg['mserver'] == 'None' or cfg['mserver'] is None:
        cfg['mserver'] = ""
    if cfg['mport'] == 'None':
        cfg['mport'] = config.ENGINE_PORT

    # Update the /etc/defaults/ovirt file
    _hack_to_workaround_pyaug_issues(mgmtIface, cfg, engine_data)
Пример #35
0
 def __init__(self):
     self.vdscli = vdscli.connect()
     self.netinfo = \
         netinfo.NetInfo(self.vdscli.getVdsCapabilities()['info'])
Пример #36
0
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
# Refer to the README and COPYING files for full details of the license
#

import os
import subprocess
import hooking
from vdsm import vdscli

s = vdscli.connect()

res = s.list(True)
if res['status']['code'] == 0:
    if not [v for v in res['vmList']
            if v.get('vmId') != os.environ.get('vmId') and
            hooking.tobool(v.get('custom', {}).get('sap_agent', False))]:
        subprocess.call(['/usr/bin/sudo', '-n', '/sbin/service', 'vhostmd',
                         'stop'])
Пример #37
0
 def __init__(self):
     self.vdscli = vdscli.connect()
     self.netinfo = \
         netinfo.NetInfo(self.vdscli.getVdsCapabilities()['info'])
Пример #38
0
    def _provision_gluster_volume(self):
        """
        Set parameters as suggested by Gluster Storage Domain Reference
        @see: http://www.ovirt.org/Gluster_Storage_Domain_Reference
        """
        cli = vdscli.connect()
        share = self.environment[ohostedcons.StorageEnv.GLUSTER_SHARE_NAME]
        brick = self.environment[ohostedcons.StorageEnv.GLUSTER_BRICK]
        self.logger.debug('glusterVolumesList')
        response = cli.glusterVolumesList()
        self.logger.debug(response)
        if response['status']['code'] != 0:
            self.logger.error(_('Failed to retrieve the Gluster Volume list'))
            raise RuntimeError(response['status']['message'])
        volumes = response['volumes']
        if share in volumes:
            self.logger.info(_('GlusterFS Volume already exists'))
            if set([brick]) != set(volumes[share]['bricks']):
                self.logger.debug(set([brick]))
                self.logger.debug(set(volumes[share]['bricks']))
                raise RuntimeError(
                    _('GlusterFS Volume has been found with different '
                      'bricks list'))
        else:
            self.logger.info(_('Creating GlusterFS Volume'))
            replica_count = ''
            stripe_count = ''
            transport_list = ['tcp']
            force = True
            self.logger.debug('glusterVolumeCreate')
            response = cli.glusterVolumeCreate(share, [brick], replica_count,
                                               stripe_count, transport_list,
                                               force)
            self.logger.debug(response)
            if response['status']['code'] != 0:
                self.logger.error(_('Failed to create the Gluster Volume'))
                raise RuntimeError(response['status']['message'])

        for option, value in {
                'cluster.quorum-type': 'auto',
                'network.ping-timeout': '10',
                'nfs.disable': 'on',
                'user.cifs': 'disable',
                'auth.allow': '*',
                'group': 'virt',
                'storage.owner-uid': '36',
                'storage.owner-gid': '36',
                'server.allow-insecure': 'on',
        }.items():
            self.logger.debug('glusterVolumeSet %s' % option)
            response = cli.glusterVolumeSet(share, option, value)
            if response['status']['code'] != 0:
                self.logger.error(
                    _('Failed to set {option} on the Gluster Volume').format(
                        option=option, ))
                raise RuntimeError(response['status']['message'])

        self.logger.debug('glusterVolumesList')
        response = cli.glusterVolumesList()
        self.logger.debug(response)
        if response['status']['code'] != 0:
            self.logger.error(_('Failed to retrieve the Gluster Volume list'))
            raise RuntimeError(response['status']['message'])
        volume = response['volumes'][share]
        self.logger.debug('glusterTasksList')
        response = cli.glusterTasksList()
        self.logger.debug(response)
        if response['status']['code'] != 0:
            self.logger.error(_('Failed to retrieve the Gluster Tasks List'))
            raise RuntimeError(response['status']['message'])
        # TODO: check if we need to do something about these tasks

        if volume['volumeStatus'] == 'ONLINE':
            self.logger.debug('GlusterFS Volume already started')
        elif volume['volumeStatus'] == 'OFFLINE':
            self.logger.debug('glusterVolumeStart')
            response = cli.glusterVolumeStart(share)
            if response['status']['code'] != 0:
                self.logger.error(_('Failed to start the Gluster Volume'))
                raise RuntimeError(response['status']['message'])
        else:
            raise RuntimeError(
                _('GlusterFS Volume found in an unknown state: {state}').
                format(state=volume['volumeStatus'], ))

        self.logger.debug('glusterVolumesList')
        response = cli.glusterVolumesList()
        self.logger.debug(response)
        if response['status']['code'] != 0:
            self.logger.error(_('Failed to retrieve the Gluster Volume list'))
            raise RuntimeError(response['status']['message'])
Пример #39
0
 def __connect__( self ): 
     ''''Connect VDSM, default connect local VDSM'''
     return vdscli.connect() 
Пример #40
0
def resume_paused_vm(vm_id):
    unpause_file = MARK_FOR_UNPAUSE_PATH % vm_id
    if os.path.isfile(unpause_file):
        vdscli.connect().cont(vm_id)
        os.remove(unpause_file)
Пример #41
0
    def _closeup(self):
        self._getPKICert()
        self._getSSHkey()
        cluster_name = None
        default_cluster_name = 'Default'
        try:
            self.logger.debug('Connecting to the Engine')
            engine_api = self._ovirtsdk_api.API(
                url='https://{fqdn}/ovirt-engine/api'.format(
                    fqdn=self.environment[
                        ohostedcons.NetworkEnv.OVIRT_HOSTED_ENGINE_FQDN
                    ],
                ),
                username='******',
                password=self.environment[
                    ohostedcons.EngineEnv.ADMIN_PASSWORD
                ],
                ca_file=self.environment[
                    ohostedcons.EngineEnv.TEMPORARY_CERT_FILE
                ],
            )

            conn = vdscli.connect()
            net_info = netinfo.NetInfo(vds_info.capabilities(conn))
            bridge_port = self.environment[ohostedcons.NetworkEnv.BRIDGE_IF]
            if bridge_port in net_info.vlans:
                self.logger.debug(
                    'Updating engine\'s management network to be vlanned'
                )
                vlan_id = net_info.vlans[bridge_port]['vlanid']
                mgmt_network = engine_api.networks.get(
                    name=self.environment[ohostedcons.NetworkEnv.BRIDGE_NAME]
                )
                mgmt_network.set_vlan(
                    self._ovirtsdk_xml.params.VLAN(id=vlan_id)
                )
                mgmt_network.update()

            self.logger.debug('Adding the host to the cluster')
            cluster_name = self.environment[
                ohostedcons.EngineEnv.HOST_CLUSTER_NAME
            ]
            if cluster_name is not None:
                if cluster_name not in [
                    c.get_name()
                    for c in engine_api.clusters.list()
                ]:
                    raise RuntimeError(
                        _(
                            'Specified cluster does not exist: {cluster}'
                        ).format(
                            cluster=cluster_name,
                        )
                    )
            else:
                cluster_l = [c.get_name() for c in engine_api.clusters.list()]
                cluster_name = (
                    default_cluster_name if default_cluster_name in
                    cluster_l else cluster_l[0]
                )
                cluster_name = self.dialog.queryString(
                    name='cluster_name',
                    note=_(
                        'Enter the name of the cluster to which you want to '
                        'add the host (@VALUES@) [@DEFAULT@]: '
                    ),
                    prompt=True,
                    default=cluster_name,
                    validValues=cluster_l,
                )
                self.environment[
                    ohostedcons.EngineEnv.HOST_CLUSTER_NAME
                ] = cluster_name
            engine_api.hosts.add(
                self._ovirtsdk_xml.params.Host(
                    name=self.environment[
                        ohostedcons.EngineEnv.APP_HOST_NAME
                    ],
                    address=self._getIPAddress(),
                    reboot_after_installation=False,
                    cluster=engine_api.clusters.get(cluster_name),
                    ssh=self._ovirtsdk_xml.params.SSH(
                        authentication_method='publickey',
                        port=self.environment[
                            ohostedcons.NetworkEnv.SSHD_PORT
                        ],
                    ),
                    override_iptables=True,
                )
            )
        except ovirtsdk.infrastructure.errors.RequestError as e:
            self.logger.debug(
                'Cannot add the host to cluster {cluster}'.format(
                    cluster=cluster_name,
                ),
                exc_info=True,
            )
            self.logger.error(
                _(
                    'Cannot automatically add the host '
                    'to cluster {cluster}:\n{details}\n'
                ).format(
                    cluster=cluster_name,
                    details=e.detail
                )
            )
            raise RuntimeError(
                _(
                    'Cannot add the host to cluster {cluster}'
                ).format(
                    cluster=cluster_name,
                )
            )

        if self.environment[
            ohostedcons.CoreEnv.IS_ADDITIONAL_HOST
        ]:
            self._check_network_configuration(
                engine_api,
                self.environment[ohostedcons.EngineEnv.APP_HOST_NAME],
            )
        else:
            up = self._wait_host_ready(
                engine_api,
                self.environment[ohostedcons.EngineEnv.APP_HOST_NAME]
            )
            if not up:
                self.logger.error(
                    _(
                        'Unable to add {host} to the manager'
                    ).format(
                        host=self.environment[
                            ohostedcons.EngineEnv.APP_HOST_NAME
                        ],
                    )
                )
            else:
                # This works only if the host is up.
                self.logger.debug('Setting CPU for the cluster')
                try:
                    cluster, cpu = self._wait_cluster_cpu_ready(
                        engine_api,
                        cluster_name
                    )
                    self.logger.debug(cpu.__dict__)
                    cpu.set_id(
                        self.environment[ohostedcons.VDSMEnv.ENGINE_CPU]
                    )
                    cluster.set_cpu(cpu)
                    cluster.update()
                except ovirtsdk.infrastructure.errors.RequestError as e:
                    self.logger.debug(
                        'Cannot set CPU level of cluster {cluster}'.format(
                            cluster=cluster_name,
                        ),
                        exc_info=True,
                    )
                    self.logger.error(
                        _(
                            'Cannot automatically set CPU level '
                            'of cluster {cluster}:\n{details}\n'
                        ).format(
                            cluster=cluster_name,
                            details=e.detail
                        )
                    )
        engine_api.disconnect()
Пример #42
0
 def setUp(self):
     isSSL = config.getboolean('vars', 'ssl')
     if isSSL and os.geteuid() != 0:
         raise SkipTest("Must be root to use SSL connection to server")
     self.s = vdscli.connect(useSSL=isSSL)
Пример #43
0
 def setUp(self):
     isSSL = config.getboolean('vars', 'ssl')
     if isSSL and os.geteuid() != 0:
         raise SkipTest("Must be root to use SSL connection to server")
     self.s = vdscli.connect(useSSL=isSSL)
Пример #44
0
 def setUp(self):
     self.s = vdscli.connect()
Пример #45
0
 def setUp(self):
     self.s = vdscli.connect()
Пример #46
0
  cmd["drives"].append(disk) 
  cmd["drives"][counter]["domainID"]=diskdomids[counter]
  cmd["drives"][counter]["poolID"]=diskpoolids[counter]
  counter=counter+1

 cmd["memSize"]=memory
 cmd["smpCoresPerSocket"]=cpuspersocket
 cmd["smp"]=smp
 cmd["bridge"]=",".join(bridges)
 cmd["macAddr"]=",".join(macs)
 cmd["vmName"]=name
 cmd["nicModel"]=",".join(nicmodels)
 return cmd

useSSL = True
s=vdscli.connect("%s:%s" % (host,port),useSSL, truststore)

#check if i am spm
try:
 spuid=s.getConnectedStoragePoolsList()["poollist"][0]
 sppath= "/rhev/data-center/%s/mastersd/master/vms" % spuid
 if s.getSpmStatus(spuid)['spm_st']['spmStatus']=="SPM":
  spm=True
 else:
  spm=False
except:
 spm=False

if listing:
 vms={}
 vmids=[]
    def _provision_gluster_volume(self):
        """
        Set parameters as suggested by Gluster Storage Domain Reference
        @see: http://www.ovirt.org/Gluster_Storage_Domain_Reference
        """
        cli = vdscli.connect()
        share = self.environment[ohostedcons.StorageEnv.GLUSTER_SHARE_NAME]
        brick = self.environment[ohostedcons.StorageEnv.GLUSTER_BRICK]
        self.logger.debug('glusterVolumesList')
        response = cli.glusterVolumesList()
        self.logger.debug(response)
        if response['status']['code'] != 0:
            self.logger.error(_('Failed to retrieve the Gluster Volume list'))
            raise RuntimeError(response['status']['message'])
        volumes = response['volumes']
        if share in volumes:
            self.logger.info(_('GlusterFS Volume already exists'))
            if set([brick]) != set(volumes[share]['bricks']):
                self.logger.debug(set([brick]))
                self.logger.debug(set(volumes[share]['bricks']))
                raise RuntimeError(
                    _(
                        'GlusterFS Volume has been found with different '
                        'bricks list'
                    )
                )
        else:
            self.logger.info(_('Creating GlusterFS Volume'))
            replica_count = ''
            stripe_count = ''
            transport_list = ['tcp']
            force = True
            self.logger.debug('glusterVolumeCreate')
            response = cli.glusterVolumeCreate(
                share,
                [brick],
                replica_count,
                stripe_count,
                transport_list,
                force
            )
            self.logger.debug(response)
            if response['status']['code'] != 0:
                self.logger.error(_('Failed to create the Gluster Volume'))
                raise RuntimeError(response['status']['message'])

        for option, value in {
            'cluster.quorum-type': 'auto',
            'network.ping-timeout': '10',
            'nfs.disable': 'on',
            'user.cifs': 'disable',
            'auth.allow': '*',
            'group': 'virt',
            'storage.owner-uid': '36',
            'storage.owner-gid': '36',
            'server.allow-insecure': 'on',
        }.items():
            self.logger.debug('glusterVolumeSet %s' % option)
            response = cli.glusterVolumeSet(
                share,
                option,
                value
            )
            if response['status']['code'] != 0:
                self.logger.error(
                    _('Failed to set {option} on the Gluster Volume').format(
                        option=option,
                    )
                )
                raise RuntimeError(response['status']['message'])

        self.logger.debug('glusterVolumesList')
        response = cli.glusterVolumesList()
        self.logger.debug(response)
        if response['status']['code'] != 0:
            self.logger.error(_('Failed to retrieve the Gluster Volume list'))
            raise RuntimeError(response['status']['message'])
        volume = response['volumes'][share]
        self.logger.debug('glusterTasksList')
        response = cli.glusterTasksList()
        self.logger.debug(response)
        if response['status']['code'] != 0:
            self.logger.error(_('Failed to retrieve the Gluster Tasks List'))
            raise RuntimeError(response['status']['message'])
        # TODO: check if we need to do something about these tasks

        if volume['volumeStatus'] == 'ONLINE':
            self.logger.debug('GlusterFS Volume already started')
        elif volume['volumeStatus'] == 'OFFLINE':
            self.logger.debug('glusterVolumeStart')
            response = cli.glusterVolumeStart(share)
            if response['status']['code'] != 0:
                self.logger.error(_('Failed to start the Gluster Volume'))
                raise RuntimeError(response['status']['message'])
        else:
            raise RuntimeError(
                _(
                    'GlusterFS Volume found in an unknown state: {state}'
                ).format(
                    state=volume['volumeStatus'],
                )
            )

        self.logger.debug('glusterVolumesList')
        response = cli.glusterVolumesList()
        self.logger.debug(response)
        if response['status']['code'] != 0:
            self.logger.error(_('Failed to retrieve the Gluster Volume list'))
            raise RuntimeError(response['status']['message'])
Пример #48
0
        cmd["drives"].append(disk)
        cmd["drives"][counter]["domainID"] = diskdomids[counter]
        cmd["drives"][counter]["poolID"] = diskpoolids[counter]
        counter = counter + 1

    cmd["memSize"] = memory
    cmd["smpCoresPerSocket"] = cpuspersocket
    cmd["smp"] = smp
    cmd["bridge"] = ",".join(bridges)
    cmd["macAddr"] = ",".join(macs)
    cmd["vmName"] = name
    cmd["nicModel"] = ",".join(nicmodels)
    return cmd

useSSL = True
s = vdscli.connect("%s:%s" % (host, port), useSSL, truststore)

# check if i am spm
try:
    spuid = s.getConnectedStoragePoolsList()["poollist"][0]
    sppath = "/rhev/data-center/%s/mastersd/master/vms" % spuid
    if s.getSpmStatus(spuid)['spm_st']['spmStatus'] == "SPM":
        spm = True
    else:
        spm = False
except:
    spm = False

if listing:
    vms = {}
    vmids = []
Пример #49
0
#!/bin/python
from vdsm import vdscli
import socket

c = vdscli.connect()
network_attrs = {
    'nic': 'veth_name0',
    'ipaddr': socket.gethostbyname(socket.gethostname()),
    'netmask': '255.240.0.0',
    'gateway': '172.17.0.1',
    'defaultRoute': True,
    'bridged': True
}

c.setupNetworks({'ovirtmgmt': network_attrs}, {}, {'connectivityCheck': False})
Пример #50
0
def resume_paused_vm(vm_id):
    unpause_file = MARK_FOR_UNPAUSE_PATH % vm_id
    if os.path.isfile(unpause_file):
        vdscli.connect().cont(vm_id)
        os.remove(unpause_file)