예제 #1
0
    def client_db_rename(self, db=None, new_dbname=None, **params):
        if not new_dbname:
            raise werkzeug.exceptions.BadRequest(
                "New database name not specified")
        if service_db.exp_db_exist(new_dbname):
            raise werkzeug.exceptions.Conflict(
                description="Database %s already exists" % new_dbname)

        _logger.info("Renaming database '%s' to '%s'...", db, new_dbname)
        try:
            service_db.exp_rename(db, new_dbname)
        except Exception as e:
            _logger.error("Rename database '%s' to '%s' failed:\n%s", db,
                          new_dbname, e)
            raise werkzeug.exceptions.InternalServerError(
                description="Cannot rename database (%s -> %s):\n%s" %
                (db, new_dbname, e))

        # Sometime, database is not available just after renaming,
        # thus we have to wait while it will be available.
        # Especially, this case sometimes happens with large databases (60+ GB)
        for __ in retry_iter(interval_timeout=0.5,
                             max_retries=10,
                             first_timeout=False):
            if service_db.exp_db_exist(new_dbname):
                return Response('OK', status=200)

        # If database still not available - raise error
        raise werkzeug.exceptions.InternalServerError(
            description="Cannot rename database (%s -> %s):\nTimed out" %
            (db, new_dbname))
예제 #2
0
 def client_db_restore(self,
                       db=None,
                       backup_file=None,
                       copy=False,
                       **params):
     if not db:
         raise werkzeug.exceptions.BadRequest("Database not specified")
     if service_db.exp_db_exist(db):
         raise werkzeug.exceptions.Conflict(
             description="Database %s already exists" % db)
     try:
         with tempfile.NamedTemporaryFile(delete=False) as data_file:
             backup_file.save(data_file)
         service_db.restore_db(db, data_file.name, str2bool(copy))
     except exceptions.AccessDenied as e:
         raise werkzeug.exceptions.Forbidden(description=str(e))
     except Exception as e:
         _logger.error("Cannot restore db %s", db, exc_info=True)
         raise werkzeug.exceptions.InternalServerError(
             "Cannot restore db (%s): %s" % (db, str(e)))
     else:
         self._postprocess_restored_db(db)
         return http.Response('OK', status=200)
     finally:
         os.unlink(data_file.name)
예제 #3
0
 def wrapper(*args, **kwargs):
     db = kwargs.get('db', None)
     if not db:
         raise werkzeug.exceptions.BadRequest("Database not specified")
     if not exp_db_exist(db):
         _logger.info('Database %s is not found.', db)
         raise DatabaseNotExists()
     return func(*args, **kwargs)
예제 #4
0
    def client_db_duplicate(self, db=None, new_dbname=None, **params):
        if not new_dbname:
            raise werkzeug.exceptions.BadRequest(
                "New database name not specified")
        if service_db.exp_db_exist(new_dbname):
            raise werkzeug.exceptions.Conflict(
                description="Database %s already exists" % new_dbname)

        _logger.info("Duplicate database: %s -> %s", db, new_dbname)
        service_db.exp_duplicate_database(db, new_dbname)
        return Response('OK', status=200)
예제 #5
0
    def database_backup(self,
                        bu_type='manual',
                        backup_format='zip',
                        backup_name=False,
                        keep_till_date=False):
        """Returns a dictionary where:
        * keys = database name
        * value = dictionary with:
            * key error and error as value
            * key database and database name as value
        """
        self.ensure_one()

        now = datetime.now()
        error = False

        # check if bd exists
        try:
            if not db_ws.exp_db_exist(self.name):
                error = "Database %s do not exist" % (self.name)
                _logger.warning(error)
        except Exception as e:
            error = ("Could not check if database %s exists. "
                     "This is what we get:\n"
                     "%s" % (self.name, e))
            _logger.warning(error)
        else:
            # crear path para backups si no existe
            try:
                if not os.path.isdir(self.backups_path):
                    os.makedirs(self.backups_path)
            except Exception as e:
                error = ("Could not create folder %s for backups. "
                         "This is what we get:\n"
                         "%s" % (self.backups_path, e))
                _logger.warning(error)
            else:
                if not backup_name:
                    backup_name = '%s_%s_%s.%s' % (
                        self.name, bu_type, now.strftime('%Y%m%d_%H%M%S'),
                        backup_format)
                backup_path = os.path.join(self.backups_path, backup_name)
                if os.path.isfile(backup_path):
                    return {'error': "File %s already exists" % backup_path}
                backup = open(backup_path, 'wb')
                # backup
                try:
                    db_ws.dump_db(self.name,
                                  backup,
                                  backup_format=backup_format)
                except Exception as e:
                    error = ('Unable to dump self. '
                             'If you are working in an instance with '
                             '"workers" then you can try restarting service.\n'
                             'This is what we get: %s' % e)
                    _logger.warning(error)
                    backup.close()
                else:
                    backup.close()
                    backup_vals = {
                        'database_id': self.id,
                        'name': backup_name,
                        'path': self.backups_path,
                        'date': now,
                        'type': bu_type,
                        'keep_till_date': keep_till_date,
                    }
                    self.backup_ids.create(backup_vals)
                    _logger.info('Backup %s Created' % backup_name)

                    if bu_type == 'automatic':
                        _logger.info('Reconfiguring next backup')
                        new_date = self.relative_delta(datetime.now(),
                                                       self.backup_interval,
                                                       self.backup_rule_type)
                        self.backup_next_date = new_date

                    # TODO check gdrive backup pat
                    if self.syncked_backup_path:
                        # so no existe el path lo creamos
                        try:
                            if not os.path.isdir(self.syncked_backup_path):
                                _logger.info('Creating syncked backup folder')
                                os.makedirs(self.syncked_backup_path)
                        except Exception as e:
                            error = ("Could not create folder %s for backups. "
                                     "This is what we get:\n"
                                     "%s" % (self.syncked_backup_path, e))
                            _logger.warning(error)

                        # now we copy the backup
                        _logger.info('Make backup a copy con syncked path')
                        try:
                            syncked_backup = os.path.join(
                                self.syncked_backup_path,
                                self.name + '.%s' % backup_format)
                            shutil.copy2(backup_path, syncked_backup)
                        except Exception as e:
                            error = ("Could not copy into syncked folder. "
                                     "This is what we get:\n"
                                     "%s" % (e))
                            _logger.warning(error)
        if error:
            return {'error': error}
        else:
            return {'backup_name': backup_name}
예제 #6
0
 def _check_db_exist(self):
     """Checks if database exists"""
     if self.type != 'self' and not db_ws.exp_db_exist(self.not_self_name):
         raise ValidationError(
             _('Database %s do not exist') % (self.not_self_name))