예제 #1
0
 def database_name(self):
     databases = self._get_database_names()
     if len(databases) == 0:
         raise exception.GuestError('No database found on guest.')
     elif len(databases) > 1:
         raise exception.GuestError('Multiple databases found on guest.')
     return databases[0]
예제 #2
0
파일: api.py 프로젝트: xiaohongshu/trove
 def _cast(self, method_name, version, **kwargs):
     LOG.debug("Casting %s" % method_name)
     try:
         cctxt = self.client.prepare(version=version)
         cctxt.cast(self.context, method_name, **kwargs)
     except RemoteError as r:
         LOG.exception(_("Error calling %s") % method_name)
         raise exception.GuestError(original_message=r.value)
     except Exception as e:
         LOG.exception(_("Error calling %s") % method_name)
         raise exception.GuestError(original_message=str(e))
예제 #3
0
 def _cast(self, method_name, **kwargs):
     LOG.debug("Casting %s" % method_name)
     try:
         self.cast(self.context, self.make_msg(method_name, **kwargs),
                   topic=kwargs.get('topic'),
                   version=kwargs.get('version'))
     except common.RemoteError as r:
         LOG.error(r)
         raise exception.GuestError(original_message=r.value)
     except Exception as e:
         LOG.error(e)
         raise exception.GuestError(original_message=str(e))
예제 #4
0
 def _cast(self, method_name, version, **kwargs):
     LOG.debug("Calling %s asynchronously", method_name)
     try:
         with NotificationCastWrapper(self.context, 'guest'):
             cctxt = self.client.prepare(version=version)
             cctxt.cast(self.context, method_name, **kwargs)
     except RemoteError as r:
         LOG.exception("Error calling %s", method_name)
         raise exception.GuestError(original_message=r.value)
     except Exception as e:
         LOG.exception("Error calling %s", method_name)
         raise exception.GuestError(original_message=str(e))
예제 #5
0
 def get_private_vip(self, ip):
     if_addr_pairs = self._get_if_addr_pairs()
     for i in range(len(if_addr_pairs)):
         # address shows up as 192.168.70.3/24, so discard the /24
         if if_addr_pairs[i][1].split('/')[0] == ip:
             if if_addr_pairs[i][0] != if_addr_pairs[i + 1][0]:
                 raise exception.GuestError(
                     _("Missing interconnect {interface} virtual IP.").
                     format(interface=if_addr_pairs[i][0]))
             return if_addr_pairs[i + 1][1].split('/')[0]
     raise exception.GuestError(
         _("Could not find interface with address {ip}").format(ip=ip))
예제 #6
0
    def __init__(self, manager_name):
        super(Manager, self).__init__(CONF)

        # Manager properties
        self.__manager_name = manager_name
        self.__manager = None
        self.__prepare_error = False

        # Guest log
        self._guest_log_context = None
        self._guest_log_loaded_context = None
        self._guest_log_cache = None
        self._guest_log_defs = None

        # Module
        self.module_driver_manager = driver_manager.ModuleDriverManager()

        # Drivers should implement
        self.adm = None
        self.app = None
        self.status = None

        if CONF.guest_agent.container_registry:
            try:
                self.docker_client.login(
                    CONF.guest_agent.container_registry_username,
                    CONF.guest_agent.container_registry_password,
                    email="",
                    registry=CONF.guest_agent.container_registry)
            except Exception as exc:
                raise exception.GuestError(f"Failed to login the container "
                                           f"registry, error: {str(exc)}")
예제 #7
0
    def delete_user(self, user):
        LOG.debug("Delete a given user.")
        db2_user = models.DatastoreUser.deserialize(user)
        db2_user.check_delete()
        userName = db2_user.name
        user_dbs = db2_user.databases
        LOG.debug("For user %s, databases to be deleted = %r." % (
            userName, user_dbs))

        if len(user_dbs) == 0:
            databases = self.list_access(db2_user.name, None)
        else:
            databases = user_dbs

        LOG.debug("databases for user = %r." % databases)
        for database in databases:
            mydb = models.DatastoreSchema.deserialize(database)
            try:
                run_command(system.REVOKE_USER_ACCESS % {
                    'dbname': mydb.name,
                    'login': userName})
                LOG.debug("Revoked access for user:%s on database:%s." % (
                    userName, mydb.name))
            except exception.ProcessExecutionError as pe:
                LOG.debug("Error occurred while revoking access to %s." %
                          mydb.name)
                pass
            try:
                utils.execute_with_timeout(system.DELETE_USER_COMMAND % {
                    'login': db2_user.name.lower()}, shell=True)
            except exception.ProcessExecutionError as pe:
                LOG.exception(_(
                    "There was an error while deleting user: %s.") % pe)
                raise exception.GuestError(original_message=_(
                    "Unable to delete user: %s.") % userName)
예제 #8
0
    def _call(self, method_name, timeout_sec, version, **kwargs):
        LOG.debug("Calling %s with timeout %s" % (method_name, timeout_sec))
        try:
            cctxt = self.client.prepare(version=version, timeout=timeout_sec)
            result = cctxt.call(self.context, method_name, **kwargs)

            LOG.debug("Result is %s." % result)
            return result
        except RemoteError as r:
            LOG.exception(_("Error calling %s") % method_name)
            raise exception.GuestError(original_message=r.value)
        except Exception as e:
            LOG.exception(_("Error calling %s") % method_name)
            raise exception.GuestError(original_message=str(e))
        except Timeout:
            raise exception.GuestTimeout()
예제 #9
0
파일: api.py 프로젝트: sitle/trove
    def _cast_with_consumer(self, method_name, **kwargs):
        conn = None
        try:
            conn = rpc.create_connection(new=True)
            conn.create_consumer(self._get_routing_key(), None, fanout=False)
        except common.RemoteError as r:
            LOG.error(r)
            raise exception.GuestError(original_message=r.value)
        except Exception as e:
            LOG.error(e)
            raise exception.GuestError(original_message=str(e))
        finally:
            if conn:
                conn.close()

        # leave the cast call out of the hackity consumer create
        self._cast(method_name, **kwargs)
예제 #10
0
    def _call(self, method_name, timeout_sec, **kwargs):
        LOG.debug("Calling %s with timeout %s." % (method_name, timeout_sec))
        try:
            result = self.call(self.context,
                               self.make_msg(method_name, **kwargs),
                               timeout=timeout_sec)

            LOG.debug("Result is %s." % result)
            return result
        except common.RemoteError as r:
            LOG.exception(_("Error calling %s") % method_name)
            raise exception.GuestError(original_message=r.value)
        except Exception as e:
            LOG.exception(_("Error calling %s") % method_name)
            raise exception.GuestError(original_message=str(e))
        except Timeout:
            raise exception.GuestTimeout()
예제 #11
0
파일: volume.py 프로젝트: novo-maria/trove
 def check_format(self, device_path):
     stdout, stderr = utils.execute("xfs_admin",
                                    "-l",
                                    device_path,
                                    run_as_root=True,
                                    root_helper="sudo")
     if 'not a valid XFS filesystem' in stdout:
         msg = _("Volume '%s' does not appear to be formatted.") % (
             device_path)
         raise exception.GuestError(original_message=msg)
예제 #12
0
파일: volume.py 프로젝트: novo-maria/trove
def log_and_raise(log_fmt, exc_fmt, fmt_content=None):
    if fmt_content is not None:
        LOG.exception(log_fmt, fmt_content)
        raise_msg = exc_fmt % fmt_content
    else:
        # if fmt_content is not provided, log_fmt and
        # exc_fmt are just plain string messages
        LOG.exception(log_fmt)
        raise_msg = exc_fmt
    raise_msg += _("\nExc: %s") % traceback.format_exc()
    raise exception.GuestError(original_message=raise_msg)
예제 #13
0
 def delete_database(self, database):
     """Delete the specified database."""
     dbName = None
     try:
         mydb = models.DatastoreSchema.deserialize(database)
         mydb.check_delete()
         dbName = mydb.name
         LOG.debug("Deleting DB2 database: %s.", dbName)
         run_command(system.DELETE_DB_COMMAND % {'dbname': dbName})
     except exception.ProcessExecutionError:
         LOG.exception(
             "There was an error while deleting database:%s.", dbName)
         raise exception.GuestError(original_message=_(
             "Unable to delete database: %s.") % dbName)
예제 #14
0
 def delete_database(self, database):
     """Delete the specified database."""
     dbName = None
     try:
         mydb = models.ValidatedMySQLDatabase()
         mydb.deserialize(database)
         dbName = mydb.name
         LOG.debug("Deleting DB2 database: %s." % dbName)
         run_command(system.DELETE_DB_COMMAND % {'dbname': dbName})
     except exception.ProcessExecutionError:
         LOG.exception(
             _("There was an error while deleting database:%s.") % dbName)
         raise exception.GuestError(
             _("Unable to delete database: %s.") % dbName)
예제 #15
0
 def pkg_version(self, package_name):
     cmd_list = ["dpkg", "-l", package_name]
     p = commands.getstatusoutput(' '.join(cmd_list))
     # check the command status code
     if not p[0] == 0:
         return None
     # Need to capture the version string
     # check the command output
     std_out = p[1]
     patterns = [
         '.*No packages found matching.*', "\w\w\s+(\S+)\s+(\S+)\s+(.*)$"
     ]
     for line in std_out.split("\n"):
         for p in patterns:
             regex = re.compile(p)
             matches = regex.match(line)
             if matches:
                 line = matches.group()
                 parts = line.split()
                 if not parts:
                     msg = _("returned nothing")
                     LOG.error(msg)
                     raise exception.GuestError(msg)
                 if len(parts) <= 2:
                     msg = _("Unexpected output.")
                     LOG.error(msg)
                     raise exception.GuestError(msg)
                 if parts[1] != package_name:
                     msg = _("Unexpected output:[1] = %s") % str(parts[1])
                     LOG.error(msg)
                     raise exception.GuestError(msg)
                 if parts[0] == 'un' or parts[2] == '<none>':
                     return None
                 return parts[2]
     msg = _("version() saw unexpected output from dpkg!")
     LOG.error(msg)
예제 #16
0
 def determine_sid(self):
     hostname = self._get_hostname()
     stdout, stderr = run_sys_command(
         '{crsctl} stat res -w "TYPE = ora.database.type" -t'.format(
             crsctl=path.join(GRID_HOME, 'bin', 'crsctl')))
     instance_id = None
     for line in stdout.split('\n'):
         words = line.strip().split()
         if hostname in words:
             instance_id = words[0]
     if not instance_id:
         raise exception.GuestError(
             _("Could not find hostname in crsctl information."))
     self.admin.ora_config.cluster_sid = "{dbname}{instance_id}".format(
         dbname=self.admin.ora_config.db_name, instance_id=instance_id)
예제 #17
0
 def test_create_cluster_fail(self, mock_logging, mock_dv, mock_ds,
                              mock_find_all, mock_load, mock_ready, mock_ip,
                              mock_reset_task, mock_update_status):
     mock_find_all.return_value.all.return_value = [self.dbinst1]
     mock_load.return_value = BaseInstance(
         Mock(), self.dbinst1, Mock(),
         InstanceServiceStatus(ServiceStatuses.NEW))
     mock_ip.return_value = "10.0.0.2"
     guest_client = Mock()
     guest_client.install_cluster = Mock(
         side_effect=exception.GuestError("Error"))
     with patch.object(ClusterTasks, 'get_guest',
                       return_value=guest_client):
         self.clustertasks.create_cluster(Mock(), self.cluster_id)
         mock_update_status.assert_called_with('1232')
         mock_reset_task.assert_called_with()
예제 #18
0
파일: api.py 프로젝트: tattabbum/trove
    def _call(self, method_name, timeout_sec, **kwargs):
        LOG.debug("Calling %s with timeout %s" % (method_name, timeout_sec))
        try:
            result = self.call(self.context,
                               self.make_msg(method_name, **kwargs),
                               timeout=timeout_sec)

            LOG.debug("Result is %s" % result)
            return result
        except Exception as e:
            LOG.error(e)
            raise exception.GuestError(original_message=str(e))
        except Timeout as t:
            if t is not timeout:
                raise
            else:
                raise exception.GuestTimeout()
예제 #19
0
 def delete_database(self, database):
     '''Delete the specified database.'''
     dbName = None
     try:
         dbName = models.CouchDBSchema.deserialize_schema(database).name
         LOG.debug("Deleting CouchDB database: %s." % dbName)
         utils.execute_with_timeout(system.DELETE_DB_COMMAND % {
             'admin_name': self._admin_user().name,
             'admin_password': self._admin_user().password,
             'dbname': dbName
         },
                                    shell=True)
     except exception.ProcessExecutionError:
         LOG.exception(
             _("There was an error while deleting database:%s.") % dbName)
         raise exception.GuestError(
             _("Unable to delete database: %s.") % dbName)
예제 #20
0
 def delete_database(self, database):
     """Delete the specified database."""
     dbName = None
     try:
         oradb = models.OracleSchema.deserialize_schema(database)
         dbName = oradb.name
         LOG.debug("Deleting Oracle database: %s." % dbName)
         run_command(
             system.DELETE_DB_COMMAND % {
                 'db': dbName,
                 'sys_user': ADMIN_USER_NAME,
                 'sys_pswd': OracleConfig().admin_password
             })
     except exception.ProcessExecutionError:
         LOG.exception(
             _("There was an error while deleting database:%s.") % dbName)
         raise exception.GuestError(
             _("Unable to delete database: %s.") % dbName)
예제 #21
0
    def guest_log_enable(self, context, log_name, disable):
        """This method can be overridden by datastore implementations to
        facilitate enabling and disabling USER type logs.  If the logs
        can be enabled with simple configuration group changes, however,
        the code here will probably suffice.
        Must return whether the datastore needs to be restarted in order for
        the logging to begin.
        """
        restart_required = False
        verb = ("Disabling" if disable else "Enabling")
        if self.configuration_manager:
            LOG.debug("%(verb)s log '%(log)s'", {
                'verb': verb,
                'log': log_name
            })
            gl_def = self.get_guest_log_defs()[log_name]
            enable_cfg_label = "%s_%s_log" % (self.GUEST_LOG_ENABLE_LABEL,
                                              log_name)
            disable_cfg_label = "%s_%s_log" % (self.GUEST_LOG_DISABLE_LABEL,
                                               log_name)
            restart_required = gl_def.get(self.GUEST_LOG_RESTART_LABEL,
                                          restart_required)
            if disable:
                self._apply_log_overrides(
                    context, enable_cfg_label, disable_cfg_label,
                    gl_def.get(self.GUEST_LOG_DISABLE_LABEL),
                    gl_def.get(self.GUEST_LOG_SECTION_LABEL), restart_required)
            else:
                self._apply_log_overrides(
                    context, disable_cfg_label, enable_cfg_label,
                    gl_def.get(self.GUEST_LOG_ENABLE_LABEL),
                    gl_def.get(self.GUEST_LOG_SECTION_LABEL), restart_required)
        else:
            log_fmt = ("%(verb)s log '%(log)s' not supported - "
                       "no configuration manager defined!")
            exc_fmt = _("%(verb)s log '%(log)s' not supported - "
                        "no configuration manager defined!")
            msg_content = {'verb': verb, 'log': log_name}
            LOG.error(log_fmt, msg_content)
            raise exception.GuestError(original_message=(exc_fmt %
                                                         msg_content))

        return restart_required
예제 #22
0
 def _check_format(self):
     """Checks that a volume is formatted."""
     LOG.debug("Checking whether '%s' is formatted." % self.device_path)
     try:
         stdout, stderr = utils.execute(
             "dumpe2fs", self.device_path,
             run_as_root=True, root_helper="sudo")
         if 'has_journal' not in stdout:
             msg = _("Volume '%s' does not appear to be formatted.") % (
                 self.device_path)
             raise exception.GuestError(original_message=msg)
     except exception.ProcessExecutionError as pe:
         if 'Wrong magic number' in pe.stderr:
             volume_fstype = CONF.volume_fstype
             msg = _("'Device '%(dev)s' did not seem to be '%(type)s'.") % (
                 {'dev': self.device_path, 'type': volume_fstype})
             log_and_raise(msg)
         msg = _("Volume '%s' was not formatted.") % self.device_path
         log_and_raise(msg)
예제 #23
0
 def delete_database(self, database):
     '''Delete the specified database.'''
     dbName = models.CouchDBSchema.deserialize(database).name
     if self._is_modifiable_database(dbName):
         try:
             LOG.debug("Deleting CouchDB database: %s.", dbName)
             utils.execute_with_timeout(
                 system.DELETE_DB_COMMAND %
                 {'admin_name': self._admin_user().name,
                  'admin_password': self._admin_user().password,
                  'dbname': dbName},
                 shell=True)
         except exception.ProcessExecutionError:
             LOG.exception(_(
                 "There was an error while deleting database:%s."), dbName)
             raise exception.GuestError(original_message=_(
                 "Unable to delete database: %s.") % dbName)
     else:
         LOG.warning(_('Cannot delete a reserved database '
                       '%(db)s'), {'db': dbName})
예제 #24
0
파일: volume.py 프로젝트: novo-maria/trove
 def check_format(self, device_path):
     try:
         stdout, stderr = utils.execute("dumpe2fs",
                                        device_path,
                                        run_as_root=True,
                                        root_helper="sudo")
         if 'has_journal' not in stdout:
             msg = _("Volume '%s' does not appear to be formatted.") % (
                 device_path)
             raise exception.GuestError(original_message=msg)
     except exception.ProcessExecutionError as pe:
         if 'Wrong magic number' in pe.stderr:
             volume_fstype = self.fstype
             log_fmt = "'Device '%(dev)s' did not seem to be '%(type)s'."
             exc_fmt = _("'Device '%(dev)s' did not seem to be '%(type)s'.")
             log_and_raise(log_fmt, exc_fmt, {
                 'dev': device_path,
                 'type': volume_fstype
             })
         log_fmt = "Volume '%s' was not formatted."
         exc_fmt = _("Volume '%s' was not formatted.")
         log_and_raise(log_fmt, exc_fmt, device_path)
예제 #25
0
    def mount_storage(self, storage_info):
        fstab = path.join('/etc', 'fstab')
        default_mount_options = ('rw,bg,hard,nointr,tcp,vers=3,timeo=600,'
                                 'rsize=32768,wsize=32768,actimeo=0')
        data_mount_options = ('user,tcp,rsize=32768,wsize=32768,hard,intr,'
                              'noac,nfsvers=3')
        if storage_info['type'] == 'nfs':
            sources = storage_info['data']
            data = list()
            if operating_system.exists(fstab):
                data.append(operating_system.read_file(fstab, as_root=True))

            def _line(source, target, options=default_mount_options):
                data.append('{source} {target} nfs {options} 0 0'.format(
                    source=source, target=target, options=options))

            _line(
                sources['votedisk_mount'],
                SHARED_DISK_PATHS['votedisk'],
            )
            _line(
                sources['registry_mount'],
                SHARED_DISK_PATHS['registry'],
            )
            _line(sources['database_mount'], SHARED_DISK_PATHS['database'],
                  data_mount_options)
            operating_system.write_file(fstab, '\n'.join(data), as_root=True)
            utils.execute_with_timeout('mount',
                                       '-a',
                                       run_as_root=True,
                                       root_helper='sudo',
                                       timeout=service.ORACLE_TIMEOUT,
                                       log_output_on_error=True)
        else:
            raise exception.GuestError(
                _("Storage type {t} not valid.").format(
                    t=storage_info['type']))
예제 #26
0
def log_and_raise(message):
    LOG.exception(message)
    raise_msg = message + _("\nExc: %s") % traceback.format_exc()
    raise exception.GuestError(original_message=raise_msg)
예제 #27
0
    def delete_user(self, user):
        LOG.debug("Delete a given CouchDB user.")
        couchdb_user = models.CouchDBUser.deserialize(user)
        db_names = self.list_database_names()

        for db in db_names:
            userlist = []
            try:
                out, err = utils.execute_with_timeout(
                    system.DB_ACCESS_COMMAND %
                    {'admin_name': self._admin_user().name,
                     'admin_password': self._admin_user().password,
                     'dbname': db},
                    shell=True)
            except exception.ProcessExecutionError:
                LOG.debug(
                    "Error while trying to get the users for database: %s.",
                    db)
                continue

            evalout = ast.literal_eval(out)
            if evalout:
                members = evalout['members']
                names = members['names']
                for i in range(0, len(names)):
                    couchdb_user.databases = db
                    userlist.append(names[i])
                if couchdb_user.name in userlist:
                    userlist.remove(couchdb_user.name)
            out2, err2 = utils.execute_with_timeout(
                system.REVOKE_ACCESS_COMMAND % {
                    'admin_name': self._admin_user().name,
                    'admin_password': self._admin_user().password,
                    'dbname': db,
                    'username': userlist},
                shell=True)

        try:
            out2, err = utils.execute_with_timeout(
                system.DELETE_REV_ID %
                {'admin_name': self._admin_user().name,
                 'admin_password': self._admin_user().password},
                shell=True)
            evalout2 = ast.literal_eval(out2)
            rows = evalout2['rows']
            userlist = []

            for i in range(0, len(rows)):
                row = rows[i]
                username = "******" + couchdb_user.name
                if row['key'] == username:
                    rev = row['value']
                    revid = rev['rev']
            utils.execute_with_timeout(
                system.DELETE_USER_COMMAND % {
                    'admin_name': self._admin_user().name,
                    'admin_password': self._admin_user().password,
                    'username': couchdb_user.name,
                    'revid': revid},
                shell=True)
        except exception.ProcessExecutionError as pe:
            LOG.exception(_(
                "There was an error while deleting user: %s."), pe)
            raise exception.GuestError(original_message=_(
                "Unable to delete user: %s.") % couchdb_user.name)