Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ISSUE#12979] Develop a maintainer sdk. #13064

Merged
merged 9 commits into from
Feb 5, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ public interface HttpHeaderConsts {
String USER_AGENT_HEADER = "User-Agent";
String REQUEST_SOURCE_HEADER = "Request-Source";
String CONTENT_TYPE = "Content-Type";
String CONTENT_DISPOSITION = "Content-Disposition";
String CONTENT_LENGTH = "Content-Length";
String ACCEPT_CHARSET = "Accept-Charset";
String ACCEPT_ENCODING = "Accept-Encoding";
Expand All @@ -36,5 +37,4 @@ public interface HttpHeaderConsts {
String REQUEST_MODULE = "Request-Module";
String APP_FILED = "app";
String CLIENT_IP = "clientIp";

}
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import com.alibaba.nacos.common.utils.HttpMethod;
import org.slf4j.Logger;

import java.io.File;
import java.lang.reflect.Type;
import java.net.URI;
import java.util.ArrayList;
Expand Down Expand Up @@ -407,6 +408,12 @@ public <T> HttpRestResult<T> postForm(String url, HttpClientConfig config, Heade
return execute(url, HttpMethod.POST, requestHttpEntity, responseType);
}

public <T> HttpRestResult<T> postFile(String url, HttpClientConfig config, Header header,
File file, Type responseType) throws Exception {
RequestHttpEntity requestHttpEntity = new RequestHttpEntity(config, header, file);
return execute(url, HttpMethod.POST, requestHttpEntity, responseType);
}

/**
* Execute the HTTP method to the given URI template, writing the given request entity to the request, and returns
* the response as {@link HttpRestResult}.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,12 @@
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Map;

Expand All @@ -46,6 +48,10 @@ public class JdkHttpClientRequest implements HttpClientRequest {

private static final String CONTENT_LENGTH = "Content-Length";

private static final String BOUNDARY_PREFIX = "----WebKitFormBoundary";

private static final String LINE_FEED = "\r\n";

private HttpClientConfig httpClientConfig;

public JdkHttpClientRequest(HttpClientConfig httpClientConfig) {
Expand Down Expand Up @@ -95,6 +101,9 @@ public HttpClientResponse execute(URI uri, String httpMethod, RequestHttpEntity
conn.setReadTimeout(this.httpClientConfig.getReadTimeOutMillis());
conn.setRequestMethod(httpMethod);
if (body != null && !"".equals(body)) {
if (body instanceof File) {
handleFileUpload(conn, (File) body);
}
String contentType = headers.getValue(HttpHeaderConsts.CONTENT_TYPE);
String bodyStr = body instanceof String ? (String) body : JacksonUtils.toJson(body);
if (MediaType.APPLICATION_FORM_URLENCODED.equals(contentType)) {
Expand All @@ -115,6 +124,28 @@ public HttpClientResponse execute(URI uri, String httpMethod, RequestHttpEntity
return new JdkHttpClientResponse(conn);
}

private void handleFileUpload(HttpURLConnection conn, File file) throws IOException {
String boundary = BOUNDARY_PREFIX + System.currentTimeMillis();
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

StringBuilder sb = new StringBuilder();
sb.append("--").append(boundary).append(LINE_FEED);
sb.append("Content-Disposition: form-data; name=\"file\"; filename=\"").append(file.getName()).append("\"")
.append(LINE_FEED);
sb.append("Content-Type: ").append(Files.probeContentType(file.toPath())).append(LINE_FEED).append(LINE_FEED);

byte[] fileBytes = Files.readAllBytes(file.toPath());
byte[] boundaryBytes = (LINE_FEED + "--" + boundary + "--" + LINE_FEED).getBytes();

conn.setDoOutput(true);
try (OutputStream outputStream = conn.getOutputStream()) {
outputStream.write(sb.toString().getBytes());
outputStream.write(fileBytes);
outputStream.write(boundaryBytes);
outputStream.flush();
}
}

/**
* Replace the HTTP config created by default with the HTTP config specified in the request.
*
Expand Down
70 changes: 70 additions & 0 deletions maintainer-client/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-all</artifactId>
<version>${revision}</version>
</parent>

<artifactId>nacos-maintainer-client</artifactId>
<name>nacos-maintainer-client ${project.version}</name>
<url>https://nacos.io</url>
<packaging>jar</packaging>

<dependencies>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-common</artifactId>
<exclusions>
<exclusion>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty-shaded</artifactId>
</exclusion>
<exclusion>
<groupId>io.grpc</groupId>
<artifactId>grpc-protobuf</artifactId>
</exclusion>
<exclusion>
<groupId>io.grpc</groupId>
<artifactId>grpc-stub</artifactId>
</exclusion>
<exclusion>
<groupId>io.grpc</groupId>
<artifactId>grpc-util</artifactId>
</exclusion>
<exclusion>
<groupId>io.grpc</groupId>
<artifactId>grpc-inprocess</artifactId>
</exclusion>
<exclusion>
<groupId>com.google.api.grpc</groupId>
<artifactId>proto-google-common-protos</artifactId>
</exclusion>
<exclusion>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/*
* Copyright 1999-$toady.year Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.alibaba.nacos.maintainer.client;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.maintainer.client.config.ConfigMaintainerFactory;
import com.alibaba.nacos.maintainer.client.config.ConfigMaintainerService;

import java.util.Properties;

/**
* Nacos maintainer service.
*
* @author Nacos
*/
public class NacosMaintainerFactory {

public static ConfigMaintainerService createConfigMaintainerService(String serverList)
throws NacosException, NacosException {
return ConfigMaintainerFactory.createConfigMaintainerService(serverList);
}

public static ConfigMaintainerService createConfigMaintainerService(Properties properties) throws NacosException {
return ConfigMaintainerFactory.createConfigMaintainerService(properties);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
/*
* Copyright 1999-2024 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.alibaba.nacos.maintainer.client.address;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.common.JustForTest;
import com.alibaba.nacos.common.http.client.NacosRestTemplate;
import com.alibaba.nacos.common.lifecycle.Closeable;
import com.alibaba.nacos.common.spi.NacosServiceLoader;
import com.alibaba.nacos.maintainer.client.env.NacosClientProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;
import java.util.List;

/**
* Server list Manager.
*
* @author Nacos
*/
public abstract class AbstractServerListManager implements ServerListManager, Closeable {

private static final Logger LOGGER = LoggerFactory.getLogger(AbstractServerListManager.class);

protected ServerListProvider serverListProvider;

protected NacosClientProperties properties;

public AbstractServerListManager(NacosClientProperties properties) {
this.properties = properties;
}

@Override
public List<String> getServerList() {
return serverListProvider.getServerList();
}

@Override
public void shutdown() throws NacosException {
String className = this.getClass().getName();
LOGGER.info("{} do shutdown begin", className);
if (null != serverListProvider) {
serverListProvider.shutdown();
}
serverListProvider = null;
LOGGER.info("{} do shutdown stop", className);
}

/**
* Start server list manager.
*
* @throws NacosException during start and initialize.
*/
public void start() throws NacosException {
Collection<ServerListProvider> serverListProviders = NacosServiceLoader.load(ServerListProvider.class);
Collection<ServerListProvider> sorted = serverListProviders.stream()
.sorted((a, b) -> b.getOrder() - a.getOrder()).toList();
for (ServerListProvider each : sorted) {
boolean matchResult = each.match(properties);
LOGGER.info("Load and match ServerListProvider {}, match result: {}", each.getClass().getCanonicalName(),
matchResult);
if (matchResult) {
this.serverListProvider = each;
LOGGER.info("Will use {} as ServerListProvider", this.serverListProvider.getClass().getCanonicalName());
break;
}
}
if (null == serverListProvider) {
LOGGER.error("No server list provider found, SPI load size: {}", sorted.size());
throw new NacosException(NacosException.CLIENT_INVALID_PARAM, "No server list provider found.");
}
this.serverListProvider.init(properties, getNacosRestTemplate());
}

public String getContextPath() {
return serverListProvider.getContextPath();
}

public String getAddressSource() {
return serverListProvider.getAddressSource();
}

public boolean isFixed() {
return serverListProvider.isFixed();
}

/**
* get nacos rest template.
*
* @return nacos rest template
*/
protected abstract NacosRestTemplate getNacosRestTemplate();

@JustForTest
NacosClientProperties getProperties() {
return properties;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
/*
* Copyright 1999-2024 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.alibaba.nacos.maintainer.client.address;

import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.common.http.client.NacosRestTemplate;
import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.maintainer.client.env.NacosClientProperties;
import com.alibaba.nacos.maintainer.client.utils.ParamUtil;

import java.util.List;

/**
* Address server list provider.
*
* @author Nacos
*/
public abstract class AbstractServerListProvider implements ServerListProvider {

protected String contextPath = ParamUtil.getDefaultContextPath();

@Override
public void init(final NacosClientProperties properties, final NacosRestTemplate nacosRestTemplate) throws NacosException {
if (null == properties) {
throw new NacosException(NacosException.INVALID_PARAM, "properties is null");
}
initContextPath(properties);
}

/**
* Get server list.
* @return server list
*/
@Override
public abstract List<String> getServerList();

/**
* Get order.
* @return order
*/
@Override
public abstract int getOrder();

public String getContextPath() {
return contextPath;
}

private void initContextPath(NacosClientProperties properties) {
String contentPathTmp = properties.getProperty(PropertyKeyConst.CONTEXT_PATH);
if (!StringUtils.isBlank(contentPathTmp)) {
this.contextPath = contentPathTmp;
}
}
}
Loading