Skip to content

fix polaris.discovery.heartbeat.enabled is not effective #1565 #1621

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

Open
wants to merge 13 commits into
base: 2022
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@
- [feat:support config all recover enabled.](https://github.com/Tencent/spring-cloud-tencent/pull/1604)
- [feat:support stat reporting path aggregation.](https://github.com/Tencent/spring-cloud-tencent/pull/1608)
- [feat:support instance detect.](https://github.com/Tencent/spring-cloud-tencent/pull/1617)
- [fix: polaris.discovery.heartbeat.enabled not effective.](https://github.com/Tencent/spring-cloud-tencent/pull/1621)
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,12 @@ public class PolarisDiscoveryProperties {
*/
private Boolean enabled = true;

/**
* Enable heartbeat or not.
*/
@Value("${spring.cloud.polaris.discovery.heartbeat.enabled:true}")
private Boolean heartbeatEnabled = true;

/**
* If instance registered.
*/
Expand Down Expand Up @@ -279,6 +285,14 @@ public void setDetect(Detect detect) {
this.detect = detect;
}

public Boolean getHeartbeatEnabled() {
return heartbeatEnabled;
}

public void setHeartbeatEnabled(Boolean heartbeatEnabled) {
this.heartbeatEnabled = heartbeatEnabled;
}

@Override
public String toString() {
return "PolarisDiscoveryProperties{" +
Expand All @@ -290,6 +304,7 @@ public String toString() {
", version='" + version + '\'' +
", protocol='" + protocol + '\'' +
", enabled=" + enabled +
", heartbeatEnabled=" + heartbeatEnabled +
", registerEnabled=" + registerEnabled +
", heartbeatInterval=" + heartbeatInterval +
", healthCheckUrl='" + healthCheckUrl + '\'' +
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.cloud.client.serviceregistry.ServiceRegistry;
import org.springframework.cloud.context.scope.refresh.RefreshScopeRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.http.HttpHeaders;

import static java.util.concurrent.TimeUnit.SECONDS;
Expand All @@ -77,7 +79,6 @@ public class PolarisServiceRegistry implements ServiceRegistry<PolarisRegistrati

private final StaticMetadataManager staticMetadataManager;
private final PolarisStatProperties polarisStatProperties;
private final ScheduledExecutorService heartbeatExecutor;

public PolarisServiceRegistry(PolarisDiscoveryProperties polarisDiscoveryProperties,
PolarisSDKContextManager polarisSDKContextManager, PolarisDiscoveryHandler polarisDiscoveryHandler,
Expand All @@ -86,21 +87,11 @@ public PolarisServiceRegistry(PolarisDiscoveryProperties polarisDiscoveryPropert
this.polarisSDKContextManager = polarisSDKContextManager;
this.polarisDiscoveryHandler = polarisDiscoveryHandler;
this.staticMetadataManager = staticMetadataManager;

if (StringUtils.isNotBlank(polarisDiscoveryProperties.getHealthCheckUrl())) {
this.heartbeatExecutor = Executors
.newSingleThreadScheduledExecutor(new NamedThreadFactory("polaris-heartbeat"));
}
else {
this.heartbeatExecutor = null;
}

this.polarisStatProperties = polarisStatProperties;
}

@Override
public void register(PolarisRegistration registration) {

if (StringUtils.isBlank(registration.getServiceId())) {
LOGGER.warn("No service to register for polaris client...");
return;
Expand All @@ -121,7 +112,6 @@ public void register(PolarisRegistration registration) {
instanceRegisterRequest.setRegion(staticMetadataManager.getRegion());
instanceRegisterRequest.setZone(staticMetadataManager.getZone());
instanceRegisterRequest.setCampus(staticMetadataManager.getCampus());
instanceRegisterRequest.setTtl(polarisDiscoveryProperties.getHeartbeatInterval());
instanceRegisterRequest.setMetadata(registration.getMetadata());
instanceRegisterRequest.setExtendedMetadata(registration.getExtendedMetadata());
instanceRegisterRequest.setProtocol(polarisDiscoveryProperties.getProtocol());
Expand All @@ -138,42 +128,33 @@ public void register(PolarisRegistration registration) {
try {
ProviderAPI providerClient = polarisSDKContextManager.getProviderAPI();
InstanceRegisterResponse instanceRegisterResponse;
if (StringUtils.isBlank(polarisDiscoveryProperties.getHealthCheckUrl())) {
instanceRegisterResponse = providerClient.registerInstance(instanceRegisterRequest);
}
else {

if (!polarisDiscoveryProperties.getHeartbeatEnabled()) {
// Use register() when heartbeat is disabled - this doesn't start the SDK's heartbeat
instanceRegisterResponse = providerClient.register(instanceRegisterRequest);
InstanceHeartbeatRequest heartbeatRequest = new InstanceHeartbeatRequest();
BeanUtils.copyProperties(instanceRegisterRequest, heartbeatRequest);
heartbeatRequest.setInstanceID(instanceRegisterResponse.getInstanceId());
// Start the heartbeat thread after the registration is successful.
heartbeat(heartbeatRequest);
LOGGER.info("Registered instance without heartbeat.");
} else {
// Use registerInstance() when heartbeat is enabled - this starts the SDK's heartbeat
instanceRegisterRequest.setTtl(polarisDiscoveryProperties.getHeartbeatInterval());
instanceRegisterResponse = providerClient.registerInstance(instanceRegisterRequest);
LOGGER.info("Registered instance with heartbeat enabled.");
}

registration.setInstanceId(instanceRegisterResponse.getInstanceId());
LOGGER.info("polaris registry, {} {} {} {}:{} {} {} {} {} register finished", polarisDiscoveryProperties.getNamespace(),
registration.getServiceId(), registration.getInstanceId(), registration.getHost(), registration.getPort(),
staticMetadataManager.getRegion(), staticMetadataManager.getZone(), staticMetadataManager.getCampus(),
staticMetadataManager.getMergedStaticMetadata());
if (Objects.nonNull(polarisStatProperties) && polarisStatProperties.isEnabled()) {
try {
StatReporter statReporter = (StatReporter) polarisSDKContextManager.getSDKContext().getPlugins()
.getPlugin(PluginTypes.STAT_REPORTER.getBaseType(), StatReporterConfig.DEFAULT_REPORTER_PROMETHEUS);
if (Objects.nonNull(statReporter)) {
ReporterMetaInfo reporterMetaInfo = statReporter.metaInfo();
if (reporterMetaInfo.getPort() != null) {
LOGGER.info("Stat server started on port: " + reporterMetaInfo.getPort() + " (http)");
}
else {
LOGGER.info("Stat server is set to type of Push gateway");
}
}
else {
LOGGER.warn("Plugin StatReporter not found");
}
}
catch (Exception e) {
LOGGER.warn("Stat server started error, ", e);
}
LOGGER.info("polaris registry, {} {} {} {}:{} {} {} {} {} register finished",
instanceRegisterRequest.getNamespace(),
instanceRegisterRequest.getService(),
instanceRegisterResponse.getInstanceId(),
instanceRegisterRequest.getHost(),
instanceRegisterRequest.getPort(),
instanceRegisterRequest.getRegion(),
instanceRegisterRequest.getZone(),
instanceRegisterRequest.getCampus(),
instanceRegisterRequest.getMetadata());

// Start stat server and configure service
if (polarisStatProperties.isEnabled()) {
startStatServer();
}

ServiceConfigImpl serviceConfig = (ServiceConfigImpl) polarisSDKContextManager.getSDKContext().getConfig()
Expand All @@ -184,8 +165,29 @@ public void register(PolarisRegistration registration) {
PolarisSDKContextManager.isRegistered = true;
}
catch (Exception e) {
LOGGER.error("polaris registry, {} register failed...{},", registration.getServiceId(), registration, e);
rethrowRuntimeException(e);
LOGGER.error("ERR_POLARIS_REGISTER, register failed...{},", registration, e);
}
}

private void startStatServer() {
try {
StatReporter statReporter = (StatReporter) polarisSDKContextManager.getSDKContext().getPlugins()
.getPlugin(PluginTypes.STAT_REPORTER.getBaseType(), StatReporterConfig.DEFAULT_REPORTER_PROMETHEUS);
if (Objects.nonNull(statReporter)) {
ReporterMetaInfo reporterMetaInfo = statReporter.metaInfo();
if (reporterMetaInfo.getPort() != null) {
LOGGER.info("Stat server started on port: " + reporterMetaInfo.getPort() + " (http)");
}
else {
LOGGER.info("Stat server is set to type of Push gateway");
}
}
else {
LOGGER.warn("Plugin StatReporter not found");
}
}
catch (Exception e) {
LOGGER.warn("Stat server started error, ", e);
}
}

Expand Down Expand Up @@ -215,21 +217,14 @@ public void deregister(PolarisRegistration registration) {
catch (Exception e) {
LOGGER.error("ERR_POLARIS_DEREGISTER, de-register failed...{},", registration, e);
}
finally {
if (null != heartbeatExecutor) {
heartbeatExecutor.shutdown();
}
}
}

@Override
public void close() {

}

@Override
public void setStatus(PolarisRegistration registration, String status) {

}

@Override
Expand All @@ -249,40 +244,7 @@ public Object getStatus(PolarisRegistration registration) {
return "DOWN";
}

/**
* Start the heartbeat thread.
* @param heartbeatRequest heartbeat request
*/
public void heartbeat(InstanceHeartbeatRequest heartbeatRequest) {
heartbeatExecutor.scheduleWithFixedDelay(() -> {
try {
// If the health check passes, the heartbeat will be reported.
// If it does not pass, the heartbeat will not be reported.
Map<String, String> headers = new HashMap<>(1);
headers.put(HttpHeaders.USER_AGENT, "polaris");
if (!OkHttpUtil.checkUrl(heartbeatRequest.getHost(), heartbeatRequest.getPort(),
polarisDiscoveryProperties.getHealthCheckUrl(), headers)) {
LOGGER.error("backend service health check failed. health check endpoint = {}",
polarisDiscoveryProperties.getHealthCheckUrl());
return;
}

polarisSDKContextManager.getProviderAPI().heartbeat(heartbeatRequest);
LOGGER.trace("Polaris heartbeat is sent");
}
catch (PolarisException e) {
LOGGER.error("polaris heartbeat error with code [{}]", e.getCode(), e);
}
catch (Exception e) {
LOGGER.error("polaris heartbeat runtime error", e);
}
}, polarisDiscoveryProperties.getHeartbeatInterval(), polarisDiscoveryProperties.getHeartbeatInterval(), SECONDS);
}

@Override
public void destroy() {
if (heartbeatExecutor != null) {
heartbeatExecutor.shutdown();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@
"defaultValue": true,
"description": "enable polaris discovery or not."
},
{
"name": "spring.cloud.polaris.discovery.heartbeat.enabled",
"type": "java.lang.Boolean",
"defaultValue": true,
"description": "enable polaris heartbeat or not."
},
{
"name": "spring.cloud.polaris.discovery.register",
"type": "java.lang.Boolean",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ spring:
discovery:
enabled: true
register: true
heartbeat:
enabled: false
contract:
exposure: true
report:
Expand Down