Search in sources :

Example 1 with ModifyRequest

use of com.alibaba.nacos.config.server.service.sql.ModifyRequest in project nacos by alibaba.

the class StandaloneDatabaseOperateImpl method dataImport.

@Override
public CompletableFuture<RestResult<String>> dataImport(File file) {
    return CompletableFuture.supplyAsync(() -> {
        try (DiskUtils.LineIterator iterator = DiskUtils.lineIterator(file)) {
            int batchSize = 1000;
            List<String> batchUpdate = new ArrayList<>(batchSize);
            List<CompletableFuture<Void>> futures = new ArrayList<>();
            List<Boolean> results = new CopyOnWriteArrayList<>();
            while (iterator.hasNext()) {
                String sql = iterator.next();
                if (StringUtils.isNotBlank(sql)) {
                    batchUpdate.add(sql);
                }
                if (batchUpdate.size() == batchSize || !iterator.hasNext()) {
                    List<ModifyRequest> sqls = batchUpdate.stream().map(s -> {
                        ModifyRequest request = new ModifyRequest();
                        request.setSql(s);
                        return request;
                    }).collect(Collectors.toList());
                    futures.add(CompletableFuture.runAsync(() -> results.add(doDataImport(jdbcTemplate, sqls))));
                    batchUpdate.clear();
                }
            }
            CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
            int code = 500;
            if (!CollectionUtils.isEmpty(results)) {
                code = (!results.stream().anyMatch(Boolean.FALSE::equals)) ? 200 : 500;
            }
            return RestResult.<String>builder().withCode(code).withData("").build();
        } catch (Throwable ex) {
            LogUtil.DEFAULT_LOG.error("An exception occurred when external data was imported into Derby : ", ex);
            return RestResultUtils.failed(ex.getMessage());
        }
    });
}
Also used : RestResult(com.alibaba.nacos.common.model.RestResult) CollectionUtils(com.alibaba.nacos.common.utils.CollectionUtils) DynamicDataSource(com.alibaba.nacos.config.server.service.datasource.DynamicDataSource) LogUtil(com.alibaba.nacos.config.server.utils.LogUtil) CompletableFuture(java.util.concurrent.CompletableFuture) ConditionStandaloneEmbedStorage(com.alibaba.nacos.config.server.configuration.ConditionStandaloneEmbedStorage) Collectors(java.util.stream.Collectors) File(java.io.File) JdbcTemplate(org.springframework.jdbc.core.JdbcTemplate) ArrayList(java.util.ArrayList) DiskUtils(com.alibaba.nacos.sys.utils.DiskUtils) Component(org.springframework.stereotype.Component) List(java.util.List) StringUtils(com.alibaba.nacos.common.utils.StringUtils) RestResultUtils(com.alibaba.nacos.common.model.RestResultUtils) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) Map(java.util.Map) RowMapper(org.springframework.jdbc.core.RowMapper) PostConstruct(javax.annotation.PostConstruct) BiConsumer(java.util.function.BiConsumer) ModifyRequest(com.alibaba.nacos.config.server.service.sql.ModifyRequest) Conditional(org.springframework.context.annotation.Conditional) DataSourceService(com.alibaba.nacos.config.server.service.datasource.DataSourceService) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) DiskUtils(com.alibaba.nacos.sys.utils.DiskUtils) ArrayList(java.util.ArrayList) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ModifyRequest(com.alibaba.nacos.config.server.service.sql.ModifyRequest) CompletableFuture(java.util.concurrent.CompletableFuture) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList)

Example 2 with ModifyRequest

use of com.alibaba.nacos.config.server.service.sql.ModifyRequest in project nacos by alibaba.

the class DistributedDatabaseOperateImpl method update.

@Override
public Boolean update(List<ModifyRequest> sqlContext, BiConsumer<Boolean, Throwable> consumer) {
    try {
        // Since the SQL parameter is Object[], in order to ensure that the types of
        // array elements are not lost, the serialization here is done using the java-specific
        // serialization framework, rather than continuing with the protobuff
        LoggerUtils.printIfDebugEnabled(LogUtil.DEFAULT_LOG, "modifyRequests info : {}", sqlContext);
        // {timestamp}-{group}-{ip:port}-{signature}
        final String key = System.currentTimeMillis() + "-" + group() + "-" + memberManager.getSelf().getAddress() + "-" + MD5Utils.md5Hex(sqlContext.toString(), Constants.ENCODE);
        WriteRequest request = WriteRequest.newBuilder().setGroup(group()).setKey(key).setData(ByteString.copyFrom(serializer.serialize(sqlContext))).putAllExtendInfo(EmbeddedStorageContextUtils.getCurrentExtendInfo()).setType(sqlContext.getClass().getCanonicalName()).build();
        if (Objects.isNull(consumer)) {
            Response response = this.protocol.write(request);
            if (response.getSuccess()) {
                return true;
            }
            LogUtil.DEFAULT_LOG.error("execute sql modify operation failed : {}", response.getErrMsg());
            return false;
        } else {
            this.protocol.writeAsync(request).whenComplete((BiConsumer<Response, Throwable>) (response, ex) -> {
                String errMsg = Objects.isNull(ex) ? response.getErrMsg() : ExceptionUtil.getCause(ex).getMessage();
                consumer.accept(response.getSuccess(), StringUtils.isBlank(errMsg) ? null : new NJdbcException(errMsg));
            });
        }
        return true;
    } catch (TimeoutException e) {
        LogUtil.FATAL_LOG.error("An timeout exception occurred during the update operation");
        throw new NacosRuntimeException(NacosException.SERVER_ERROR, e.toString());
    } catch (Throwable e) {
        LogUtil.FATAL_LOG.error("An exception occurred during the update operation : {}", e);
        throw new NacosRuntimeException(NacosException.SERVER_ERROR, e.toString());
    }
}
Also used : Response(com.alibaba.nacos.consistency.entity.Response) NotifyCenter(com.alibaba.nacos.common.notify.NotifyCenter) LoggerUtils(com.alibaba.nacos.common.utils.LoggerUtils) Subscriber(com.alibaba.nacos.common.notify.listener.Subscriber) LocalDataSourceServiceImpl(com.alibaba.nacos.config.server.service.datasource.LocalDataSourceServiceImpl) RequestProcessor4CP(com.alibaba.nacos.consistency.cp.RequestProcessor4CP) ServerMemberManager(com.alibaba.nacos.core.cluster.ServerMemberManager) TimeoutException(java.util.concurrent.TimeoutException) ConditionDistributedEmbedStorage(com.alibaba.nacos.config.server.configuration.ConditionDistributedEmbedStorage) Constants(com.alibaba.nacos.config.server.constant.Constants) MD5Utils(com.alibaba.nacos.common.utils.MD5Utils) DataIntegrityViolationException(org.springframework.dao.DataIntegrityViolationException) Map(java.util.Map) ProtocolManager(com.alibaba.nacos.core.distributed.ProtocolManager) JacksonUtils(com.alibaba.nacos.common.utils.JacksonUtils) RestResult(com.alibaba.nacos.common.model.RestResult) RaftDbErrorEvent(com.alibaba.nacos.config.server.model.event.RaftDbErrorEvent) SerializeFactory(com.alibaba.nacos.consistency.SerializeFactory) DynamicDataSource(com.alibaba.nacos.config.server.service.datasource.DynamicDataSource) ConfigExecutor(com.alibaba.nacos.config.server.utils.ConfigExecutor) GenericType(com.alibaba.nacos.core.utils.GenericType) Collectors(java.util.stream.Collectors) ByteString(com.google.protobuf.ByteString) Objects(java.util.Objects) DiskUtils(com.alibaba.nacos.sys.utils.DiskUtils) List(java.util.List) Event(com.alibaba.nacos.common.notify.Event) StringUtils(com.alibaba.nacos.common.utils.StringUtils) RestResultUtils(com.alibaba.nacos.common.model.RestResultUtils) ConsistencyException(com.alibaba.nacos.consistency.exception.ConsistencyException) RowMapper(org.springframework.jdbc.core.RowMapper) Conditional(org.springframework.context.annotation.Conditional) DataAccessException(org.springframework.dao.DataAccessException) SnapshotOperation(com.alibaba.nacos.consistency.snapshot.SnapshotOperation) DerbyLoadEvent(com.alibaba.nacos.config.server.model.event.DerbyLoadEvent) LogUtil(com.alibaba.nacos.config.server.utils.LogUtil) CompletableFuture(java.util.concurrent.CompletableFuture) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) JustForTest(com.alibaba.nacos.common.JustForTest) JdbcTemplate(org.springframework.jdbc.core.JdbcTemplate) ArrayList(java.util.ArrayList) NJdbcException(com.alibaba.nacos.config.server.exception.NJdbcException) NacosException(com.alibaba.nacos.api.exception.NacosException) EmbeddedStorageContextUtils(com.alibaba.nacos.config.server.service.sql.EmbeddedStorageContextUtils) BiConsumer(java.util.function.BiConsumer) Preconditions(com.alibaba.nacos.common.utils.Preconditions) ReadRequest(com.alibaba.nacos.consistency.entity.ReadRequest) NacosRuntimeException(com.alibaba.nacos.api.exception.runtime.NacosRuntimeException) QueryType(com.alibaba.nacos.config.server.service.sql.QueryType) ConfigDumpEvent(com.alibaba.nacos.config.server.model.event.ConfigDumpEvent) ExceptionUtil(com.alibaba.nacos.common.utils.ExceptionUtil) DumpConfigHandler(com.alibaba.nacos.config.server.service.dump.DumpConfigHandler) Serializer(com.alibaba.nacos.consistency.Serializer) SelectRequest(com.alibaba.nacos.config.server.service.sql.SelectRequest) BadSqlGrammarException(org.springframework.jdbc.BadSqlGrammarException) File(java.io.File) WriteRequest(com.alibaba.nacos.consistency.entity.WriteRequest) Response(com.alibaba.nacos.consistency.entity.Response) Component(org.springframework.stereotype.Component) Lock(java.util.concurrent.locks.Lock) TransactionTemplate(org.springframework.transaction.support.TransactionTemplate) ModifyRequest(com.alibaba.nacos.config.server.service.sql.ModifyRequest) RowMapperManager(com.alibaba.nacos.config.server.service.repository.RowMapperManager) CPProtocol(com.alibaba.nacos.consistency.cp.CPProtocol) Comparator(java.util.Comparator) ClassUtils(com.alibaba.nacos.core.utils.ClassUtils) Collections(java.util.Collections) WriteRequest(com.alibaba.nacos.consistency.entity.WriteRequest) ByteString(com.google.protobuf.ByteString) NJdbcException(com.alibaba.nacos.config.server.exception.NJdbcException) NacosRuntimeException(com.alibaba.nacos.api.exception.runtime.NacosRuntimeException) TimeoutException(java.util.concurrent.TimeoutException)

Example 3 with ModifyRequest

use of com.alibaba.nacos.config.server.service.sql.ModifyRequest in project nacos by alibaba.

the class DistributedDatabaseOperateImpl method dataImport.

@Override
public CompletableFuture<RestResult<String>> dataImport(File file) {
    return CompletableFuture.supplyAsync(() -> {
        try (DiskUtils.LineIterator iterator = DiskUtils.lineIterator(file)) {
            int batchSize = 1000;
            List<String> batchUpdate = new ArrayList<>(batchSize);
            List<CompletableFuture<Response>> futures = new ArrayList<>();
            while (iterator.hasNext()) {
                String sql = iterator.next();
                if (StringUtils.isNotBlank(sql)) {
                    batchUpdate.add(sql);
                }
                boolean submit = batchUpdate.size() == batchSize || !iterator.hasNext();
                if (submit) {
                    List<ModifyRequest> requests = batchUpdate.stream().map(ModifyRequest::new).collect(Collectors.toList());
                    CompletableFuture<Response> future = protocol.writeAsync(WriteRequest.newBuilder().setGroup(group()).setData(ByteString.copyFrom(serializer.serialize(requests))).putExtendInfo(DATA_IMPORT_KEY, Boolean.TRUE.toString()).build());
                    futures.add(future);
                    batchUpdate.clear();
                }
            }
            CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
            for (CompletableFuture<Response> future : futures) {
                Response response = future.get();
                if (!response.getSuccess()) {
                    return RestResultUtils.failed(response.getErrMsg());
                }
            }
            return RestResultUtils.success();
        } catch (Throwable ex) {
            LogUtil.DEFAULT_LOG.error("data import has error :", ex);
            return RestResultUtils.failed(ex.getMessage());
        }
    });
}
Also used : DiskUtils(com.alibaba.nacos.sys.utils.DiskUtils) ArrayList(java.util.ArrayList) ByteString(com.google.protobuf.ByteString) ModifyRequest(com.alibaba.nacos.config.server.service.sql.ModifyRequest) Response(com.alibaba.nacos.consistency.entity.Response) CompletableFuture(java.util.concurrent.CompletableFuture)

Example 4 with ModifyRequest

use of com.alibaba.nacos.config.server.service.sql.ModifyRequest in project nacos by alibaba.

the class DistributedDatabaseOperateImpl method onApply.

@Override
public Response onApply(WriteRequest log) {
    LoggerUtils.printIfDebugEnabled(LogUtil.DEFAULT_LOG, "onApply info : log : {}", log);
    final ByteString byteString = log.getData();
    Preconditions.checkArgument(byteString != null, "Log.getData() must not null");
    List<ModifyRequest> sqlContext = serializer.deserialize(byteString.toByteArray(), List.class);
    final Lock lock = readLock;
    lock.lock();
    try {
        boolean isOk = false;
        if (log.containsExtendInfo(DATA_IMPORT_KEY)) {
            isOk = doDataImport(jdbcTemplate, sqlContext);
        } else {
            sqlContext.sort(Comparator.comparingInt(ModifyRequest::getExecuteNo));
            isOk = update(transactionTemplate, jdbcTemplate, sqlContext);
            // If there is additional information, post processing
            // Put into the asynchronous thread pool for processing to avoid blocking the
            // normal execution of the state machine
            ConfigExecutor.executeEmbeddedDump(() -> handleExtendInfo(log.getExtendInfoMap()));
        }
        return Response.newBuilder().setSuccess(isOk).build();
    // We do not believe that an error caused by a problem with an SQL error
    // should trigger the stop operation of the raft state machine
    } catch (BadSqlGrammarException | DataIntegrityViolationException e) {
        return Response.newBuilder().setSuccess(false).setErrMsg(e.toString()).build();
    } catch (DataAccessException e) {
        throw new ConsistencyException(e.toString());
    } finally {
        lock.unlock();
    }
}
Also used : BadSqlGrammarException(org.springframework.jdbc.BadSqlGrammarException) ByteString(com.google.protobuf.ByteString) ConsistencyException(com.alibaba.nacos.consistency.exception.ConsistencyException) ModifyRequest(com.alibaba.nacos.config.server.service.sql.ModifyRequest) DataAccessException(org.springframework.dao.DataAccessException) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) Lock(java.util.concurrent.locks.Lock) DataIntegrityViolationException(org.springframework.dao.DataIntegrityViolationException)

Example 5 with ModifyRequest

use of com.alibaba.nacos.config.server.service.sql.ModifyRequest in project nacos by alibaba.

the class EmbeddedStorageContextUtils_CITCase method test_multi_thread_sql_contexts.

@Test
public void test_multi_thread_sql_contexts() throws Exception {
    CountDownLatch latch = new CountDownLatch(3);
    ExecutorService service = Executors.newFixedThreadPool(3);
    for (int i = 1; i < 4; i++) {
        final int j = i;
        service.submit(() -> {
            try {
                EmbeddedStorageContextUtils.addSqlContext("test_" + j, j);
                EmbeddedStorageContextUtils.addSqlContext("test_" + j * 10, j);
                List<ModifyRequest> list = EmbeddedStorageContextUtils.getCurrentSqlContext();
                System.out.println(list);
                Assert.assertEquals("test_" + j, list.get(0).getSql());
                Assert.assertEquals("test_" + j * 10, list.get(0).getSql());
            } finally {
                latch.countDown();
            }
        });
    }
    latch.await();
}
Also used : ExecutorService(java.util.concurrent.ExecutorService) ModifyRequest(com.alibaba.nacos.config.server.service.sql.ModifyRequest) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test)

Aggregations

ModifyRequest (com.alibaba.nacos.config.server.service.sql.ModifyRequest)5 DiskUtils (com.alibaba.nacos.sys.utils.DiskUtils)3 ByteString (com.google.protobuf.ByteString)3 ArrayList (java.util.ArrayList)3 CompletableFuture (java.util.concurrent.CompletableFuture)3 RestResult (com.alibaba.nacos.common.model.RestResult)2 RestResultUtils (com.alibaba.nacos.common.model.RestResultUtils)2 StringUtils (com.alibaba.nacos.common.utils.StringUtils)2 DynamicDataSource (com.alibaba.nacos.config.server.service.datasource.DynamicDataSource)2 LogUtil (com.alibaba.nacos.config.server.utils.LogUtil)2 Response (com.alibaba.nacos.consistency.entity.Response)2 File (java.io.File)2 List (java.util.List)2 Map (java.util.Map)2 BiConsumer (java.util.function.BiConsumer)2 Collectors (java.util.stream.Collectors)2 Conditional (org.springframework.context.annotation.Conditional)2 JdbcTemplate (org.springframework.jdbc.core.JdbcTemplate)2 RowMapper (org.springframework.jdbc.core.RowMapper)2 Component (org.springframework.stereotype.Component)2