Search in sources :

Example 1 with RestResult

use of com.alibaba.nacos.common.model.RestResult in project nacos by alibaba.

the class NacosClusterController method leave.

/**
 * member leave.
 *
 * @param params member ip list, example [ip1:port1,ip2:port2,...]
 * @return {@link RestResult}
 * @throws Exception {@link Exception}
 */
@PostMapping("/server/leave")
public RestResult<String> leave(@RequestBody Collection<String> params) throws Exception {
    Collection<Member> memberList = MemberUtil.multiParse(params);
    memberManager.memberLeave(memberList);
    final NacosAsyncRestTemplate nacosAsyncRestTemplate = HttpClientBeanHolder.getNacosAsyncRestTemplate(Loggers.CLUSTER);
    final GenericType<RestResult<String>> genericType = new GenericType<RestResult<String>>() {
    };
    final Collection<Member> notifyList = memberManager.allMembersWithoutSelf();
    notifyList.removeAll(memberList);
    CountDownLatch latch = new CountDownLatch(notifyList.size());
    for (Member member : notifyList) {
        final String url = HttpUtils.buildUrl(false, member.getAddress(), EnvUtil.getContextPath(), Commons.NACOS_CORE_CONTEXT, "/cluster/server/leave");
        nacosAsyncRestTemplate.post(url, Header.EMPTY, Query.EMPTY, params, genericType.getType(), new Callback<String>() {

            @Override
            public void onReceive(RestResult<String> result) {
                try {
                    if (result.ok()) {
                        LoggerUtils.printIfDebugEnabled(Loggers.CLUSTER, "The node : [{}] success to process the request", member);
                        MemberUtil.onSuccess(memberManager, member);
                    } else {
                        Loggers.CLUSTER.warn("The node : [{}] failed to process the request, response is : {}", member, result);
                        MemberUtil.onFail(memberManager, member);
                    }
                } finally {
                    latch.countDown();
                }
            }

            @Override
            public void onError(Throwable throwable) {
                try {
                    Loggers.CLUSTER.error("Failed to communicate with the node : {}", member);
                    MemberUtil.onFail(memberManager, member);
                } finally {
                    latch.countDown();
                }
            }

            @Override
            public void onCancel() {
            }
        });
    }
    try {
        latch.await(10_000, TimeUnit.MILLISECONDS);
        return RestResultUtils.success("ok");
    } catch (Throwable ex) {
        return RestResultUtils.failed(ex.getMessage());
    }
}
Also used : GenericType(com.alibaba.nacos.core.utils.GenericType) RestResult(com.alibaba.nacos.common.model.RestResult) NacosAsyncRestTemplate(com.alibaba.nacos.common.http.client.NacosAsyncRestTemplate) CountDownLatch(java.util.concurrent.CountDownLatch) Member(com.alibaba.nacos.core.cluster.Member) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Example 2 with RestResult

use of com.alibaba.nacos.common.model.RestResult 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 3 with RestResult

use of com.alibaba.nacos.common.model.RestResult in project nacos by alibaba.

the class NacosClusterController method leave.

/**
 * member leave.
 *
 * @param params member ip list, example [ip1:port1,ip2:port2,...]
 * @return {@link RestResult}
 * @throws Exception {@link Exception}
 */
@PostMapping("/server/leave")
public RestResult<String> leave(@RequestBody Collection<String> params, @RequestParam(defaultValue = "true") Boolean notifyOtherMembers) throws Exception {
    Collection<Member> memberList = MemberUtil.multiParse(params);
    memberManager.memberLeave(memberList);
    // End conditions for cluster notifications, FIX https://github.com/alibaba/nacos/issues/6273
    if (Boolean.FALSE.equals(notifyOtherMembers)) {
        return RestResultUtils.success("ok");
    }
    final NacosAsyncRestTemplate nacosAsyncRestTemplate = HttpClientBeanHolder.getNacosAsyncRestTemplate(Loggers.CLUSTER);
    final GenericType<RestResult<String>> genericType = new GenericType<RestResult<String>>() {
    };
    final Collection<Member> notifyList = memberManager.allMembersWithoutSelf();
    notifyList.removeAll(memberList);
    CountDownLatch latch = new CountDownLatch(notifyList.size());
    for (Member member : notifyList) {
        final String url = HttpUtils.buildUrl(false, member.getAddress(), EnvUtil.getContextPath(), Commons.NACOS_CORE_CONTEXT, "/cluster/server/leave?notifyOtherMembers=false");
        nacosAsyncRestTemplate.post(url, Header.EMPTY, Query.EMPTY, params, genericType.getType(), new Callback<String>() {

            @Override
            public void onReceive(RestResult<String> result) {
                try {
                    if (result.ok()) {
                        LoggerUtils.printIfDebugEnabled(Loggers.CLUSTER, "The node : [{}] success to process the request", member);
                        MemberUtil.onSuccess(memberManager, member);
                    } else {
                        Loggers.CLUSTER.warn("The node : [{}] failed to process the request, response is : {}", member, result);
                        MemberUtil.onFail(memberManager, member);
                    }
                } finally {
                    latch.countDown();
                }
            }

            @Override
            public void onError(Throwable throwable) {
                try {
                    Loggers.CLUSTER.error("Failed to communicate with the node : {}", member);
                    MemberUtil.onFail(memberManager, member);
                } finally {
                    latch.countDown();
                }
            }

            @Override
            public void onCancel() {
            }
        });
    }
    try {
        latch.await(10_000, TimeUnit.MILLISECONDS);
        return RestResultUtils.success("ok");
    } catch (Throwable ex) {
        return RestResultUtils.failed(ex.getMessage());
    }
}
Also used : GenericType(com.alibaba.nacos.core.utils.GenericType) RestResult(com.alibaba.nacos.common.model.RestResult) NacosAsyncRestTemplate(com.alibaba.nacos.common.http.client.NacosAsyncRestTemplate) CountDownLatch(java.util.concurrent.CountDownLatch) Member(com.alibaba.nacos.core.cluster.Member) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Example 4 with RestResult

use of com.alibaba.nacos.common.model.RestResult in project nacos by alibaba.

the class NacosClusterV2Controller method deleteNodes.

/**
 * member leave.
 *
 * @param addresses member ip list, example [ip1:port1,ip2:port2,...]
 * @return {@link RestResult}
 * @throws Exception throw {@link Exception}
 */
@DeleteMapping("/nodes")
public RestResult<Void> deleteNodes(@RequestParam("addresses") List<String> addresses) throws Exception {
    Collection<Member> memberList = MemberUtil.multiParse(addresses);
    memberManager.memberLeave(memberList);
    final NacosAsyncRestTemplate nacosAsyncRestTemplate = HttpClientBeanHolder.getNacosAsyncRestTemplate(Loggers.CLUSTER);
    final GenericType<RestResult<String>> genericType = new GenericType<RestResult<String>>() {
    };
    final Collection<Member> notifyList = memberManager.allMembersWithoutSelf();
    notifyList.removeAll(memberList);
    CountDownLatch latch = new CountDownLatch(notifyList.size());
    for (Member member : notifyList) {
        final String url = HttpUtils.buildUrl(false, member.getAddress(), EnvUtil.getContextPath(), Commons.NACOS_CORE_CONTEXT_V2, "/cluster/nodes");
        nacosAsyncRestTemplate.delete(url, Header.EMPTY, StringUtils.join(addresses, ","), genericType.getType(), new Callback<Void>() {

            @Override
            public void onReceive(RestResult<Void> result) {
                try {
                    if (result.ok()) {
                        LoggerUtils.printIfDebugEnabled(Loggers.CLUSTER, "The node : [{}] success to process the request", member);
                        MemberUtil.onSuccess(memberManager, member);
                    } else {
                        Loggers.CLUSTER.warn("The node : [{}] failed to process the request, response is : {}", member, result);
                        MemberUtil.onFail(memberManager, member);
                    }
                } finally {
                    latch.countDown();
                }
            }

            @Override
            public void onError(Throwable throwable) {
                try {
                    Loggers.CLUSTER.error("Failed to communicate with the node : {}", member);
                    MemberUtil.onFail(memberManager, member);
                } finally {
                    latch.countDown();
                }
            }

            @Override
            public void onCancel() {
            }
        });
    }
    try {
        latch.await(10_000, TimeUnit.MILLISECONDS);
        return RestResultUtils.success();
    } catch (Throwable ex) {
        return RestResultUtils.failed(ex.getMessage());
    }
}
Also used : GenericType(com.alibaba.nacos.core.utils.GenericType) RestResult(com.alibaba.nacos.common.model.RestResult) NacosAsyncRestTemplate(com.alibaba.nacos.common.http.client.NacosAsyncRestTemplate) CountDownLatch(java.util.concurrent.CountDownLatch) Member(com.alibaba.nacos.core.cluster.Member) DeleteMapping(org.springframework.web.bind.annotation.DeleteMapping)

Example 5 with RestResult

use of com.alibaba.nacos.common.model.RestResult in project nacos by alibaba.

the class ConfigController method cloneConfig.

/**
 * Execute clone config operation.
 *
 * @param request         http servlet request .
 * @param srcUser         src user string value.
 * @param namespace       namespace string value.
 * @param configBeansList config beans list.
 * @param policy          config policy model.
 * @return RestResult for map.
 * @throws NacosException NacosException.
 */
@PostMapping(params = "clone=true")
@Secured(action = ActionTypes.WRITE, signType = SignType.CONFIG)
public RestResult<Map<String, Object>> cloneConfig(HttpServletRequest request, @RequestParam(value = "src_user", required = false) String srcUser, @RequestParam(value = "tenant") String namespace, @RequestBody List<SameNamespaceCloneConfigBean> configBeansList, @RequestParam(value = "policy", defaultValue = "ABORT") SameConfigPolicy policy) throws NacosException {
    Map<String, Object> failedData = new HashMap<>(4);
    if (CollectionUtils.isEmpty(configBeansList)) {
        failedData.put("succCount", 0);
        return RestResultUtils.buildResult(ResultCodeEnum.NO_SELECTED_CONFIG, failedData);
    }
    configBeansList.removeAll(Collections.singleton(null));
    namespace = NamespaceUtil.processNamespaceParameter(namespace);
    if (StringUtils.isNotBlank(namespace) && persistService.tenantInfoCountByTenantId(namespace) <= 0) {
        failedData.put("succCount", 0);
        return RestResultUtils.buildResult(ResultCodeEnum.NAMESPACE_NOT_EXIST, failedData);
    }
    List<Long> idList = new ArrayList<>(configBeansList.size());
    Map<Long, SameNamespaceCloneConfigBean> configBeansMap = configBeansList.stream().collect(Collectors.toMap(SameNamespaceCloneConfigBean::getCfgId, cfg -> {
        idList.add(cfg.getCfgId());
        return cfg;
    }, (k1, k2) -> k1));
    List<ConfigAllInfo> queryedDataList = persistService.findAllConfigInfo4Export(null, null, null, null, idList);
    if (queryedDataList == null || queryedDataList.isEmpty()) {
        failedData.put("succCount", 0);
        return RestResultUtils.buildResult(ResultCodeEnum.DATA_EMPTY, failedData);
    }
    List<ConfigAllInfo> configInfoList4Clone = new ArrayList<>(queryedDataList.size());
    for (ConfigAllInfo ci : queryedDataList) {
        SameNamespaceCloneConfigBean paramBean = configBeansMap.get(ci.getId());
        ConfigAllInfo ci4save = new ConfigAllInfo();
        ci4save.setTenant(namespace);
        ci4save.setType(ci.getType());
        ci4save.setGroup((paramBean != null && StringUtils.isNotBlank(paramBean.getGroup())) ? paramBean.getGroup() : ci.getGroup());
        ci4save.setDataId((paramBean != null && StringUtils.isNotBlank(paramBean.getDataId())) ? paramBean.getDataId() : ci.getDataId());
        ci4save.setContent(ci.getContent());
        if (StringUtils.isNotBlank(ci.getAppName())) {
            ci4save.setAppName(ci.getAppName());
        }
        ci4save.setDesc(ci.getDesc());
        ci4save.setEncryptedDataKey(ci.getEncryptedDataKey() == null ? StringUtils.EMPTY : ci.getEncryptedDataKey());
        configInfoList4Clone.add(ci4save);
    }
    final String srcIp = RequestUtil.getRemoteIp(request);
    String requestIpApp = RequestUtil.getAppName(request);
    final Timestamp time = TimeUtils.getCurrentTime();
    Map<String, Object> saveResult = persistService.batchInsertOrUpdate(configInfoList4Clone, srcUser, srcIp, null, time, false, policy);
    for (ConfigInfo configInfo : configInfoList4Clone) {
        ConfigChangePublisher.notifyConfigChange(new ConfigDataChangeEvent(false, configInfo.getDataId(), configInfo.getGroup(), configInfo.getTenant(), time.getTime()));
        ConfigTraceService.logPersistenceEvent(configInfo.getDataId(), configInfo.getGroup(), configInfo.getTenant(), requestIpApp, time.getTime(), InetUtils.getSelfIP(), ConfigTraceService.PERSISTENCE_EVENT_PUB, configInfo.getContent());
    }
    return RestResultUtils.success("Clone Completed Successfully", saveResult);
}
Also used : SameNamespaceCloneConfigBean(com.alibaba.nacos.config.server.controller.parameters.SameNamespaceCloneConfigBean) ConfigType(com.alibaba.nacos.api.config.ConfigType) ConfigMetadata(com.alibaba.nacos.config.server.model.ConfigMetadata) RequestParam(org.springframework.web.bind.annotation.RequestParam) URLDecoder(java.net.URLDecoder) Pair(com.alibaba.nacos.common.utils.Pair) ServletException(javax.servlet.ServletException) Date(java.util.Date) LoggerFactory(org.slf4j.LoggerFactory) Constants(com.alibaba.nacos.config.server.constant.Constants) MapUtil(com.alibaba.nacos.common.utils.MapUtil) ResultCodeEnum(com.alibaba.nacos.config.server.result.code.ResultCodeEnum) Map(java.util.Map) GroupkeyListenserStatus(com.alibaba.nacos.config.server.model.GroupkeyListenserStatus) YamlParserUtil(com.alibaba.nacos.config.server.utils.YamlParserUtil) SameNamespaceCloneConfigBean(com.alibaba.nacos.config.server.controller.parameters.SameNamespaceCloneConfigBean) DeleteMapping(org.springframework.web.bind.annotation.DeleteMapping) RestResult(com.alibaba.nacos.common.model.RestResult) PostMapping(org.springframework.web.bind.annotation.PostMapping) TimeUtils(com.alibaba.nacos.config.server.utils.TimeUtils) HttpHeaders(org.springframework.http.HttpHeaders) Timestamp(java.sql.Timestamp) InetUtils(com.alibaba.nacos.sys.utils.InetUtils) Set(java.util.Set) RestController(org.springframework.web.bind.annotation.RestController) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) List(java.util.List) StringUtils(com.alibaba.nacos.common.utils.StringUtils) ConfigInfo(com.alibaba.nacos.config.server.model.ConfigInfo) CollectionUtils(org.springframework.util.CollectionUtils) RestResultUtils(com.alibaba.nacos.common.model.RestResultUtils) ActionTypes(com.alibaba.nacos.plugin.auth.constant.ActionTypes) Secured(com.alibaba.nacos.auth.annotation.Secured) DateFormatUtils(com.alibaba.nacos.common.utils.DateFormatUtils) ConfigDataChangeEvent(com.alibaba.nacos.config.server.model.event.ConfigDataChangeEvent) ConfigTraceService(com.alibaba.nacos.config.server.service.trace.ConfigTraceService) SignType(com.alibaba.nacos.plugin.auth.constant.SignType) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) HashMap(java.util.HashMap) NamespaceUtil(com.alibaba.nacos.common.utils.NamespaceUtil) RequestUtil(com.alibaba.nacos.config.server.utils.RequestUtil) ConfigAllInfo(com.alibaba.nacos.config.server.model.ConfigAllInfo) PersistService(com.alibaba.nacos.config.server.service.repository.PersistService) ArrayList(java.util.ArrayList) RequestBody(org.springframework.web.bind.annotation.RequestBody) HttpServletRequest(javax.servlet.http.HttpServletRequest) ZipUtils(com.alibaba.nacos.config.server.utils.ZipUtils) ConfigInfo4Beta(com.alibaba.nacos.config.server.model.ConfigInfo4Beta) EncryptionHandler(com.alibaba.nacos.plugin.encryption.handler.EncryptionHandler) NacosException(com.alibaba.nacos.api.exception.NacosException) ConfigAdvanceInfo(com.alibaba.nacos.config.server.model.ConfigAdvanceInfo) GetMapping(org.springframework.web.bind.annotation.GetMapping) Page(com.alibaba.nacos.config.server.model.Page) SameConfigPolicy(com.alibaba.nacos.config.server.model.SameConfigPolicy) ParamUtils(com.alibaba.nacos.config.server.utils.ParamUtils) Logger(org.slf4j.Logger) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) GroupKey(com.alibaba.nacos.config.server.utils.GroupKey) ConfigSubService(com.alibaba.nacos.config.server.service.ConfigSubService) HttpStatus(org.springframework.http.HttpStatus) AggrWhitelist(com.alibaba.nacos.config.server.service.AggrWhitelist) MD5Util(com.alibaba.nacos.config.server.utils.MD5Util) ConfigChangePublisher(com.alibaba.nacos.config.server.service.ConfigChangePublisher) SampleResult(com.alibaba.nacos.config.server.model.SampleResult) MultipartFile(org.springframework.web.multipart.MultipartFile) ResponseEntity(org.springframework.http.ResponseEntity) Collections(java.util.Collections) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ConfigInfo(com.alibaba.nacos.config.server.model.ConfigInfo) Timestamp(java.sql.Timestamp) ConfigAllInfo(com.alibaba.nacos.config.server.model.ConfigAllInfo) ConfigDataChangeEvent(com.alibaba.nacos.config.server.model.event.ConfigDataChangeEvent) PostMapping(org.springframework.web.bind.annotation.PostMapping) Secured(com.alibaba.nacos.auth.annotation.Secured)

Aggregations

RestResult (com.alibaba.nacos.common.model.RestResult)10 PostMapping (org.springframework.web.bind.annotation.PostMapping)5 Map (java.util.Map)4 Secured (com.alibaba.nacos.auth.annotation.Secured)3 NacosAsyncRestTemplate (com.alibaba.nacos.common.http.client.NacosAsyncRestTemplate)3 RestResultUtils (com.alibaba.nacos.common.model.RestResultUtils)3 StringUtils (com.alibaba.nacos.common.utils.StringUtils)3 ConfigInfo (com.alibaba.nacos.config.server.model.ConfigInfo)3 PersistService (com.alibaba.nacos.config.server.service.repository.PersistService)3 Member (com.alibaba.nacos.core.cluster.Member)3 GenericType (com.alibaba.nacos.core.utils.GenericType)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3 CountDownLatch (java.util.concurrent.CountDownLatch)3 Collectors (java.util.stream.Collectors)3 DeleteMapping (org.springframework.web.bind.annotation.DeleteMapping)3 ConfigType (com.alibaba.nacos.api.config.ConfigType)2 NacosException (com.alibaba.nacos.api.exception.NacosException)2 DateFormatUtils (com.alibaba.nacos.common.utils.DateFormatUtils)2 MapUtil (com.alibaba.nacos.common.utils.MapUtil)2