You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@inlong.apache.org by GitBox <gi...@apache.org> on 2022/08/02 09:44:14 UTC

[GitHub] [inlong] kipshi opened a new pull request, #5332: [INLONG-5223][Manager] Add heartbeat Mechanism for Inlong component cluster

kipshi opened a new pull request, #5332:
URL: https://github.com/apache/inlong/pull/5332

   ### Prepare a Pull Request
   *(Change the title refer to the following example)*
   
   - Title Example: [INLONG-XYZ][Component] Title of the pull request
   
   *(The following *XYZ* should be replaced by the actual [GitHub Issue](https://github.com/apache/inlong/issues) number)*
   
   - Fixes #5222 
   
   ### Motivation
   
   1 Add heartbeat manager interface in Inlong common;
   
   2 Add heartbeat manager in Agent;
   
   3 Add heartbeat manager in Dataproxy;
   
   4 Optimize heartbeat mechanism in Manager, use Caffeine cache to manipulate evict node;
   
   5 Add inlong cluster Api in Manager Client;
   
   6 Add cluster tag in Agent Environment;
   
   7 Add cluster status and node status enums;
   
   8 Add clusterTag in FileCollectorTask;
   
   ### Modifications
   
   *Describe the modifications you've done.*
   
   ### Verifying this change
   
   *(Please pick either of the following options)*
   
   - [ ] This change is a trivial rework/code cleanup without any test coverage.
   
   - [ ] This change is already covered by existing tests, such as:
     *(please describe tests)*
   
   - [ ] This change added tests and can be verified as follows:
   
     *(example:)*
     - *Added integration tests for end-to-end deployment with large payloads (10MB)*
     - *Extended integration test for recovery after broker failure*
   
   ### Documentation
   
     - Does this pull request introduce a new feature? (yes / no)
     - If yes, how is the feature documented? (not applicable / docs / JavaDocs / not documented)
     - If a feature is not applicable for documentation, explain why?
     - If a feature is not documented yet in this PR, please create a follow-up issue for adding the documentation
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@inlong.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [inlong] healchow commented on a diff in pull request #5332: [INLONG-5222][Manager][Agent][DataProxy] Add heartbeat mechanism for Inlong component cluster

Posted by GitBox <gi...@apache.org>.
healchow commented on code in PR #5332:
URL: https://github.com/apache/inlong/pull/5332#discussion_r936566799


##########
inlong-manager/manager-pojo/src/main/java/org/apache/inlong/manager/pojo/cluster/agent/AgentClusterRequest.java:
##########
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.inlong.manager.pojo.cluster.agent;
+
+import io.swagger.annotations.ApiModel;
+import lombok.Data;
+import lombok.EqualsAndHashCode;
+import lombok.ToString;
+import org.apache.inlong.manager.common.enums.ClusterType;
+import org.apache.inlong.manager.pojo.cluster.ClusterRequest;
+import org.apache.inlong.manager.common.util.JsonTypeDefine;
+
+/**
+ * Inlong cluster request for agent
+ */
+@Data
+@ToString(callSuper = true)
+@EqualsAndHashCode(callSuper = true)
+@JsonTypeDefine(value = ClusterType.DATAPROXY)
+@ApiModel("Inlong cluster request for DataProxy")

Review Comment:
   This is `Agent` or `DataProxy`?



##########
pom.xml:
##########
@@ -1553,6 +1553,11 @@
                 <artifactId>dlc-data-catalog-metastore-client</artifactId>
                 <version>${dlc.client.version}</version>
             </dependency>
+            <dependency>

Review Comment:
   Does this newly added dependency have a special license and notice? If so, please add it to the `{project_path}/licenses` directory.



##########
inlong-manager/manager-service/src/test/java/org/apache/inlong/manager/service/core/impl/HeartbeatServiceTest.java:
##########
@@ -17,130 +17,62 @@
 
 package org.apache.inlong.manager.service.core.impl;
 
-import com.github.pagehelper.Page;
-import com.github.pagehelper.PageInfo;
-import org.apache.inlong.manager.pojo.heartbeat.ComponentHeartbeat;
-import org.apache.inlong.manager.pojo.heartbeat.ComponentHeartbeatResponse;
-import org.apache.inlong.manager.pojo.heartbeat.GroupHeartbeat;
-import org.apache.inlong.manager.pojo.heartbeat.GroupHeartbeatResponse;
-import org.apache.inlong.manager.pojo.heartbeat.HeartbeatPageRequest;
-import org.apache.inlong.manager.pojo.heartbeat.HeartbeatQueryRequest;
-import org.apache.inlong.manager.pojo.heartbeat.HeartbeatReportRequest;
-import org.apache.inlong.manager.pojo.heartbeat.StreamHeartbeat;
-import org.apache.inlong.manager.pojo.heartbeat.StreamHeartbeatResponse;
-import org.apache.inlong.manager.dao.entity.ComponentHeartbeatEntity;
-import org.apache.inlong.manager.dao.entity.GroupHeartbeatEntity;
-import org.apache.inlong.manager.dao.entity.StreamHeartbeatEntity;
+import com.google.common.collect.Maps;
+import org.apache.inlong.common.heartbeat.GroupHeartbeat;
+import org.apache.inlong.common.heartbeat.StreamHeartbeat;
+import org.apache.inlong.manager.common.util.JsonUtils;
 import org.apache.inlong.manager.dao.mapper.ComponentHeartbeatEntityMapper;
 import org.apache.inlong.manager.dao.mapper.GroupHeartbeatEntityMapper;
 import org.apache.inlong.manager.dao.mapper.StreamHeartbeatEntityMapper;
+import org.apache.inlong.manager.pojo.heartbeat.HeartbeatQueryRequest;
+import org.apache.inlong.manager.pojo.heartbeat.HeartbeatReportRequest;
+import org.apache.inlong.manager.pojo.heartbeat.StreamHeartbeatResponse;
+import org.apache.inlong.manager.service.ServiceBaseTest;
 import org.apache.inlong.manager.service.core.HeartbeatService;
 import org.junit.jupiter.api.Assertions;
-import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.Mockito;
-import org.mockito.MockitoAnnotations;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
 
 import java.time.Instant;
 import java.util.ArrayList;
 import java.util.List;
-
-import static org.mockito.BDDMockito.given;
+import java.util.Map;
 
 /**
  * Heartbeat service test.
  */
-public class HeartbeatServiceTest {
+@EnableAutoConfiguration
+public class HeartbeatServiceTest extends ServiceBaseTest {
 
-    @InjectMocks
-    private HeartbeatService heartbeatService = new HeartbeatServiceImpl();
-    @Mock
+    @Autowired
+    private HeartbeatService heartbeatService;
+    @Autowired
     private ComponentHeartbeatEntityMapper componentHeartbeatMapper;
-    @Mock
+    @Autowired
     private GroupHeartbeatEntityMapper groupHeartbeatMapper;
-    @Mock
+    @Autowired
     private StreamHeartbeatEntityMapper streamHeartbeatMapper;
 
-    /**
-     * setUp
-     */
-    @BeforeEach
-    public void setUp() {
-        MockitoAnnotations.openMocks(this);
-        ComponentHeartbeatEntity componentHeartbeat = new ComponentHeartbeatEntity();
-        componentHeartbeat.setComponent("Sort");
-        componentHeartbeat.setInstance("127.0.0.1");
-        componentHeartbeat.setStatusHeartbeat("[{\"status\":\"running\"}]");
-        componentHeartbeat.setMetricHeartbeat("[{\"mem\":\"16gb\",\"cpu\":\"60%\"}]");
-        componentHeartbeat.setReportTime(System.currentTimeMillis());
-        Page<ComponentHeartbeatEntity> componentPage = new Page<>();
-        componentPage.add(componentHeartbeat);
-        componentPage.setTotal(1);
-        given(componentHeartbeatMapper.insert(new ComponentHeartbeatEntity())).willReturn(1);
-        given(componentHeartbeatMapper.selectByKey(Mockito.anyString(),
-                Mockito.anyString())).willReturn(componentHeartbeat);
-        given(componentHeartbeatMapper.selectByCondition(Mockito.any())).willReturn(componentPage);
-
-        GroupHeartbeatEntity groupHeartbeat = new GroupHeartbeatEntity();
-        groupHeartbeat.setComponent("Sort");
-        groupHeartbeat.setInstance("127.0.0.1");
-        groupHeartbeat.setStatusHeartbeat("[{\"summaryMetric\":{\"totalRecordNumOfRead\""
-                + ": \"10\"},\"streamMetrics\":[{\"streamId\":\"stream1\"}]}]");
-        groupHeartbeat.setReportTime(System.currentTimeMillis());
-        groupHeartbeat.setMetricHeartbeat("[{\"summaryMetric\":{\"totalRecordNumOfRead\""
-                + ": \"10\"},"
-                + "\"streamMetrics\":[{\"streamId\":\"stream1\"}]}]");
-        Page<GroupHeartbeatEntity> groupPage = new Page<>();
-        groupPage.add(groupHeartbeat);
-        groupPage.setTotal(1);
-        given(groupHeartbeatMapper.selectByKey(Mockito.anyString(),
-                Mockito.anyString(), Mockito.anyString())).willReturn(groupHeartbeat);
-        given(groupHeartbeatMapper.selectByCondition(Mockito.any())).willReturn(groupPage);
-
-        StreamHeartbeatEntity streamHeartbeat = new StreamHeartbeatEntity();
-        streamHeartbeat.setComponent("Sort");
-        streamHeartbeat.setInstance("127.0.0.1");
-        streamHeartbeat.setInlongGroupId("group1");
-        streamHeartbeat.setInlongStreamId("test_test");
-        streamHeartbeat.setStatusHeartbeat("[{\"statue\":\"running\"}]");
-        streamHeartbeat.setMetricHeartbeat("[{\"outMsg\":\"1\",\"inMsg\":2}]");
-        streamHeartbeat.setReportTime(System.currentTimeMillis());
-
-        Page<StreamHeartbeatEntity> streamPage = new Page<>();
-        streamPage.add(streamHeartbeat);
-        streamPage.setTotal(1);
-
-        given(streamHeartbeatMapper.selectByKey(Mockito.anyString(),
-                Mockito.anyString(), Mockito.anyString(), Mockito.anyString()))
-                .willReturn(streamHeartbeat);
-        given(streamHeartbeatMapper.selectByCondition(Mockito.any())).willReturn(streamPage);
-    }
-
     @Test
     public void testReportHeartbeat() {
         HeartbeatReportRequest request = new HeartbeatReportRequest();
-        request.setComponent("Sort");
-        request.setInstance("127.0.0.1");
+        request.setComponentType("AGENT");

Review Comment:
   Please replace it with the constant of `ClusterType`.



##########
inlong-manager/manager-service/src/main/java/org/apache/inlong/manager/service/core/heartbeat/HeartbeatManager.java:
##########
@@ -0,0 +1,180 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.inlong.manager.service.core.heartbeat;
+
+import com.github.benmanes.caffeine.cache.Cache;
+import com.github.benmanes.caffeine.cache.Caffeine;
+import com.github.benmanes.caffeine.cache.LoadingCache;
+import com.github.benmanes.caffeine.cache.RemovalCause;
+import lombok.Getter;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.inlong.common.heartbeat.AbstractHeartbeatManager;
+import org.apache.inlong.common.heartbeat.ComponentHeartbeat;
+import org.apache.inlong.common.heartbeat.HeartbeatMsg;
+import org.apache.inlong.manager.common.consts.InlongConstants;
+import org.apache.inlong.manager.common.enums.ClusterStatus;
+import org.apache.inlong.manager.common.enums.NodeStatus;
+import org.apache.inlong.manager.dao.entity.InlongClusterEntity;
+import org.apache.inlong.manager.dao.entity.InlongClusterNodeEntity;
+import org.apache.inlong.manager.dao.mapper.InlongClusterEntityMapper;
+import org.apache.inlong.manager.dao.mapper.InlongClusterNodeEntityMapper;
+import org.apache.inlong.manager.pojo.cluster.ClusterInfo;
+import org.apache.inlong.manager.pojo.cluster.ClusterNodeRequest;
+import org.apache.inlong.manager.pojo.user.UserRoleCode;
+import org.apache.inlong.manager.service.cluster.InlongClusterOperator;
+import org.apache.inlong.manager.service.cluster.InlongClusterOperatorFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.PostConstruct;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+@Component
+@Slf4j
+public class HeartbeatManager implements AbstractHeartbeatManager {
+
+    @Getter
+    private Cache<ComponentHeartbeat, HeartbeatMsg> heartbeats;

Review Comment:
   It is recommended to change it to `heartbeatCache`, which is easier to understand.



##########
inlong-manager/manager-service/src/main/java/org/apache/inlong/manager/service/core/heartbeat/HeartbeatManager.java:
##########
@@ -0,0 +1,180 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.inlong.manager.service.core.heartbeat;
+
+import com.github.benmanes.caffeine.cache.Cache;
+import com.github.benmanes.caffeine.cache.Caffeine;
+import com.github.benmanes.caffeine.cache.LoadingCache;
+import com.github.benmanes.caffeine.cache.RemovalCause;
+import lombok.Getter;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.inlong.common.heartbeat.AbstractHeartbeatManager;
+import org.apache.inlong.common.heartbeat.ComponentHeartbeat;
+import org.apache.inlong.common.heartbeat.HeartbeatMsg;
+import org.apache.inlong.manager.common.consts.InlongConstants;
+import org.apache.inlong.manager.common.enums.ClusterStatus;
+import org.apache.inlong.manager.common.enums.NodeStatus;
+import org.apache.inlong.manager.dao.entity.InlongClusterEntity;
+import org.apache.inlong.manager.dao.entity.InlongClusterNodeEntity;
+import org.apache.inlong.manager.dao.mapper.InlongClusterEntityMapper;
+import org.apache.inlong.manager.dao.mapper.InlongClusterNodeEntityMapper;
+import org.apache.inlong.manager.pojo.cluster.ClusterInfo;
+import org.apache.inlong.manager.pojo.cluster.ClusterNodeRequest;
+import org.apache.inlong.manager.pojo.user.UserRoleCode;
+import org.apache.inlong.manager.service.cluster.InlongClusterOperator;
+import org.apache.inlong.manager.service.cluster.InlongClusterOperatorFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.PostConstruct;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+@Component
+@Slf4j
+public class HeartbeatManager implements AbstractHeartbeatManager {
+
+    @Getter
+    private Cache<ComponentHeartbeat, HeartbeatMsg> heartbeats;
+
+    @Getter
+    private LoadingCache<ComponentHeartbeat, ClusterInfo> clusterInfos;

Review Comment:
   It is recommended to change it to `clusterInfoCache`, which is easier to understand.



##########
inlong-dataproxy/dataproxy-source/src/main/java/org/apache/inlong/dataproxy/heartbeat/HeartbeatManager.java:
##########
@@ -0,0 +1,150 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.inlong.dataproxy.heartbeat;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.http.client.config.RequestConfig;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClientBuilder;
+import org.apache.http.util.EntityUtils;
+import org.apache.inlong.common.enums.ComponentTypeEnum;
+import org.apache.inlong.common.heartbeat.AbstractHeartbeatManager;
+import org.apache.inlong.common.heartbeat.GroupHeartbeat;
+import org.apache.inlong.common.heartbeat.HeartbeatMsg;
+import org.apache.inlong.common.heartbeat.StreamHeartbeat;
+import org.apache.inlong.dataproxy.config.ConfigManager;
+import org.apache.inlong.dataproxy.consts.ConfigConstants;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.concurrent.TimeUnit;
+
+import static java.util.concurrent.TimeUnit.SECONDS;
+
+@Slf4j
+public class HeartbeatManager implements AbstractHeartbeatManager {
+
+    private CloseableHttpClient httpClient;
+    private Gson gson;
+
+    public HeartbeatManager() {
+        httpClient = constructHttpClient();
+        gson = new GsonBuilder().create();
+    }
+
+    public void start() {
+        Thread reportHeartbeatThread = new Thread(() -> {
+            while (true) {
+                HeartbeatMsg heartbeatMsg = new HeartbeatMsg();
+                reportHeartbeat(heartbeatMsg);
+                try {
+                    SECONDS.sleep(heartbeatInterval());
+                } catch (InterruptedException ex) {
+                    log.error("", ex);

Review Comment:
   It is recommended to add specific information. Because no matter what type of exception, simple and understandable logging is a good coding style.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@inlong.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [inlong] leosanqing commented on a diff in pull request #5332: [INLONG-5222][Manager][Agent][DataProxy] Add heartbeat mechanism for Inlong component cluster

Posted by GitBox <gi...@apache.org>.
leosanqing commented on code in PR #5332:
URL: https://github.com/apache/inlong/pull/5332#discussion_r936805140


##########
inlong-manager/manager-service/src/main/java/org/apache/inlong/manager/service/core/heartbeat/HeartbeatManager.java:
##########
@@ -0,0 +1,180 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.inlong.manager.service.core.heartbeat;
+
+import com.github.benmanes.caffeine.cache.Cache;
+import com.github.benmanes.caffeine.cache.Caffeine;
+import com.github.benmanes.caffeine.cache.LoadingCache;
+import com.github.benmanes.caffeine.cache.RemovalCause;
+import lombok.Getter;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.inlong.common.heartbeat.AbstractHeartbeatManager;
+import org.apache.inlong.common.heartbeat.ComponentHeartbeat;
+import org.apache.inlong.common.heartbeat.HeartbeatMsg;
+import org.apache.inlong.manager.common.consts.InlongConstants;
+import org.apache.inlong.manager.common.enums.ClusterStatus;
+import org.apache.inlong.manager.common.enums.NodeStatus;
+import org.apache.inlong.manager.dao.entity.InlongClusterEntity;
+import org.apache.inlong.manager.dao.entity.InlongClusterNodeEntity;
+import org.apache.inlong.manager.dao.mapper.InlongClusterEntityMapper;
+import org.apache.inlong.manager.dao.mapper.InlongClusterNodeEntityMapper;
+import org.apache.inlong.manager.pojo.cluster.ClusterInfo;
+import org.apache.inlong.manager.pojo.cluster.ClusterNodeRequest;
+import org.apache.inlong.manager.pojo.user.UserRoleCode;
+import org.apache.inlong.manager.service.cluster.InlongClusterOperator;
+import org.apache.inlong.manager.service.cluster.InlongClusterOperatorFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.PostConstruct;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+@Component
+@Slf4j
+public class HeartbeatManager implements AbstractHeartbeatManager {
+
+    @Getter
+    private Cache<ComponentHeartbeat, HeartbeatMsg> heartbeats;
+
+    @Getter
+    private LoadingCache<ComponentHeartbeat, ClusterInfo> clusterInfos;
+
+    @Autowired
+    private InlongClusterOperatorFactory clusterOperatorFactory;
+
+    @Autowired
+    private InlongClusterEntityMapper clusterMapper;
+
+    @Autowired
+    private InlongClusterNodeEntityMapper clusterNodeMapper;
+
+    @PostConstruct
+    public void init() {
+        long expireTime = heartbeatInterval() * 2;
+        heartbeats = Caffeine.newBuilder()
+                .expireAfterAccess(expireTime, TimeUnit.SECONDS)
+                .removalListener((ComponentHeartbeat k, HeartbeatMsg v, RemovalCause c) -> {
+                    evictClusterNode(v);
+                }).build();
+
+        clusterInfos = Caffeine.newBuilder()
+                .expireAfterAccess(expireTime, TimeUnit.SECONDS)
+                .build(k -> fetchCluster(k));
+    }
+
+    @Override
+    public void reportHeartbeat(HeartbeatMsg heartbeat) {
+        ComponentHeartbeat componentHeartbeat = heartbeat.componentHeartbeat();
+        ClusterInfo clusterInfo = clusterInfos.get(componentHeartbeat);
+        if (clusterInfo == null) {
+            log.error("find no cluster by clusterName={} and type={}", componentHeartbeat.getClusterName(),
+                    componentHeartbeat.getComponentType());
+            return;
+        }
+        HeartbeatMsg lastHeartbeat = heartbeats.getIfPresent(componentHeartbeat);
+        if (lastHeartbeat == null) {
+            InlongClusterNodeEntity clusterNode = getClusterNode(clusterInfo, heartbeat);
+            if (clusterNode == null) {
+                insertClusterNode(clusterInfo, heartbeat);
+                log.info("insert node success");
+            } else {
+                updateClusterNode(clusterNode);
+                log.info("update node success");
+
+            }
+        }
+        heartbeats.put(componentHeartbeat, heartbeat);
+    }
+
+    private void evictClusterNode(HeartbeatMsg heartbeat) {
+        log.debug("evict cluster node");
+        ComponentHeartbeat componentHeartbeat = heartbeat.componentHeartbeat();
+        ClusterInfo clusterInfo = clusterInfos.getIfPresent(componentHeartbeat);
+        if (clusterInfo == null) {
+            log.error("find no cluster by clusterName={} and type={}", componentHeartbeat.getClusterName(),
+                    componentHeartbeat.getComponentType());
+            return;
+        }
+        InlongClusterNodeEntity clusterNode = getClusterNode(clusterInfo, heartbeat);
+        if (clusterNode == null) {
+            log.error("find no cluster node by type={},ip={},port={}",
+                    heartbeat.getComponentType(), heartbeat.getIp(), heartbeat.getPort());
+            return;
+        }
+        clusterNode.setStatus(NodeStatus.HEARTBEAT_TIMEOUT.getStatus());
+        clusterNodeMapper.updateById(clusterNode);
+    }
+
+    private InlongClusterNodeEntity getClusterNode(ClusterInfo clusterInfo, HeartbeatMsg heartbeat) {
+        ClusterNodeRequest nodeRequest = new ClusterNodeRequest();
+        nodeRequest.setParentId(clusterInfo.getId());
+        nodeRequest.setType(heartbeat.getComponentType());
+        nodeRequest.setIp(heartbeat.getIp());
+        nodeRequest.setPort(heartbeat.getPort());
+        InlongClusterNodeEntity clusterNode = clusterNodeMapper.selectByUniqueKey(nodeRequest);
+        return clusterNode;
+    }
+
+    private void insertClusterNode(ClusterInfo clusterInfo, HeartbeatMsg heartbeat) {
+        InlongClusterNodeEntity clusterNode = new InlongClusterNodeEntity();
+        clusterNode.setParentId(clusterInfo.getId());
+        clusterNode.setType(heartbeat.getComponentType());
+        clusterNode.setIp(heartbeat.getIp());
+        clusterNode.setPort(heartbeat.getPort());
+        clusterNode.setStatus(ClusterStatus.NORMAL.getStatus());
+        clusterNode.setCreator(UserRoleCode.ADMIN);
+        clusterNode.setModifier(UserRoleCode.ADMIN);
+        clusterNode.setIsDeleted(InlongConstants.UN_DELETED);
+        clusterNodeMapper.insertOnDuplicateKeyUpdate(clusterNode);
+    }
+
+    private void updateClusterNode(InlongClusterNodeEntity clusterNode) {
+        clusterNode.setStatus(ClusterStatus.NORMAL.getStatus());
+        clusterNodeMapper.updateById(clusterNode);
+    }
+
+    private ClusterInfo fetchCluster(ComponentHeartbeat componentHeartbeat) {
+        log.debug("fetch cluster");
+        final String clusterName = componentHeartbeat.getClusterName();
+        final String type = componentHeartbeat.getComponentType();
+        final String clusterTag = componentHeartbeat.getClusterTag();
+        List<InlongClusterEntity> entities = clusterMapper.selectByKey(clusterTag, clusterName, type);
+        if (CollectionUtils.isNotEmpty(entities)) {
+            InlongClusterEntity cluster = entities.get(0);
+            InlongClusterOperator operator = clusterOperatorFactory.getInstance(cluster.getType());
+            ClusterInfo clusterInfo = operator.getFromEntity(cluster);
+            return clusterInfo;
+        }
+        InlongClusterEntity cluster = new InlongClusterEntity();

Review Comment:
   Add a blank line



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@inlong.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [inlong] kipshi commented on a diff in pull request #5332: [INLONG-5222][Manager][Agent][DataProxy] Add heartbeat mechanism for Inlong component cluster

Posted by GitBox <gi...@apache.org>.
kipshi commented on code in PR #5332:
URL: https://github.com/apache/inlong/pull/5332#discussion_r937380561


##########
inlong-dataproxy/dataproxy-source/src/main/java/org/apache/inlong/dataproxy/heartbeat/HeartbeatManager.java:
##########
@@ -0,0 +1,150 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.inlong.dataproxy.heartbeat;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.http.client.config.RequestConfig;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClientBuilder;
+import org.apache.http.util.EntityUtils;
+import org.apache.inlong.common.enums.ComponentTypeEnum;
+import org.apache.inlong.common.heartbeat.AbstractHeartbeatManager;
+import org.apache.inlong.common.heartbeat.GroupHeartbeat;
+import org.apache.inlong.common.heartbeat.HeartbeatMsg;
+import org.apache.inlong.common.heartbeat.StreamHeartbeat;
+import org.apache.inlong.dataproxy.config.ConfigManager;
+import org.apache.inlong.dataproxy.consts.ConfigConstants;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.concurrent.TimeUnit;
+
+import static java.util.concurrent.TimeUnit.SECONDS;
+
+@Slf4j
+public class HeartbeatManager implements AbstractHeartbeatManager {
+
+    private CloseableHttpClient httpClient;
+    private Gson gson;
+
+    public HeartbeatManager() {
+        httpClient = constructHttpClient();
+        gson = new GsonBuilder().create();
+    }
+
+    public void start() {
+        Thread reportHeartbeatThread = new Thread(() -> {
+            while (true) {
+                HeartbeatMsg heartbeatMsg = buildHeartbeat();
+                reportHeartbeat(heartbeatMsg);
+                try {
+                    SECONDS.sleep(heartbeatInterval());
+                } catch (InterruptedException ex) {
+                    log.error("", ex);
+                }
+            }
+        });
+        reportHeartbeatThread.setDaemon(true);
+        reportHeartbeatThread.start();
+    }
+
+    @Override
+    public void reportHeartbeat(HeartbeatMsg heartbeat) {
+        ConfigManager configManager = ConfigManager.getInstance();
+        final String managerHost = configManager.getCommonProperties().get(ConfigConstants.MANAGER_HOST);
+        final String url =
+                "http://" + managerHost + ConfigConstants.MANAGER_PATH + ConfigConstants.MANAGER_HEARTBEAT_REPORT;
+        try {
+            HttpPost post = new HttpPost(url);
+            String body = gson.toJson(heartbeat);
+            StringEntity stringEntity = new StringEntity(body);
+            stringEntity.setContentType("application/json");
+            post.setEntity(stringEntity);
+            CloseableHttpResponse response = httpClient.execute(post);
+            String isSuccess = EntityUtils.toString(response.getEntity());
+            if (StringUtils.isNotEmpty(isSuccess)
+                    && response.getStatusLine().getStatusCode() == 200) {
+                if (log.isDebugEnabled()) {
+                    log.debug("reportHeartbeat url {}, heartbeat: {}, return str {}", url, body, isSuccess);
+                }
+            }
+        } catch (Exception ex) {
+            log.error("reportHeartbeat failed for url {}", url, ex);
+        }
+    }
+
+    private synchronized CloseableHttpClient constructHttpClient() {
+        long timeoutInMs = TimeUnit.MILLISECONDS.toMillis(50000);
+        RequestConfig requestConfig = RequestConfig.custom()
+                .setConnectTimeout((int) timeoutInMs)
+                .setSocketTimeout((int) timeoutInMs).build();
+        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
+        httpClientBuilder.setDefaultRequestConfig(requestConfig);
+        return httpClientBuilder.build();
+    }
+
+    private HeartbeatMsg buildHeartbeat() {
+        ConfigManager configManager = ConfigManager.getInstance();
+        HeartbeatMsg heartbeatMsg = new HeartbeatMsg();
+        Map<String, String> commonProperties = configManager.getCommonProperties();
+        String localIp = commonProperties.get(ConfigConstants.PROXY_LOCAL_IP);
+        heartbeatMsg.setIp(localIp);
+        heartbeatMsg.setComponentType(ComponentTypeEnum.DataProxy.getName());
+        heartbeatMsg.setReportTime(System.currentTimeMillis());
+        Map<String, String> groupIdMappings = configManager.getGroupIdMappingProperties();
+        Map<String, Map<String, String>> streamIdMappings = configManager.getStreamIdMappingProperties();
+        Map<String, String> groupIdEnableMappings = configManager.getGroupIdEnableMappingProperties();
+        List<GroupHeartbeat> groupHeartbeats = new ArrayList<>();

Review Comment:
   not necessary +4 



##########
inlong-dataproxy/dataproxy-source/src/main/java/org/apache/inlong/dataproxy/heartbeat/HeartbeatManager.java:
##########
@@ -0,0 +1,150 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.inlong.dataproxy.heartbeat;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.http.client.config.RequestConfig;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClientBuilder;
+import org.apache.http.util.EntityUtils;
+import org.apache.inlong.common.enums.ComponentTypeEnum;
+import org.apache.inlong.common.heartbeat.AbstractHeartbeatManager;
+import org.apache.inlong.common.heartbeat.GroupHeartbeat;
+import org.apache.inlong.common.heartbeat.HeartbeatMsg;
+import org.apache.inlong.common.heartbeat.StreamHeartbeat;
+import org.apache.inlong.dataproxy.config.ConfigManager;
+import org.apache.inlong.dataproxy.consts.ConfigConstants;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.concurrent.TimeUnit;
+
+import static java.util.concurrent.TimeUnit.SECONDS;
+
+@Slf4j
+public class HeartbeatManager implements AbstractHeartbeatManager {
+
+    private CloseableHttpClient httpClient;
+    private Gson gson;
+
+    public HeartbeatManager() {
+        httpClient = constructHttpClient();
+        gson = new GsonBuilder().create();
+    }
+
+    public void start() {
+        Thread reportHeartbeatThread = new Thread(() -> {
+            while (true) {
+                HeartbeatMsg heartbeatMsg = buildHeartbeat();
+                reportHeartbeat(heartbeatMsg);
+                try {
+                    SECONDS.sleep(heartbeatInterval());
+                } catch (InterruptedException ex) {
+                    log.error("", ex);
+                }
+            }
+        });
+        reportHeartbeatThread.setDaemon(true);
+        reportHeartbeatThread.start();
+    }
+
+    @Override
+    public void reportHeartbeat(HeartbeatMsg heartbeat) {
+        ConfigManager configManager = ConfigManager.getInstance();
+        final String managerHost = configManager.getCommonProperties().get(ConfigConstants.MANAGER_HOST);
+        final String url =
+                "http://" + managerHost + ConfigConstants.MANAGER_PATH + ConfigConstants.MANAGER_HEARTBEAT_REPORT;
+        try {
+            HttpPost post = new HttpPost(url);
+            String body = gson.toJson(heartbeat);
+            StringEntity stringEntity = new StringEntity(body);
+            stringEntity.setContentType("application/json");
+            post.setEntity(stringEntity);
+            CloseableHttpResponse response = httpClient.execute(post);
+            String isSuccess = EntityUtils.toString(response.getEntity());
+            if (StringUtils.isNotEmpty(isSuccess)
+                    && response.getStatusLine().getStatusCode() == 200) {
+                if (log.isDebugEnabled()) {
+                    log.debug("reportHeartbeat url {}, heartbeat: {}, return str {}", url, body, isSuccess);
+                }
+            }
+        } catch (Exception ex) {
+            log.error("reportHeartbeat failed for url {}", url, ex);
+        }
+    }
+
+    private synchronized CloseableHttpClient constructHttpClient() {
+        long timeoutInMs = TimeUnit.MILLISECONDS.toMillis(50000);
+        RequestConfig requestConfig = RequestConfig.custom()
+                .setConnectTimeout((int) timeoutInMs)
+                .setSocketTimeout((int) timeoutInMs).build();
+        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
+        httpClientBuilder.setDefaultRequestConfig(requestConfig);
+        return httpClientBuilder.build();
+    }
+
+    private HeartbeatMsg buildHeartbeat() {
+        ConfigManager configManager = ConfigManager.getInstance();
+        HeartbeatMsg heartbeatMsg = new HeartbeatMsg();
+        Map<String, String> commonProperties = configManager.getCommonProperties();
+        String localIp = commonProperties.get(ConfigConstants.PROXY_LOCAL_IP);
+        heartbeatMsg.setIp(localIp);
+        heartbeatMsg.setComponentType(ComponentTypeEnum.DataProxy.getName());
+        heartbeatMsg.setReportTime(System.currentTimeMillis());
+        Map<String, String> groupIdMappings = configManager.getGroupIdMappingProperties();
+        Map<String, Map<String, String>> streamIdMappings = configManager.getStreamIdMappingProperties();
+        Map<String, String> groupIdEnableMappings = configManager.getGroupIdEnableMappingProperties();
+        List<GroupHeartbeat> groupHeartbeats = new ArrayList<>();
+        for (Entry<String, String> entry : groupIdMappings.entrySet()) {
+            String groupIdNum = entry.getKey();
+            String groupId = entry.getValue();
+            GroupHeartbeat groupHeartbeat = new GroupHeartbeat();
+            groupHeartbeat.setInlongGroupId(groupId);
+            String status = groupIdEnableMappings.getOrDefault(groupIdNum, "disabled");
+            status = status.equals("TRUE") ? "enabled" : "disabled";
+            groupHeartbeat.setStatus(status);
+            groupHeartbeats.add(groupHeartbeat);
+        }
+        heartbeatMsg.setGroupHeartbeats(groupHeartbeats);
+        List<StreamHeartbeat> streamHeartbeats = new ArrayList<>();

Review Comment:
   not necessary + 5



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@inlong.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [inlong] kipshi commented on a diff in pull request #5332: [INLONG-5222][Manager][Agent][DataProxy] Add heartbeat mechanism for Inlong component cluster

Posted by GitBox <gi...@apache.org>.
kipshi commented on code in PR #5332:
URL: https://github.com/apache/inlong/pull/5332#discussion_r937381458


##########
inlong-manager/manager-service/src/test/java/org/apache/inlong/manager/service/core/heartbeat/HeartbeatManagerTest.java:
##########
@@ -0,0 +1,89 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.inlong.manager.service.core.heartbeat;
+
+import lombok.extern.slf4j.Slf4j;
+import org.apache.inlong.common.enums.ComponentTypeEnum;
+import org.apache.inlong.common.heartbeat.HeartbeatMsg;
+import org.apache.inlong.manager.common.enums.NodeStatus;
+import org.apache.inlong.manager.pojo.cluster.ClusterNodeRequest;
+import org.apache.inlong.manager.common.util.JsonUtils;
+import org.apache.inlong.manager.dao.entity.InlongClusterEntity;
+import org.apache.inlong.manager.dao.entity.InlongClusterNodeEntity;
+import org.apache.inlong.manager.dao.mapper.InlongClusterEntityMapper;
+import org.apache.inlong.manager.dao.mapper.InlongClusterNodeEntityMapper;
+import org.apache.inlong.manager.service.ServiceBaseTest;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
+
+import java.util.List;
+
+@EnableAutoConfiguration
+@Slf4j
+public class HeartbeatManagerTest extends ServiceBaseTest {
+
+    @Autowired
+    HeartbeatManager heartbeatManager;
+
+    @Autowired
+    InlongClusterEntityMapper clusterMapper;
+
+    @Autowired
+    InlongClusterNodeEntityMapper clusterNodeMapper;
+
+    @Test
+    void testReportHeartbeat() throws InterruptedException {
+        HeartbeatMsg msg = createHeartbeatMsg();
+        heartbeatManager.reportHeartbeat(msg);
+        InlongClusterEntity entity = clusterMapper.selectById(1);
+        log.info(JsonUtils.toJsonString(entity));
+        List<InlongClusterEntity> clusterEntities = clusterMapper.selectByKey(null, msg.getClusterName(),
+                msg.getComponentType());
+        Assertions.assertTrue(clusterEntities.size() == 1);
+        Assertions.assertTrue(clusterEntities.get(0).getName().equals(msg.getClusterName()));
+        int clusterId = clusterEntities.get(0).getId();
+        ClusterNodeRequest nodeRequest = new ClusterNodeRequest();
+        nodeRequest.setParentId(clusterId);
+        nodeRequest.setType(msg.getComponentType());
+        nodeRequest.setIp(msg.getIp());
+        nodeRequest.setPort(msg.getPort());
+        InlongClusterNodeEntity clusterNode = clusterNodeMapper.selectByUniqueKey(nodeRequest);
+        Assertions.assertTrue(clusterNode != null);
+        Assertions.assertTrue(clusterNode.getStatus() == NodeStatus.NORMAL.getStatus());
+        heartbeatManager.getHeartbeats().invalidateAll();
+        Thread.sleep(1000);
+        clusterNode = clusterNodeMapper.selectByUniqueKey(nodeRequest);
+        log.debug(JsonUtils.toJsonString(clusterNode));
+        Assertions.assertTrue(clusterNode.getStatus() == NodeStatus.HEARTBEAT_TIMEOUT.getStatus());

Review Comment:
   not necessary +11



##########
inlong-manager/manager-service/src/test/java/org/apache/inlong/manager/service/core/heartbeat/HeartbeatManagerTest.java:
##########
@@ -0,0 +1,89 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.inlong.manager.service.core.heartbeat;
+
+import lombok.extern.slf4j.Slf4j;
+import org.apache.inlong.common.enums.ComponentTypeEnum;
+import org.apache.inlong.common.heartbeat.HeartbeatMsg;
+import org.apache.inlong.manager.common.enums.NodeStatus;
+import org.apache.inlong.manager.pojo.cluster.ClusterNodeRequest;
+import org.apache.inlong.manager.common.util.JsonUtils;
+import org.apache.inlong.manager.dao.entity.InlongClusterEntity;
+import org.apache.inlong.manager.dao.entity.InlongClusterNodeEntity;
+import org.apache.inlong.manager.dao.mapper.InlongClusterEntityMapper;
+import org.apache.inlong.manager.dao.mapper.InlongClusterNodeEntityMapper;
+import org.apache.inlong.manager.service.ServiceBaseTest;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
+
+import java.util.List;
+
+@EnableAutoConfiguration
+@Slf4j
+public class HeartbeatManagerTest extends ServiceBaseTest {
+
+    @Autowired
+    HeartbeatManager heartbeatManager;
+
+    @Autowired
+    InlongClusterEntityMapper clusterMapper;
+
+    @Autowired
+    InlongClusterNodeEntityMapper clusterNodeMapper;
+
+    @Test
+    void testReportHeartbeat() throws InterruptedException {
+        HeartbeatMsg msg = createHeartbeatMsg();
+        heartbeatManager.reportHeartbeat(msg);
+        InlongClusterEntity entity = clusterMapper.selectById(1);
+        log.info(JsonUtils.toJsonString(entity));
+        List<InlongClusterEntity> clusterEntities = clusterMapper.selectByKey(null, msg.getClusterName(),
+                msg.getComponentType());
+        Assertions.assertTrue(clusterEntities.size() == 1);
+        Assertions.assertTrue(clusterEntities.get(0).getName().equals(msg.getClusterName()));
+        int clusterId = clusterEntities.get(0).getId();
+        ClusterNodeRequest nodeRequest = new ClusterNodeRequest();
+        nodeRequest.setParentId(clusterId);
+        nodeRequest.setType(msg.getComponentType());
+        nodeRequest.setIp(msg.getIp());
+        nodeRequest.setPort(msg.getPort());
+        InlongClusterNodeEntity clusterNode = clusterNodeMapper.selectByUniqueKey(nodeRequest);
+        Assertions.assertTrue(clusterNode != null);
+        Assertions.assertTrue(clusterNode.getStatus() == NodeStatus.NORMAL.getStatus());
+        heartbeatManager.getHeartbeats().invalidateAll();
+        Thread.sleep(1000);
+        clusterNode = clusterNodeMapper.selectByUniqueKey(nodeRequest);
+        log.debug(JsonUtils.toJsonString(clusterNode));
+        Assertions.assertTrue(clusterNode.getStatus() == NodeStatus.HEARTBEAT_TIMEOUT.getStatus());
+        heartbeatManager.reportHeartbeat(msg);
+        clusterNode = clusterNodeMapper.selectByUniqueKey(nodeRequest);
+        Assertions.assertTrue(clusterNode.getStatus() == NodeStatus.NORMAL.getStatus());

Review Comment:
   same as above



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@inlong.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [inlong] kipshi commented on a diff in pull request #5332: [INLONG-5222][Manager][Agent][DataProxy] Add heartbeat mechanism for Inlong component cluster

Posted by GitBox <gi...@apache.org>.
kipshi commented on code in PR #5332:
URL: https://github.com/apache/inlong/pull/5332#discussion_r937386803


##########
inlong-manager/manager-service/src/test/java/org/apache/inlong/manager/service/core/heartbeat/HeartbeatManagerTest.java:
##########
@@ -0,0 +1,89 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.inlong.manager.service.core.heartbeat;
+
+import lombok.extern.slf4j.Slf4j;
+import org.apache.inlong.common.enums.ComponentTypeEnum;
+import org.apache.inlong.common.heartbeat.HeartbeatMsg;
+import org.apache.inlong.manager.common.enums.NodeStatus;
+import org.apache.inlong.manager.pojo.cluster.ClusterNodeRequest;
+import org.apache.inlong.manager.common.util.JsonUtils;
+import org.apache.inlong.manager.dao.entity.InlongClusterEntity;
+import org.apache.inlong.manager.dao.entity.InlongClusterNodeEntity;
+import org.apache.inlong.manager.dao.mapper.InlongClusterEntityMapper;
+import org.apache.inlong.manager.dao.mapper.InlongClusterNodeEntityMapper;
+import org.apache.inlong.manager.service.ServiceBaseTest;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
+
+import java.util.List;
+
+@EnableAutoConfiguration
+@Slf4j
+public class HeartbeatManagerTest extends ServiceBaseTest {
+
+    @Autowired
+    HeartbeatManager heartbeatManager;
+
+    @Autowired
+    InlongClusterEntityMapper clusterMapper;
+
+    @Autowired
+    InlongClusterNodeEntityMapper clusterNodeMapper;
+
+    @Test
+    void testReportHeartbeat() throws InterruptedException {
+        HeartbeatMsg msg = createHeartbeatMsg();
+        heartbeatManager.reportHeartbeat(msg);
+        InlongClusterEntity entity = clusterMapper.selectById(1);
+        log.info(JsonUtils.toJsonString(entity));
+        List<InlongClusterEntity> clusterEntities = clusterMapper.selectByKey(null, msg.getClusterName(),
+                msg.getComponentType());
+        Assertions.assertTrue(clusterEntities.size() == 1);
+        Assertions.assertTrue(clusterEntities.get(0).getName().equals(msg.getClusterName()));
+        int clusterId = clusterEntities.get(0).getId();

Review Comment:
   not necessary+11



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@inlong.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [inlong] leosanqing commented on a diff in pull request #5332: [INLONG-5222][Manager][Agent][DataProxy] Add heartbeat mechanism for Inlong component cluster

Posted by GitBox <gi...@apache.org>.
leosanqing commented on code in PR #5332:
URL: https://github.com/apache/inlong/pull/5332#discussion_r936777405


##########
inlong-agent/agent-core/src/main/java/org/apache/inlong/agent/core/HeartbeatManager.java:
##########
@@ -106,6 +176,50 @@ private TaskSnapshotRequest getHeartBeat() {
         return taskSnapshotRequest;
     }
 
+    /**
+     * build heartbeat message of agent
+     */
+    private HeartbeatMsg buildHeartbeatMsg() {
+        HeartbeatMsg heartbeatMsg = new HeartbeatMsg();
+        final String agentIp = AgentUtils.fetchLocalIp();
+        final int agentPort = conf.getInt(AGENT_HTTP_PORT, DEFAULT_AGENT_HTTP_PORT);
+        final String clusterName = conf.get(AGENT_CLUSTER_NAME);
+        final String clusterTag = conf.get(AGENT_CLUSTER_TAG);
+        heartbeatMsg.setIp(agentIp);
+        heartbeatMsg.setPort(agentPort);
+        heartbeatMsg.setComponentType(ComponentTypeEnum.Agent.getName());
+        heartbeatMsg.setReportTime(System.currentTimeMillis());
+        if (StringUtils.isNotBlank(clusterName)) {

Review Comment:
   Personally I think it would be better. The above is the logic of getting attributes, and the following is the logic of constructing the heartbeatMsg object
   ```
            final String agentIp = AgentUtils.fetchLocalIp();
            final int agentPort = conf.getInt(AGENT_HTTP_PORT, DEFAULT_AGENT_HTTP_PORT);
            final String clusterName = conf.get(AGENT_CLUSTER_NAME);
            final String clusterTag = conf.get(AGENT_CLUSTER_TAG);
   
            HeartbeatMsg heartbeatMsg = new HeartbeatMsg();
            heartbeatMsg.setIp(agentIp);
            heartbeatMsg.setPort(agentPort);
            heartbeatMsg.setComponentType(ComponentTypeEnum.Agent.getName());
            heartbeatMsg.setReportTime(System.currentTimeMillis());
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@inlong.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [inlong] leosanqing commented on a diff in pull request #5332: [INLONG-5222][Manager][Agent][DataProxy] Add heartbeat mechanism for Inlong component cluster

Posted by GitBox <gi...@apache.org>.
leosanqing commented on code in PR #5332:
URL: https://github.com/apache/inlong/pull/5332#discussion_r936807513


##########
inlong-manager/manager-service/src/main/java/org/apache/inlong/manager/service/core/heartbeat/HeartbeatManager.java:
##########
@@ -0,0 +1,180 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.inlong.manager.service.core.heartbeat;
+
+import com.github.benmanes.caffeine.cache.Cache;
+import com.github.benmanes.caffeine.cache.Caffeine;
+import com.github.benmanes.caffeine.cache.LoadingCache;
+import com.github.benmanes.caffeine.cache.RemovalCause;
+import lombok.Getter;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.inlong.common.heartbeat.AbstractHeartbeatManager;
+import org.apache.inlong.common.heartbeat.ComponentHeartbeat;
+import org.apache.inlong.common.heartbeat.HeartbeatMsg;
+import org.apache.inlong.manager.common.consts.InlongConstants;
+import org.apache.inlong.manager.common.enums.ClusterStatus;
+import org.apache.inlong.manager.common.enums.NodeStatus;
+import org.apache.inlong.manager.dao.entity.InlongClusterEntity;
+import org.apache.inlong.manager.dao.entity.InlongClusterNodeEntity;
+import org.apache.inlong.manager.dao.mapper.InlongClusterEntityMapper;
+import org.apache.inlong.manager.dao.mapper.InlongClusterNodeEntityMapper;
+import org.apache.inlong.manager.pojo.cluster.ClusterInfo;
+import org.apache.inlong.manager.pojo.cluster.ClusterNodeRequest;
+import org.apache.inlong.manager.pojo.user.UserRoleCode;
+import org.apache.inlong.manager.service.cluster.InlongClusterOperator;
+import org.apache.inlong.manager.service.cluster.InlongClusterOperatorFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.PostConstruct;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+@Component
+@Slf4j
+public class HeartbeatManager implements AbstractHeartbeatManager {
+
+    @Getter
+    private Cache<ComponentHeartbeat, HeartbeatMsg> heartbeats;
+
+    @Getter
+    private LoadingCache<ComponentHeartbeat, ClusterInfo> clusterInfos;
+
+    @Autowired
+    private InlongClusterOperatorFactory clusterOperatorFactory;
+
+    @Autowired
+    private InlongClusterEntityMapper clusterMapper;
+
+    @Autowired
+    private InlongClusterNodeEntityMapper clusterNodeMapper;
+
+    @PostConstruct
+    public void init() {
+        long expireTime = heartbeatInterval() * 2;
+        heartbeats = Caffeine.newBuilder()
+                .expireAfterAccess(expireTime, TimeUnit.SECONDS)
+                .removalListener((ComponentHeartbeat k, HeartbeatMsg v, RemovalCause c) -> {
+                    evictClusterNode(v);
+                }).build();
+
+        clusterInfos = Caffeine.newBuilder()
+                .expireAfterAccess(expireTime, TimeUnit.SECONDS)
+                .build(k -> fetchCluster(k));
+    }
+
+    @Override
+    public void reportHeartbeat(HeartbeatMsg heartbeat) {
+        ComponentHeartbeat componentHeartbeat = heartbeat.componentHeartbeat();
+        ClusterInfo clusterInfo = clusterInfos.get(componentHeartbeat);
+        if (clusterInfo == null) {
+            log.error("find no cluster by clusterName={} and type={}", componentHeartbeat.getClusterName(),
+                    componentHeartbeat.getComponentType());
+            return;
+        }
+        HeartbeatMsg lastHeartbeat = heartbeats.getIfPresent(componentHeartbeat);
+        if (lastHeartbeat == null) {
+            InlongClusterNodeEntity clusterNode = getClusterNode(clusterInfo, heartbeat);
+            if (clusterNode == null) {
+                insertClusterNode(clusterInfo, heartbeat);
+                log.info("insert node success");
+            } else {
+                updateClusterNode(clusterNode);
+                log.info("update node success");
+
+            }
+        }
+        heartbeats.put(componentHeartbeat, heartbeat);
+    }
+
+    private void evictClusterNode(HeartbeatMsg heartbeat) {
+        log.debug("evict cluster node");
+        ComponentHeartbeat componentHeartbeat = heartbeat.componentHeartbeat();
+        ClusterInfo clusterInfo = clusterInfos.getIfPresent(componentHeartbeat);
+        if (clusterInfo == null) {
+            log.error("find no cluster by clusterName={} and type={}", componentHeartbeat.getClusterName(),
+                    componentHeartbeat.getComponentType());
+            return;
+        }
+        InlongClusterNodeEntity clusterNode = getClusterNode(clusterInfo, heartbeat);
+        if (clusterNode == null) {
+            log.error("find no cluster node by type={},ip={},port={}",
+                    heartbeat.getComponentType(), heartbeat.getIp(), heartbeat.getPort());
+            return;
+        }
+        clusterNode.setStatus(NodeStatus.HEARTBEAT_TIMEOUT.getStatus());
+        clusterNodeMapper.updateById(clusterNode);
+    }
+
+    private InlongClusterNodeEntity getClusterNode(ClusterInfo clusterInfo, HeartbeatMsg heartbeat) {
+        ClusterNodeRequest nodeRequest = new ClusterNodeRequest();
+        nodeRequest.setParentId(clusterInfo.getId());
+        nodeRequest.setType(heartbeat.getComponentType());
+        nodeRequest.setIp(heartbeat.getIp());
+        nodeRequest.setPort(heartbeat.getPort());
+        InlongClusterNodeEntity clusterNode = clusterNodeMapper.selectByUniqueKey(nodeRequest);
+        return clusterNode;
+    }
+
+    private void insertClusterNode(ClusterInfo clusterInfo, HeartbeatMsg heartbeat) {
+        InlongClusterNodeEntity clusterNode = new InlongClusterNodeEntity();
+        clusterNode.setParentId(clusterInfo.getId());
+        clusterNode.setType(heartbeat.getComponentType());
+        clusterNode.setIp(heartbeat.getIp());
+        clusterNode.setPort(heartbeat.getPort());
+        clusterNode.setStatus(ClusterStatus.NORMAL.getStatus());
+        clusterNode.setCreator(UserRoleCode.ADMIN);
+        clusterNode.setModifier(UserRoleCode.ADMIN);
+        clusterNode.setIsDeleted(InlongConstants.UN_DELETED);
+        clusterNodeMapper.insertOnDuplicateKeyUpdate(clusterNode);
+    }
+
+    private void updateClusterNode(InlongClusterNodeEntity clusterNode) {
+        clusterNode.setStatus(ClusterStatus.NORMAL.getStatus());
+        clusterNodeMapper.updateById(clusterNode);
+    }
+
+    private ClusterInfo fetchCluster(ComponentHeartbeat componentHeartbeat) {
+        log.debug("fetch cluster");
+        final String clusterName = componentHeartbeat.getClusterName();
+        final String type = componentHeartbeat.getComponentType();
+        final String clusterTag = componentHeartbeat.getClusterTag();
+        List<InlongClusterEntity> entities = clusterMapper.selectByKey(clusterTag, clusterName, type);
+        if (CollectionUtils.isNotEmpty(entities)) {
+            InlongClusterEntity cluster = entities.get(0);

Review Comment:
   Please add a comment why only the first one needs to be returned



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@inlong.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [inlong] leosanqing commented on a diff in pull request #5332: [INLONG-5222][Manager][Agent][DataProxy] Add heartbeat mechanism for Inlong component cluster

Posted by GitBox <gi...@apache.org>.
leosanqing commented on code in PR #5332:
URL: https://github.com/apache/inlong/pull/5332#discussion_r936798078


##########
inlong-dataproxy/dataproxy-source/src/main/java/org/apache/inlong/dataproxy/heartbeat/HeartbeatManager.java:
##########
@@ -0,0 +1,150 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.inlong.dataproxy.heartbeat;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.http.client.config.RequestConfig;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClientBuilder;
+import org.apache.http.util.EntityUtils;
+import org.apache.inlong.common.enums.ComponentTypeEnum;
+import org.apache.inlong.common.heartbeat.AbstractHeartbeatManager;
+import org.apache.inlong.common.heartbeat.GroupHeartbeat;
+import org.apache.inlong.common.heartbeat.HeartbeatMsg;
+import org.apache.inlong.common.heartbeat.StreamHeartbeat;
+import org.apache.inlong.dataproxy.config.ConfigManager;
+import org.apache.inlong.dataproxy.consts.ConfigConstants;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.concurrent.TimeUnit;
+
+import static java.util.concurrent.TimeUnit.SECONDS;
+
+@Slf4j
+public class HeartbeatManager implements AbstractHeartbeatManager {
+
+    private CloseableHttpClient httpClient;
+    private Gson gson;
+
+    public HeartbeatManager() {
+        httpClient = constructHttpClient();
+        gson = new GsonBuilder().create();
+    }
+
+    public void start() {
+        Thread reportHeartbeatThread = new Thread(() -> {
+            while (true) {
+                HeartbeatMsg heartbeatMsg = buildHeartbeat();
+                reportHeartbeat(heartbeatMsg);
+                try {
+                    SECONDS.sleep(heartbeatInterval());
+                } catch (InterruptedException ex) {
+                    log.error("", ex);
+                }
+            }
+        });
+        reportHeartbeatThread.setDaemon(true);
+        reportHeartbeatThread.start();
+    }
+
+    @Override
+    public void reportHeartbeat(HeartbeatMsg heartbeat) {
+        ConfigManager configManager = ConfigManager.getInstance();
+        final String managerHost = configManager.getCommonProperties().get(ConfigConstants.MANAGER_HOST);
+        final String url =
+                "http://" + managerHost + ConfigConstants.MANAGER_PATH + ConfigConstants.MANAGER_HEARTBEAT_REPORT;
+        try {
+            HttpPost post = new HttpPost(url);
+            String body = gson.toJson(heartbeat);
+            StringEntity stringEntity = new StringEntity(body);
+            stringEntity.setContentType("application/json");
+            post.setEntity(stringEntity);
+            CloseableHttpResponse response = httpClient.execute(post);
+            String isSuccess = EntityUtils.toString(response.getEntity());
+            if (StringUtils.isNotEmpty(isSuccess)
+                    && response.getStatusLine().getStatusCode() == 200) {
+                if (log.isDebugEnabled()) {
+                    log.debug("reportHeartbeat url {}, heartbeat: {}, return str {}", url, body, isSuccess);
+                }
+            }
+        } catch (Exception ex) {
+            log.error("reportHeartbeat failed for url {}", url, ex);
+        }
+    }
+
+    private synchronized CloseableHttpClient constructHttpClient() {
+        long timeoutInMs = TimeUnit.MILLISECONDS.toMillis(50000);
+        RequestConfig requestConfig = RequestConfig.custom()
+                .setConnectTimeout((int) timeoutInMs)
+                .setSocketTimeout((int) timeoutInMs).build();
+        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
+        httpClientBuilder.setDefaultRequestConfig(requestConfig);
+        return httpClientBuilder.build();
+    }
+
+    private HeartbeatMsg buildHeartbeat() {
+        ConfigManager configManager = ConfigManager.getInstance();
+        HeartbeatMsg heartbeatMsg = new HeartbeatMsg();
+        Map<String, String> commonProperties = configManager.getCommonProperties();
+        String localIp = commonProperties.get(ConfigConstants.PROXY_LOCAL_IP);
+        heartbeatMsg.setIp(localIp);
+        heartbeatMsg.setComponentType(ComponentTypeEnum.DataProxy.getName());
+        heartbeatMsg.setReportTime(System.currentTimeMillis());
+        Map<String, String> groupIdMappings = configManager.getGroupIdMappingProperties();
+        Map<String, Map<String, String>> streamIdMappings = configManager.getStreamIdMappingProperties();
+        Map<String, String> groupIdEnableMappings = configManager.getGroupIdEnableMappingProperties();
+        List<GroupHeartbeat> groupHeartbeats = new ArrayList<>();

Review Comment:
   Add blank line



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@inlong.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [inlong] kipshi commented on a diff in pull request #5332: [INLONG-5222][Manager][Agent][DataProxy] Add heartbeat mechanism for Inlong component cluster

Posted by GitBox <gi...@apache.org>.
kipshi commented on code in PR #5332:
URL: https://github.com/apache/inlong/pull/5332#discussion_r937381262


##########
inlong-manager/manager-service/src/main/java/org/apache/inlong/manager/service/core/heartbeat/HeartbeatManager.java:
##########
@@ -0,0 +1,180 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.inlong.manager.service.core.heartbeat;
+
+import com.github.benmanes.caffeine.cache.Cache;
+import com.github.benmanes.caffeine.cache.Caffeine;
+import com.github.benmanes.caffeine.cache.LoadingCache;
+import com.github.benmanes.caffeine.cache.RemovalCause;
+import lombok.Getter;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.inlong.common.heartbeat.AbstractHeartbeatManager;
+import org.apache.inlong.common.heartbeat.ComponentHeartbeat;
+import org.apache.inlong.common.heartbeat.HeartbeatMsg;
+import org.apache.inlong.manager.common.consts.InlongConstants;
+import org.apache.inlong.manager.common.enums.ClusterStatus;
+import org.apache.inlong.manager.common.enums.NodeStatus;
+import org.apache.inlong.manager.dao.entity.InlongClusterEntity;
+import org.apache.inlong.manager.dao.entity.InlongClusterNodeEntity;
+import org.apache.inlong.manager.dao.mapper.InlongClusterEntityMapper;
+import org.apache.inlong.manager.dao.mapper.InlongClusterNodeEntityMapper;
+import org.apache.inlong.manager.pojo.cluster.ClusterInfo;
+import org.apache.inlong.manager.pojo.cluster.ClusterNodeRequest;
+import org.apache.inlong.manager.pojo.user.UserRoleCode;
+import org.apache.inlong.manager.service.cluster.InlongClusterOperator;
+import org.apache.inlong.manager.service.cluster.InlongClusterOperatorFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.PostConstruct;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+@Component
+@Slf4j
+public class HeartbeatManager implements AbstractHeartbeatManager {
+
+    @Getter
+    private Cache<ComponentHeartbeat, HeartbeatMsg> heartbeats;
+
+    @Getter
+    private LoadingCache<ComponentHeartbeat, ClusterInfo> clusterInfos;
+
+    @Autowired
+    private InlongClusterOperatorFactory clusterOperatorFactory;
+
+    @Autowired
+    private InlongClusterEntityMapper clusterMapper;
+
+    @Autowired
+    private InlongClusterNodeEntityMapper clusterNodeMapper;
+
+    @PostConstruct
+    public void init() {
+        long expireTime = heartbeatInterval() * 2;
+        heartbeats = Caffeine.newBuilder()
+                .expireAfterAccess(expireTime, TimeUnit.SECONDS)
+                .removalListener((ComponentHeartbeat k, HeartbeatMsg v, RemovalCause c) -> {
+                    evictClusterNode(v);
+                }).build();
+
+        clusterInfos = Caffeine.newBuilder()
+                .expireAfterAccess(expireTime, TimeUnit.SECONDS)
+                .build(k -> fetchCluster(k));
+    }
+
+    @Override
+    public void reportHeartbeat(HeartbeatMsg heartbeat) {
+        ComponentHeartbeat componentHeartbeat = heartbeat.componentHeartbeat();
+        ClusterInfo clusterInfo = clusterInfos.get(componentHeartbeat);
+        if (clusterInfo == null) {
+            log.error("find no cluster by clusterName={} and type={}", componentHeartbeat.getClusterName(),
+                    componentHeartbeat.getComponentType());
+            return;
+        }
+        HeartbeatMsg lastHeartbeat = heartbeats.getIfPresent(componentHeartbeat);
+        if (lastHeartbeat == null) {
+            InlongClusterNodeEntity clusterNode = getClusterNode(clusterInfo, heartbeat);
+            if (clusterNode == null) {
+                insertClusterNode(clusterInfo, heartbeat);
+                log.info("insert node success");
+            } else {
+                updateClusterNode(clusterNode);
+                log.info("update node success");
+
+            }
+        }
+        heartbeats.put(componentHeartbeat, heartbeat);
+    }
+
+    private void evictClusterNode(HeartbeatMsg heartbeat) {
+        log.debug("evict cluster node");
+        ComponentHeartbeat componentHeartbeat = heartbeat.componentHeartbeat();
+        ClusterInfo clusterInfo = clusterInfos.getIfPresent(componentHeartbeat);
+        if (clusterInfo == null) {
+            log.error("find no cluster by clusterName={} and type={}", componentHeartbeat.getClusterName(),
+                    componentHeartbeat.getComponentType());
+            return;
+        }
+        InlongClusterNodeEntity clusterNode = getClusterNode(clusterInfo, heartbeat);
+        if (clusterNode == null) {
+            log.error("find no cluster node by type={},ip={},port={}",
+                    heartbeat.getComponentType(), heartbeat.getIp(), heartbeat.getPort());
+            return;
+        }
+        clusterNode.setStatus(NodeStatus.HEARTBEAT_TIMEOUT.getStatus());
+        clusterNodeMapper.updateById(clusterNode);
+    }
+
+    private InlongClusterNodeEntity getClusterNode(ClusterInfo clusterInfo, HeartbeatMsg heartbeat) {
+        ClusterNodeRequest nodeRequest = new ClusterNodeRequest();
+        nodeRequest.setParentId(clusterInfo.getId());
+        nodeRequest.setType(heartbeat.getComponentType());
+        nodeRequest.setIp(heartbeat.getIp());
+        nodeRequest.setPort(heartbeat.getPort());
+        InlongClusterNodeEntity clusterNode = clusterNodeMapper.selectByUniqueKey(nodeRequest);
+        return clusterNode;
+    }
+
+    private void insertClusterNode(ClusterInfo clusterInfo, HeartbeatMsg heartbeat) {
+        InlongClusterNodeEntity clusterNode = new InlongClusterNodeEntity();
+        clusterNode.setParentId(clusterInfo.getId());
+        clusterNode.setType(heartbeat.getComponentType());
+        clusterNode.setIp(heartbeat.getIp());
+        clusterNode.setPort(heartbeat.getPort());
+        clusterNode.setStatus(ClusterStatus.NORMAL.getStatus());
+        clusterNode.setCreator(UserRoleCode.ADMIN);
+        clusterNode.setModifier(UserRoleCode.ADMIN);
+        clusterNode.setIsDeleted(InlongConstants.UN_DELETED);
+        clusterNodeMapper.insertOnDuplicateKeyUpdate(clusterNode);
+    }
+
+    private void updateClusterNode(InlongClusterNodeEntity clusterNode) {
+        clusterNode.setStatus(ClusterStatus.NORMAL.getStatus());
+        clusterNodeMapper.updateById(clusterNode);
+    }
+
+    private ClusterInfo fetchCluster(ComponentHeartbeat componentHeartbeat) {
+        log.debug("fetch cluster");
+        final String clusterName = componentHeartbeat.getClusterName();
+        final String type = componentHeartbeat.getComponentType();
+        final String clusterTag = componentHeartbeat.getClusterTag();
+        List<InlongClusterEntity> entities = clusterMapper.selectByKey(clusterTag, clusterName, type);
+        if (CollectionUtils.isNotEmpty(entities)) {
+            InlongClusterEntity cluster = entities.get(0);
+            InlongClusterOperator operator = clusterOperatorFactory.getInstance(cluster.getType());
+            ClusterInfo clusterInfo = operator.getFromEntity(cluster);
+            return clusterInfo;
+        }
+        InlongClusterEntity cluster = new InlongClusterEntity();

Review Comment:
   not necessary +8



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@inlong.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [inlong] leosanqing commented on a diff in pull request #5332: [INLONG-5222][Manager][Agent][DataProxy] Add heartbeat mechanism for Inlong component cluster

Posted by GitBox <gi...@apache.org>.
leosanqing commented on code in PR #5332:
URL: https://github.com/apache/inlong/pull/5332#discussion_r936781410


##########
inlong-agent/agent-core/src/main/java/org/apache/inlong/agent/core/HeartbeatManager.java:
##########
@@ -106,6 +176,50 @@ private TaskSnapshotRequest getHeartBeat() {
         return taskSnapshotRequest;
     }
 
+    /**
+     * build heartbeat message of agent
+     */
+    private HeartbeatMsg buildHeartbeatMsg() {
+        HeartbeatMsg heartbeatMsg = new HeartbeatMsg();
+        final String agentIp = AgentUtils.fetchLocalIp();
+        final int agentPort = conf.getInt(AGENT_HTTP_PORT, DEFAULT_AGENT_HTTP_PORT);
+        final String clusterName = conf.get(AGENT_CLUSTER_NAME);
+        final String clusterTag = conf.get(AGENT_CLUSTER_TAG);
+        heartbeatMsg.setIp(agentIp);
+        heartbeatMsg.setPort(agentPort);
+        heartbeatMsg.setComponentType(ComponentTypeEnum.Agent.getName());
+        heartbeatMsg.setReportTime(System.currentTimeMillis());
+        if (StringUtils.isNotBlank(clusterName)) {
+            heartbeatMsg.setClusterName(clusterName);
+        }
+        if (StringUtils.isNotBlank(clusterTag)) {
+            heartbeatMsg.setClusterTag(clusterTag);
+        }
+        Map<String, JobWrapper> jobWrapperMap = jobmanager.getJobs();

Review Comment:
   Add a blank line to split the logic of building the jobWrapperMap and setting the heartbeatMsg field



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@inlong.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [inlong] kipshi commented on a diff in pull request #5332: [INLONG-5222][Manager][Agent][DataProxy] Add heartbeat mechanism for Inlong component cluster

Posted by GitBox <gi...@apache.org>.
kipshi commented on code in PR #5332:
URL: https://github.com/apache/inlong/pull/5332#discussion_r937380092


##########
inlong-agent/agent-core/src/main/java/org/apache/inlong/agent/core/HeartbeatManager.java:
##########
@@ -106,6 +176,50 @@ private TaskSnapshotRequest getHeartBeat() {
         return taskSnapshotRequest;
     }
 
+    /**
+     * build heartbeat message of agent
+     */
+    private HeartbeatMsg buildHeartbeatMsg() {
+        HeartbeatMsg heartbeatMsg = new HeartbeatMsg();
+        final String agentIp = AgentUtils.fetchLocalIp();
+        final int agentPort = conf.getInt(AGENT_HTTP_PORT, DEFAULT_AGENT_HTTP_PORT);
+        final String clusterName = conf.get(AGENT_CLUSTER_NAME);
+        final String clusterTag = conf.get(AGENT_CLUSTER_TAG);
+        heartbeatMsg.setIp(agentIp);
+        heartbeatMsg.setPort(agentPort);
+        heartbeatMsg.setComponentType(ComponentTypeEnum.Agent.getName());
+        heartbeatMsg.setReportTime(System.currentTimeMillis());
+        if (StringUtils.isNotBlank(clusterName)) {

Review Comment:
   i personally wouldn't



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@inlong.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [inlong] leosanqing commented on a diff in pull request #5332: [INLONG-5222][Manager][Agent][DataProxy] Add heartbeat mechanism for Inlong component cluster

Posted by GitBox <gi...@apache.org>.
leosanqing commented on code in PR #5332:
URL: https://github.com/apache/inlong/pull/5332#discussion_r936815572


##########
inlong-manager/manager-service/src/test/java/org/apache/inlong/manager/service/core/heartbeat/HeartbeatManagerTest.java:
##########
@@ -0,0 +1,89 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.inlong.manager.service.core.heartbeat;
+
+import lombok.extern.slf4j.Slf4j;
+import org.apache.inlong.common.enums.ComponentTypeEnum;
+import org.apache.inlong.common.heartbeat.HeartbeatMsg;
+import org.apache.inlong.manager.common.enums.NodeStatus;
+import org.apache.inlong.manager.pojo.cluster.ClusterNodeRequest;
+import org.apache.inlong.manager.common.util.JsonUtils;
+import org.apache.inlong.manager.dao.entity.InlongClusterEntity;
+import org.apache.inlong.manager.dao.entity.InlongClusterNodeEntity;
+import org.apache.inlong.manager.dao.mapper.InlongClusterEntityMapper;
+import org.apache.inlong.manager.dao.mapper.InlongClusterNodeEntityMapper;
+import org.apache.inlong.manager.service.ServiceBaseTest;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
+
+import java.util.List;
+
+@EnableAutoConfiguration
+@Slf4j
+public class HeartbeatManagerTest extends ServiceBaseTest {
+
+    @Autowired
+    HeartbeatManager heartbeatManager;
+
+    @Autowired
+    InlongClusterEntityMapper clusterMapper;
+
+    @Autowired
+    InlongClusterNodeEntityMapper clusterNodeMapper;
+
+    @Test
+    void testReportHeartbeat() throws InterruptedException {
+        HeartbeatMsg msg = createHeartbeatMsg();
+        heartbeatManager.reportHeartbeat(msg);
+        InlongClusterEntity entity = clusterMapper.selectById(1);
+        log.info(JsonUtils.toJsonString(entity));
+        List<InlongClusterEntity> clusterEntities = clusterMapper.selectByKey(null, msg.getClusterName(),
+                msg.getComponentType());
+        Assertions.assertTrue(clusterEntities.size() == 1);
+        Assertions.assertTrue(clusterEntities.get(0).getName().equals(msg.getClusterName()));
+        int clusterId = clusterEntities.get(0).getId();
+        ClusterNodeRequest nodeRequest = new ClusterNodeRequest();
+        nodeRequest.setParentId(clusterId);
+        nodeRequest.setType(msg.getComponentType());
+        nodeRequest.setIp(msg.getIp());
+        nodeRequest.setPort(msg.getPort());
+        InlongClusterNodeEntity clusterNode = clusterNodeMapper.selectByUniqueKey(nodeRequest);
+        Assertions.assertTrue(clusterNode != null);
+        Assertions.assertTrue(clusterNode.getStatus() == NodeStatus.NORMAL.getStatus());
+        heartbeatManager.getHeartbeats().invalidateAll();

Review Comment:
   pls add a blank line



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@inlong.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [inlong] leosanqing commented on a diff in pull request #5332: [INLONG-5222][Manager][Agent][DataProxy] Add heartbeat mechanism for Inlong component cluster

Posted by GitBox <gi...@apache.org>.
leosanqing commented on code in PR #5332:
URL: https://github.com/apache/inlong/pull/5332#discussion_r936816585


##########
inlong-manager/manager-service/src/test/java/org/apache/inlong/manager/service/core/heartbeat/HeartbeatManagerTest.java:
##########
@@ -0,0 +1,89 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.inlong.manager.service.core.heartbeat;
+
+import lombok.extern.slf4j.Slf4j;
+import org.apache.inlong.common.enums.ComponentTypeEnum;
+import org.apache.inlong.common.heartbeat.HeartbeatMsg;
+import org.apache.inlong.manager.common.enums.NodeStatus;
+import org.apache.inlong.manager.pojo.cluster.ClusterNodeRequest;
+import org.apache.inlong.manager.common.util.JsonUtils;
+import org.apache.inlong.manager.dao.entity.InlongClusterEntity;
+import org.apache.inlong.manager.dao.entity.InlongClusterNodeEntity;
+import org.apache.inlong.manager.dao.mapper.InlongClusterEntityMapper;
+import org.apache.inlong.manager.dao.mapper.InlongClusterNodeEntityMapper;
+import org.apache.inlong.manager.service.ServiceBaseTest;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
+
+import java.util.List;
+
+@EnableAutoConfiguration
+@Slf4j
+public class HeartbeatManagerTest extends ServiceBaseTest {
+
+    @Autowired
+    HeartbeatManager heartbeatManager;
+
+    @Autowired
+    InlongClusterEntityMapper clusterMapper;
+
+    @Autowired
+    InlongClusterNodeEntityMapper clusterNodeMapper;
+
+    @Test
+    void testReportHeartbeat() throws InterruptedException {
+        HeartbeatMsg msg = createHeartbeatMsg();
+        heartbeatManager.reportHeartbeat(msg);
+        InlongClusterEntity entity = clusterMapper.selectById(1);
+        log.info(JsonUtils.toJsonString(entity));
+        List<InlongClusterEntity> clusterEntities = clusterMapper.selectByKey(null, msg.getClusterName(),
+                msg.getComponentType());
+        Assertions.assertTrue(clusterEntities.size() == 1);
+        Assertions.assertTrue(clusterEntities.get(0).getName().equals(msg.getClusterName()));
+        int clusterId = clusterEntities.get(0).getId();
+        ClusterNodeRequest nodeRequest = new ClusterNodeRequest();
+        nodeRequest.setParentId(clusterId);
+        nodeRequest.setType(msg.getComponentType());
+        nodeRequest.setIp(msg.getIp());
+        nodeRequest.setPort(msg.getPort());
+        InlongClusterNodeEntity clusterNode = clusterNodeMapper.selectByUniqueKey(nodeRequest);
+        Assertions.assertTrue(clusterNode != null);
+        Assertions.assertTrue(clusterNode.getStatus() == NodeStatus.NORMAL.getStatus());
+        heartbeatManager.getHeartbeats().invalidateAll();
+        Thread.sleep(1000);
+        clusterNode = clusterNodeMapper.selectByUniqueKey(nodeRequest);
+        log.debug(JsonUtils.toJsonString(clusterNode));
+        Assertions.assertTrue(clusterNode.getStatus() == NodeStatus.HEARTBEAT_TIMEOUT.getStatus());
+        heartbeatManager.reportHeartbeat(msg);
+        clusterNode = clusterNodeMapper.selectByUniqueKey(nodeRequest);
+        Assertions.assertTrue(clusterNode.getStatus() == NodeStatus.NORMAL.getStatus());

Review Comment:
   same as above



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@inlong.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [inlong] leosanqing commented on a diff in pull request #5332: [INLONG-5222][Manager][Agent][DataProxy] Add heartbeat mechanism for Inlong component cluster

Posted by GitBox <gi...@apache.org>.
leosanqing commented on code in PR #5332:
URL: https://github.com/apache/inlong/pull/5332#discussion_r936814999


##########
inlong-manager/manager-service/src/test/java/org/apache/inlong/manager/service/core/heartbeat/HeartbeatManagerTest.java:
##########
@@ -0,0 +1,89 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.inlong.manager.service.core.heartbeat;
+
+import lombok.extern.slf4j.Slf4j;
+import org.apache.inlong.common.enums.ComponentTypeEnum;
+import org.apache.inlong.common.heartbeat.HeartbeatMsg;
+import org.apache.inlong.manager.common.enums.NodeStatus;
+import org.apache.inlong.manager.pojo.cluster.ClusterNodeRequest;
+import org.apache.inlong.manager.common.util.JsonUtils;
+import org.apache.inlong.manager.dao.entity.InlongClusterEntity;
+import org.apache.inlong.manager.dao.entity.InlongClusterNodeEntity;
+import org.apache.inlong.manager.dao.mapper.InlongClusterEntityMapper;
+import org.apache.inlong.manager.dao.mapper.InlongClusterNodeEntityMapper;
+import org.apache.inlong.manager.service.ServiceBaseTest;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
+
+import java.util.List;
+
+@EnableAutoConfiguration
+@Slf4j
+public class HeartbeatManagerTest extends ServiceBaseTest {
+
+    @Autowired
+    HeartbeatManager heartbeatManager;
+
+    @Autowired
+    InlongClusterEntityMapper clusterMapper;
+
+    @Autowired
+    InlongClusterNodeEntityMapper clusterNodeMapper;
+
+    @Test
+    void testReportHeartbeat() throws InterruptedException {
+        HeartbeatMsg msg = createHeartbeatMsg();
+        heartbeatManager.reportHeartbeat(msg);
+        InlongClusterEntity entity = clusterMapper.selectById(1);
+        log.info(JsonUtils.toJsonString(entity));
+        List<InlongClusterEntity> clusterEntities = clusterMapper.selectByKey(null, msg.getClusterName(),
+                msg.getComponentType());
+        Assertions.assertTrue(clusterEntities.size() == 1);
+        Assertions.assertTrue(clusterEntities.get(0).getName().equals(msg.getClusterName()));
+        int clusterId = clusterEntities.get(0).getId();

Review Comment:
   Pls add a blank line



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@inlong.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [inlong] kipshi commented on a diff in pull request #5332: [INLONG-5222][Manager][Agent][DataProxy] Add heartbeat mechanism for Inlong component cluster

Posted by GitBox <gi...@apache.org>.
kipshi commented on code in PR #5332:
URL: https://github.com/apache/inlong/pull/5332#discussion_r937380299


##########
inlong-agent/agent-core/src/main/java/org/apache/inlong/agent/core/HeartbeatManager.java:
##########
@@ -106,6 +176,50 @@ private TaskSnapshotRequest getHeartBeat() {
         return taskSnapshotRequest;
     }
 
+    /**
+     * build heartbeat message of agent
+     */
+    private HeartbeatMsg buildHeartbeatMsg() {
+        HeartbeatMsg heartbeatMsg = new HeartbeatMsg();
+        final String agentIp = AgentUtils.fetchLocalIp();
+        final int agentPort = conf.getInt(AGENT_HTTP_PORT, DEFAULT_AGENT_HTTP_PORT);
+        final String clusterName = conf.get(AGENT_CLUSTER_NAME);
+        final String clusterTag = conf.get(AGENT_CLUSTER_TAG);
+        heartbeatMsg.setIp(agentIp);
+        heartbeatMsg.setPort(agentPort);
+        heartbeatMsg.setComponentType(ComponentTypeEnum.Agent.getName());
+        heartbeatMsg.setReportTime(System.currentTimeMillis());
+        if (StringUtils.isNotBlank(clusterName)) {
+            heartbeatMsg.setClusterName(clusterName);
+        }
+        if (StringUtils.isNotBlank(clusterTag)) {
+            heartbeatMsg.setClusterTag(clusterTag);
+        }
+        Map<String, JobWrapper> jobWrapperMap = jobmanager.getJobs();

Review Comment:
   not necessary +3



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@inlong.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [inlong] healchow merged pull request #5332: [INLONG-5222][Manager][Agent][DataProxy] Add heartbeat mechanism for Inlong component cluster

Posted by GitBox <gi...@apache.org>.
healchow merged PR #5332:
URL: https://github.com/apache/inlong/pull/5332


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@inlong.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [inlong] kipshi commented on a diff in pull request #5332: [INLONG-5222][Manager][Agent][DataProxy] Add heartbeat mechanism for Inlong component cluster

Posted by GitBox <gi...@apache.org>.
kipshi commented on code in PR #5332:
URL: https://github.com/apache/inlong/pull/5332#discussion_r937379278


##########
inlong-manager/manager-service/src/main/java/org/apache/inlong/manager/service/core/heartbeat/HeartbeatManager.java:
##########
@@ -0,0 +1,180 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.inlong.manager.service.core.heartbeat;
+
+import com.github.benmanes.caffeine.cache.Cache;
+import com.github.benmanes.caffeine.cache.Caffeine;
+import com.github.benmanes.caffeine.cache.LoadingCache;
+import com.github.benmanes.caffeine.cache.RemovalCause;
+import lombok.Getter;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.inlong.common.heartbeat.AbstractHeartbeatManager;
+import org.apache.inlong.common.heartbeat.ComponentHeartbeat;
+import org.apache.inlong.common.heartbeat.HeartbeatMsg;
+import org.apache.inlong.manager.common.consts.InlongConstants;
+import org.apache.inlong.manager.common.enums.ClusterStatus;
+import org.apache.inlong.manager.common.enums.NodeStatus;
+import org.apache.inlong.manager.dao.entity.InlongClusterEntity;
+import org.apache.inlong.manager.dao.entity.InlongClusterNodeEntity;
+import org.apache.inlong.manager.dao.mapper.InlongClusterEntityMapper;
+import org.apache.inlong.manager.dao.mapper.InlongClusterNodeEntityMapper;
+import org.apache.inlong.manager.pojo.cluster.ClusterInfo;
+import org.apache.inlong.manager.pojo.cluster.ClusterNodeRequest;
+import org.apache.inlong.manager.pojo.user.UserRoleCode;
+import org.apache.inlong.manager.service.cluster.InlongClusterOperator;
+import org.apache.inlong.manager.service.cluster.InlongClusterOperatorFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.PostConstruct;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+@Component
+@Slf4j
+public class HeartbeatManager implements AbstractHeartbeatManager {
+
+    @Getter
+    private Cache<ComponentHeartbeat, HeartbeatMsg> heartbeats;

Review Comment:
   not necessary



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@inlong.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [inlong] kipshi commented on a diff in pull request #5332: [INLONG-5222][Manager][Agent][DataProxy] Add heartbeat mechanism for Inlong component cluster

Posted by GitBox <gi...@apache.org>.
kipshi commented on code in PR #5332:
URL: https://github.com/apache/inlong/pull/5332#discussion_r937385856


##########
inlong-manager/manager-service/src/test/java/org/apache/inlong/manager/service/core/impl/HeartbeatServiceTest.java:
##########
@@ -17,130 +17,62 @@
 
 package org.apache.inlong.manager.service.core.impl;
 
-import com.github.pagehelper.Page;
-import com.github.pagehelper.PageInfo;
-import org.apache.inlong.manager.pojo.heartbeat.ComponentHeartbeat;
-import org.apache.inlong.manager.pojo.heartbeat.ComponentHeartbeatResponse;
-import org.apache.inlong.manager.pojo.heartbeat.GroupHeartbeat;
-import org.apache.inlong.manager.pojo.heartbeat.GroupHeartbeatResponse;
-import org.apache.inlong.manager.pojo.heartbeat.HeartbeatPageRequest;
-import org.apache.inlong.manager.pojo.heartbeat.HeartbeatQueryRequest;
-import org.apache.inlong.manager.pojo.heartbeat.HeartbeatReportRequest;
-import org.apache.inlong.manager.pojo.heartbeat.StreamHeartbeat;
-import org.apache.inlong.manager.pojo.heartbeat.StreamHeartbeatResponse;
-import org.apache.inlong.manager.dao.entity.ComponentHeartbeatEntity;
-import org.apache.inlong.manager.dao.entity.GroupHeartbeatEntity;
-import org.apache.inlong.manager.dao.entity.StreamHeartbeatEntity;
+import com.google.common.collect.Maps;
+import org.apache.inlong.common.heartbeat.GroupHeartbeat;
+import org.apache.inlong.common.heartbeat.StreamHeartbeat;
+import org.apache.inlong.manager.common.util.JsonUtils;
 import org.apache.inlong.manager.dao.mapper.ComponentHeartbeatEntityMapper;
 import org.apache.inlong.manager.dao.mapper.GroupHeartbeatEntityMapper;
 import org.apache.inlong.manager.dao.mapper.StreamHeartbeatEntityMapper;
+import org.apache.inlong.manager.pojo.heartbeat.HeartbeatQueryRequest;
+import org.apache.inlong.manager.pojo.heartbeat.HeartbeatReportRequest;
+import org.apache.inlong.manager.pojo.heartbeat.StreamHeartbeatResponse;
+import org.apache.inlong.manager.service.ServiceBaseTest;
 import org.apache.inlong.manager.service.core.HeartbeatService;
 import org.junit.jupiter.api.Assertions;
-import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.Mockito;
-import org.mockito.MockitoAnnotations;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
 
 import java.time.Instant;
 import java.util.ArrayList;
 import java.util.List;
-
-import static org.mockito.BDDMockito.given;
+import java.util.Map;
 
 /**
  * Heartbeat service test.
  */
-public class HeartbeatServiceTest {
+@EnableAutoConfiguration
+public class HeartbeatServiceTest extends ServiceBaseTest {
 
-    @InjectMocks
-    private HeartbeatService heartbeatService = new HeartbeatServiceImpl();
-    @Mock
+    @Autowired
+    private HeartbeatService heartbeatService;
+    @Autowired
     private ComponentHeartbeatEntityMapper componentHeartbeatMapper;
-    @Mock
+    @Autowired
     private GroupHeartbeatEntityMapper groupHeartbeatMapper;
-    @Mock
+    @Autowired
     private StreamHeartbeatEntityMapper streamHeartbeatMapper;
 
-    /**
-     * setUp
-     */
-    @BeforeEach
-    public void setUp() {
-        MockitoAnnotations.openMocks(this);
-        ComponentHeartbeatEntity componentHeartbeat = new ComponentHeartbeatEntity();
-        componentHeartbeat.setComponent("Sort");
-        componentHeartbeat.setInstance("127.0.0.1");
-        componentHeartbeat.setStatusHeartbeat("[{\"status\":\"running\"}]");
-        componentHeartbeat.setMetricHeartbeat("[{\"mem\":\"16gb\",\"cpu\":\"60%\"}]");
-        componentHeartbeat.setReportTime(System.currentTimeMillis());
-        Page<ComponentHeartbeatEntity> componentPage = new Page<>();
-        componentPage.add(componentHeartbeat);
-        componentPage.setTotal(1);
-        given(componentHeartbeatMapper.insert(new ComponentHeartbeatEntity())).willReturn(1);
-        given(componentHeartbeatMapper.selectByKey(Mockito.anyString(),
-                Mockito.anyString())).willReturn(componentHeartbeat);
-        given(componentHeartbeatMapper.selectByCondition(Mockito.any())).willReturn(componentPage);
-
-        GroupHeartbeatEntity groupHeartbeat = new GroupHeartbeatEntity();
-        groupHeartbeat.setComponent("Sort");
-        groupHeartbeat.setInstance("127.0.0.1");
-        groupHeartbeat.setStatusHeartbeat("[{\"summaryMetric\":{\"totalRecordNumOfRead\""
-                + ": \"10\"},\"streamMetrics\":[{\"streamId\":\"stream1\"}]}]");
-        groupHeartbeat.setReportTime(System.currentTimeMillis());
-        groupHeartbeat.setMetricHeartbeat("[{\"summaryMetric\":{\"totalRecordNumOfRead\""
-                + ": \"10\"},"
-                + "\"streamMetrics\":[{\"streamId\":\"stream1\"}]}]");
-        Page<GroupHeartbeatEntity> groupPage = new Page<>();
-        groupPage.add(groupHeartbeat);
-        groupPage.setTotal(1);
-        given(groupHeartbeatMapper.selectByKey(Mockito.anyString(),
-                Mockito.anyString(), Mockito.anyString())).willReturn(groupHeartbeat);
-        given(groupHeartbeatMapper.selectByCondition(Mockito.any())).willReturn(groupPage);
-
-        StreamHeartbeatEntity streamHeartbeat = new StreamHeartbeatEntity();
-        streamHeartbeat.setComponent("Sort");
-        streamHeartbeat.setInstance("127.0.0.1");
-        streamHeartbeat.setInlongGroupId("group1");
-        streamHeartbeat.setInlongStreamId("test_test");
-        streamHeartbeat.setStatusHeartbeat("[{\"statue\":\"running\"}]");
-        streamHeartbeat.setMetricHeartbeat("[{\"outMsg\":\"1\",\"inMsg\":2}]");
-        streamHeartbeat.setReportTime(System.currentTimeMillis());
-
-        Page<StreamHeartbeatEntity> streamPage = new Page<>();
-        streamPage.add(streamHeartbeat);
-        streamPage.setTotal(1);
-
-        given(streamHeartbeatMapper.selectByKey(Mockito.anyString(),
-                Mockito.anyString(), Mockito.anyString(), Mockito.anyString()))
-                .willReturn(streamHeartbeat);
-        given(streamHeartbeatMapper.selectByCondition(Mockito.any())).willReturn(streamPage);
-    }
-
     @Test
     public void testReportHeartbeat() {
         HeartbeatReportRequest request = new HeartbeatReportRequest();
-        request.setComponent("Sort");
-        request.setInstance("127.0.0.1");
+        request.setComponentType("AGENT");

Review Comment:
   done



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@inlong.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [inlong] kipshi commented on a diff in pull request #5332: [INLONG-5222][Manager][Agent][DataProxy] Add heartbeat mechanism for Inlong component cluster

Posted by GitBox <gi...@apache.org>.
kipshi commented on code in PR #5332:
URL: https://github.com/apache/inlong/pull/5332#discussion_r937386563


##########
inlong-manager/manager-pojo/src/main/java/org/apache/inlong/manager/pojo/cluster/agent/AgentClusterRequest.java:
##########
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.inlong.manager.pojo.cluster.agent;
+
+import io.swagger.annotations.ApiModel;
+import lombok.Data;
+import lombok.EqualsAndHashCode;
+import lombok.ToString;
+import org.apache.inlong.manager.common.enums.ClusterType;
+import org.apache.inlong.manager.pojo.cluster.ClusterRequest;
+import org.apache.inlong.manager.common.util.JsonTypeDefine;
+
+/**
+ * Inlong cluster request for agent
+ */
+@Data
+@ToString(callSuper = true)
+@EqualsAndHashCode(callSuper = true)
+@JsonTypeDefine(value = ClusterType.DATAPROXY)
+@ApiModel("Inlong cluster request for DataProxy")

Review Comment:
   done



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@inlong.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [inlong] leosanqing commented on a diff in pull request #5332: [INLONG-5222][Manager][Agent][DataProxy] Add heartbeat mechanism for Inlong component cluster

Posted by GitBox <gi...@apache.org>.
leosanqing commented on code in PR #5332:
URL: https://github.com/apache/inlong/pull/5332#discussion_r936798412


##########
inlong-dataproxy/dataproxy-source/src/main/java/org/apache/inlong/dataproxy/heartbeat/HeartbeatManager.java:
##########
@@ -0,0 +1,150 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.inlong.dataproxy.heartbeat;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.http.client.config.RequestConfig;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClientBuilder;
+import org.apache.http.util.EntityUtils;
+import org.apache.inlong.common.enums.ComponentTypeEnum;
+import org.apache.inlong.common.heartbeat.AbstractHeartbeatManager;
+import org.apache.inlong.common.heartbeat.GroupHeartbeat;
+import org.apache.inlong.common.heartbeat.HeartbeatMsg;
+import org.apache.inlong.common.heartbeat.StreamHeartbeat;
+import org.apache.inlong.dataproxy.config.ConfigManager;
+import org.apache.inlong.dataproxy.consts.ConfigConstants;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.concurrent.TimeUnit;
+
+import static java.util.concurrent.TimeUnit.SECONDS;
+
+@Slf4j
+public class HeartbeatManager implements AbstractHeartbeatManager {
+
+    private CloseableHttpClient httpClient;
+    private Gson gson;
+
+    public HeartbeatManager() {
+        httpClient = constructHttpClient();
+        gson = new GsonBuilder().create();
+    }
+
+    public void start() {
+        Thread reportHeartbeatThread = new Thread(() -> {
+            while (true) {
+                HeartbeatMsg heartbeatMsg = buildHeartbeat();
+                reportHeartbeat(heartbeatMsg);
+                try {
+                    SECONDS.sleep(heartbeatInterval());
+                } catch (InterruptedException ex) {
+                    log.error("", ex);
+                }
+            }
+        });
+        reportHeartbeatThread.setDaemon(true);
+        reportHeartbeatThread.start();
+    }
+
+    @Override
+    public void reportHeartbeat(HeartbeatMsg heartbeat) {
+        ConfigManager configManager = ConfigManager.getInstance();
+        final String managerHost = configManager.getCommonProperties().get(ConfigConstants.MANAGER_HOST);
+        final String url =
+                "http://" + managerHost + ConfigConstants.MANAGER_PATH + ConfigConstants.MANAGER_HEARTBEAT_REPORT;
+        try {
+            HttpPost post = new HttpPost(url);
+            String body = gson.toJson(heartbeat);
+            StringEntity stringEntity = new StringEntity(body);
+            stringEntity.setContentType("application/json");
+            post.setEntity(stringEntity);
+            CloseableHttpResponse response = httpClient.execute(post);
+            String isSuccess = EntityUtils.toString(response.getEntity());
+            if (StringUtils.isNotEmpty(isSuccess)
+                    && response.getStatusLine().getStatusCode() == 200) {
+                if (log.isDebugEnabled()) {
+                    log.debug("reportHeartbeat url {}, heartbeat: {}, return str {}", url, body, isSuccess);
+                }
+            }
+        } catch (Exception ex) {
+            log.error("reportHeartbeat failed for url {}", url, ex);
+        }
+    }
+
+    private synchronized CloseableHttpClient constructHttpClient() {
+        long timeoutInMs = TimeUnit.MILLISECONDS.toMillis(50000);
+        RequestConfig requestConfig = RequestConfig.custom()
+                .setConnectTimeout((int) timeoutInMs)
+                .setSocketTimeout((int) timeoutInMs).build();
+        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
+        httpClientBuilder.setDefaultRequestConfig(requestConfig);
+        return httpClientBuilder.build();
+    }
+
+    private HeartbeatMsg buildHeartbeat() {
+        ConfigManager configManager = ConfigManager.getInstance();
+        HeartbeatMsg heartbeatMsg = new HeartbeatMsg();
+        Map<String, String> commonProperties = configManager.getCommonProperties();
+        String localIp = commonProperties.get(ConfigConstants.PROXY_LOCAL_IP);
+        heartbeatMsg.setIp(localIp);
+        heartbeatMsg.setComponentType(ComponentTypeEnum.DataProxy.getName());
+        heartbeatMsg.setReportTime(System.currentTimeMillis());
+        Map<String, String> groupIdMappings = configManager.getGroupIdMappingProperties();
+        Map<String, Map<String, String>> streamIdMappings = configManager.getStreamIdMappingProperties();
+        Map<String, String> groupIdEnableMappings = configManager.getGroupIdEnableMappingProperties();
+        List<GroupHeartbeat> groupHeartbeats = new ArrayList<>();
+        for (Entry<String, String> entry : groupIdMappings.entrySet()) {
+            String groupIdNum = entry.getKey();
+            String groupId = entry.getValue();
+            GroupHeartbeat groupHeartbeat = new GroupHeartbeat();
+            groupHeartbeat.setInlongGroupId(groupId);
+            String status = groupIdEnableMappings.getOrDefault(groupIdNum, "disabled");
+            status = status.equals("TRUE") ? "enabled" : "disabled";
+            groupHeartbeat.setStatus(status);
+            groupHeartbeats.add(groupHeartbeat);
+        }
+        heartbeatMsg.setGroupHeartbeats(groupHeartbeats);
+        List<StreamHeartbeat> streamHeartbeats = new ArrayList<>();

Review Comment:
   add blank line



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@inlong.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [inlong] kipshi commented on a diff in pull request #5332: [INLONG-5222][Manager][Agent][DataProxy] Add heartbeat mechanism for Inlong component cluster

Posted by GitBox <gi...@apache.org>.
kipshi commented on code in PR #5332:
URL: https://github.com/apache/inlong/pull/5332#discussion_r937393005


##########
pom.xml:
##########
@@ -1553,6 +1553,11 @@
                 <artifactId>dlc-data-catalog-metastore-client</artifactId>
                 <version>${dlc.client.version}</version>
             </dependency>
+            <dependency>

Review Comment:
   not necessary+15



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@inlong.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [inlong] leosanqing commented on a diff in pull request #5332: [INLONG-5222][Manager][Agent][DataProxy] Add heartbeat mechanism for Inlong component cluster

Posted by GitBox <gi...@apache.org>.
leosanqing commented on code in PR #5332:
URL: https://github.com/apache/inlong/pull/5332#discussion_r936816330


##########
inlong-manager/manager-service/src/test/java/org/apache/inlong/manager/service/core/heartbeat/HeartbeatManagerTest.java:
##########
@@ -0,0 +1,89 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.inlong.manager.service.core.heartbeat;
+
+import lombok.extern.slf4j.Slf4j;
+import org.apache.inlong.common.enums.ComponentTypeEnum;
+import org.apache.inlong.common.heartbeat.HeartbeatMsg;
+import org.apache.inlong.manager.common.enums.NodeStatus;
+import org.apache.inlong.manager.pojo.cluster.ClusterNodeRequest;
+import org.apache.inlong.manager.common.util.JsonUtils;
+import org.apache.inlong.manager.dao.entity.InlongClusterEntity;
+import org.apache.inlong.manager.dao.entity.InlongClusterNodeEntity;
+import org.apache.inlong.manager.dao.mapper.InlongClusterEntityMapper;
+import org.apache.inlong.manager.dao.mapper.InlongClusterNodeEntityMapper;
+import org.apache.inlong.manager.service.ServiceBaseTest;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
+
+import java.util.List;
+
+@EnableAutoConfiguration
+@Slf4j
+public class HeartbeatManagerTest extends ServiceBaseTest {
+
+    @Autowired
+    HeartbeatManager heartbeatManager;
+
+    @Autowired
+    InlongClusterEntityMapper clusterMapper;
+
+    @Autowired
+    InlongClusterNodeEntityMapper clusterNodeMapper;
+
+    @Test
+    void testReportHeartbeat() throws InterruptedException {
+        HeartbeatMsg msg = createHeartbeatMsg();
+        heartbeatManager.reportHeartbeat(msg);
+        InlongClusterEntity entity = clusterMapper.selectById(1);
+        log.info(JsonUtils.toJsonString(entity));
+        List<InlongClusterEntity> clusterEntities = clusterMapper.selectByKey(null, msg.getClusterName(),
+                msg.getComponentType());
+        Assertions.assertTrue(clusterEntities.size() == 1);
+        Assertions.assertTrue(clusterEntities.get(0).getName().equals(msg.getClusterName()));
+        int clusterId = clusterEntities.get(0).getId();
+        ClusterNodeRequest nodeRequest = new ClusterNodeRequest();
+        nodeRequest.setParentId(clusterId);
+        nodeRequest.setType(msg.getComponentType());
+        nodeRequest.setIp(msg.getIp());
+        nodeRequest.setPort(msg.getPort());
+        InlongClusterNodeEntity clusterNode = clusterNodeMapper.selectByUniqueKey(nodeRequest);
+        Assertions.assertTrue(clusterNode != null);
+        Assertions.assertTrue(clusterNode.getStatus() == NodeStatus.NORMAL.getStatus());
+        heartbeatManager.getHeartbeats().invalidateAll();
+        Thread.sleep(1000);
+        clusterNode = clusterNodeMapper.selectByUniqueKey(nodeRequest);
+        log.debug(JsonUtils.toJsonString(clusterNode));
+        Assertions.assertTrue(clusterNode.getStatus() == NodeStatus.HEARTBEAT_TIMEOUT.getStatus());

Review Comment:
   clould use assertEquals()



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@inlong.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [inlong] healchow commented on a diff in pull request #5332: [INLONG-5223][Manager][Agent][Dataproxy] Add heartbeat Mechanism for Inlong component cluster

Posted by GitBox <gi...@apache.org>.
healchow commented on code in PR #5332:
URL: https://github.com/apache/inlong/pull/5332#discussion_r935518220


##########
inlong-agent/agent-common/src/main/java/org/apache/inlong/agent/constant/FetcherConstants.java:
##########
@@ -53,12 +53,13 @@ public class FetcherConstants {
     public static final String AGENT_MANAGER_REPORTSNAPSHOT_HTTP_PATH = "agent.manager.reportsnapshot.http.path";
     public static final String DEFAULT_AGENT_MANAGER_REPORTSNAPSHOT_HTTP_PATH = "/agent/reportSnapshot";
 
+    public static final String AGENT_MANAGER_HEARTBEAT_HTTP_PATH = "agent.manager.heartbeat.http.path";
+    public static final String DEFAULT_AGENT_MANAGER_HEARTBEAT_HTTP_PATH = "/openapi/heartbeat/report";

Review Comment:
   The `AGENT_MANAGER_VIP_HTTP_PREFIX_PATH` already contains `/openapi`, so there may not need `/openapi` again.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@inlong.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [inlong] GanfengTan commented on pull request #5332: [INLONG-5223][Manager] Add heartbeat Mechanism for Inlong component cluster

Posted by GitBox <gi...@apache.org>.
GanfengTan commented on PR #5332:
URL: https://github.com/apache/inlong/pull/5332#issuecomment-1202276293

   @kipshi Please, update your title becuse the PR for multiple modules.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@inlong.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [inlong] kipshi commented on a diff in pull request #5332: [INLONG-5222][Manager][Agent][DataProxy] Add heartbeat mechanism for Inlong component cluster

Posted by GitBox <gi...@apache.org>.
kipshi commented on code in PR #5332:
URL: https://github.com/apache/inlong/pull/5332#discussion_r937382050


##########
inlong-manager/manager-service/src/main/java/org/apache/inlong/manager/service/core/heartbeat/HeartbeatManager.java:
##########
@@ -0,0 +1,180 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.inlong.manager.service.core.heartbeat;
+
+import com.github.benmanes.caffeine.cache.Cache;
+import com.github.benmanes.caffeine.cache.Caffeine;
+import com.github.benmanes.caffeine.cache.LoadingCache;
+import com.github.benmanes.caffeine.cache.RemovalCause;
+import lombok.Getter;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.inlong.common.heartbeat.AbstractHeartbeatManager;
+import org.apache.inlong.common.heartbeat.ComponentHeartbeat;
+import org.apache.inlong.common.heartbeat.HeartbeatMsg;
+import org.apache.inlong.manager.common.consts.InlongConstants;
+import org.apache.inlong.manager.common.enums.ClusterStatus;
+import org.apache.inlong.manager.common.enums.NodeStatus;
+import org.apache.inlong.manager.dao.entity.InlongClusterEntity;
+import org.apache.inlong.manager.dao.entity.InlongClusterNodeEntity;
+import org.apache.inlong.manager.dao.mapper.InlongClusterEntityMapper;
+import org.apache.inlong.manager.dao.mapper.InlongClusterNodeEntityMapper;
+import org.apache.inlong.manager.pojo.cluster.ClusterInfo;
+import org.apache.inlong.manager.pojo.cluster.ClusterNodeRequest;
+import org.apache.inlong.manager.pojo.user.UserRoleCode;
+import org.apache.inlong.manager.service.cluster.InlongClusterOperator;
+import org.apache.inlong.manager.service.cluster.InlongClusterOperatorFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import javax.annotation.PostConstruct;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+@Component
+@Slf4j
+public class HeartbeatManager implements AbstractHeartbeatManager {
+
+    @Getter
+    private Cache<ComponentHeartbeat, HeartbeatMsg> heartbeats;
+
+    @Getter
+    private LoadingCache<ComponentHeartbeat, ClusterInfo> clusterInfos;

Review Comment:
   not necessary



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@inlong.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [inlong] kipshi commented on a diff in pull request #5332: [INLONG-5222][Manager][Agent][DataProxy] Add heartbeat mechanism for Inlong component cluster

Posted by GitBox <gi...@apache.org>.
kipshi commented on code in PR #5332:
URL: https://github.com/apache/inlong/pull/5332#discussion_r937378947


##########
inlong-dataproxy/dataproxy-source/src/main/java/org/apache/inlong/dataproxy/heartbeat/HeartbeatManager.java:
##########
@@ -0,0 +1,150 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.inlong.dataproxy.heartbeat;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.http.client.config.RequestConfig;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClientBuilder;
+import org.apache.http.util.EntityUtils;
+import org.apache.inlong.common.enums.ComponentTypeEnum;
+import org.apache.inlong.common.heartbeat.AbstractHeartbeatManager;
+import org.apache.inlong.common.heartbeat.GroupHeartbeat;
+import org.apache.inlong.common.heartbeat.HeartbeatMsg;
+import org.apache.inlong.common.heartbeat.StreamHeartbeat;
+import org.apache.inlong.dataproxy.config.ConfigManager;
+import org.apache.inlong.dataproxy.consts.ConfigConstants;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.concurrent.TimeUnit;
+
+import static java.util.concurrent.TimeUnit.SECONDS;
+
+@Slf4j
+public class HeartbeatManager implements AbstractHeartbeatManager {
+
+    private CloseableHttpClient httpClient;
+    private Gson gson;
+
+    public HeartbeatManager() {
+        httpClient = constructHttpClient();
+        gson = new GsonBuilder().create();
+    }
+
+    public void start() {
+        Thread reportHeartbeatThread = new Thread(() -> {
+            while (true) {
+                HeartbeatMsg heartbeatMsg = new HeartbeatMsg();
+                reportHeartbeat(heartbeatMsg);
+                try {
+                    SECONDS.sleep(heartbeatInterval());
+                } catch (InterruptedException ex) {
+                    log.error("", ex);

Review Comment:
   not necessary



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@inlong.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [inlong] EMsnap commented on a diff in pull request #5332: [INLONG-5223][Manager] Add heartbeat Mechanism for Inlong component cluster

Posted by GitBox <gi...@apache.org>.
EMsnap commented on code in PR #5332:
URL: https://github.com/apache/inlong/pull/5332#discussion_r935345978


##########
inlong-dataproxy/dataproxy-source/src/main/java/org/apache/inlong/dataproxy/heartbeat/HeartbeatManager.java:
##########
@@ -0,0 +1,150 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.inlong.dataproxy.heartbeat;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.http.client.config.RequestConfig;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClientBuilder;
+import org.apache.http.util.EntityUtils;
+import org.apache.inlong.common.enums.ComponentTypeEnum;
+import org.apache.inlong.common.heartbeat.AbstractHeartbeatManager;
+import org.apache.inlong.common.heartbeat.GroupHeartbeat;
+import org.apache.inlong.common.heartbeat.HeartbeatMsg;
+import org.apache.inlong.common.heartbeat.StreamHeartbeat;
+import org.apache.inlong.dataproxy.config.ConfigManager;
+import org.apache.inlong.dataproxy.consts.ConfigConstants;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.concurrent.TimeUnit;
+
+import static java.util.concurrent.TimeUnit.SECONDS;
+
+@Slf4j
+public class HeartbeatManager implements AbstractHeartbeatManager {
+
+    private CloseableHttpClient httpClient;
+    private Gson gson;
+
+    public HeartbeatManager() {
+        httpClient = constructHttpClient();
+        gson = new GsonBuilder().create();
+    }
+
+    public void start() {
+        Thread reportHeartbeatThread = new Thread(() -> {
+            while (true) {
+                HeartbeatMsg heartbeatMsg = new HeartbeatMsg();
+                reportHeartbeat(heartbeatMsg);
+                try {
+                    SECONDS.sleep(heartbeatInterval());
+                } catch (InterruptedException ex) {
+                    log.error("", ex);

Review Comment:
   pls add description 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@inlong.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [inlong] kipshi commented on a diff in pull request #5332: [INLONG-5222][Manager][Agent][DataProxy] Add heartbeat mechanism for Inlong component cluster

Posted by GitBox <gi...@apache.org>.
kipshi commented on code in PR #5332:
URL: https://github.com/apache/inlong/pull/5332#discussion_r936436898


##########
inlong-agent/agent-core/src/main/java/org/apache/inlong/agent/core/HeartbeatManager.java:
##########
@@ -70,13 +88,65 @@ public HeartbeatManager(AgentManager agentManager) {
         jobmanager = agentManager.getJobManager();
         httpManager = new HttpManager(conf);
         baseManagerUrl = buildBaseUrl();
-        reportSnapshotUrl = builReportSnapShotUrl(baseManagerUrl);
+        reportSnapshotUrl = buildReportSnapShotUrl(baseManagerUrl);
+        reportHeartbeatUrl = buildReportHeartbeatUrl();
+    }
+
+    @Override
+    public void start() throws Exception {
+        submitWorker(snapshotReportThread());
+        submitWorker(heartbeatReportThread());
+    }
+
+    private Runnable snapshotReportThread() {
+        return () -> {
+            while (isRunnable()) {
+                try {
+                    TaskSnapshotRequest taskSnapshotRequest = buildTaskSnapshotRequest();
+                    httpManager.doSentPost(reportSnapshotUrl, taskSnapshotRequest);
+                    if (LOGGER.isDebugEnabled()) {
+                        LOGGER.debug(" {} report to manager", taskSnapshotRequest);
+                    }
+                    int heartbeatInterval = conf.getInt(AGENT_HEARTBEAT_INTERVAL,

Review Comment:
   I think it is



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@inlong.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [inlong] kipshi commented on a diff in pull request #5332: [INLONG-5222][Manager][Agent][DataProxy] Add heartbeat mechanism for Inlong component cluster

Posted by GitBox <gi...@apache.org>.
kipshi commented on code in PR #5332:
URL: https://github.com/apache/inlong/pull/5332#discussion_r937379553


##########
inlong-agent/agent-core/src/main/java/org/apache/inlong/agent/core/HeartbeatManager.java:
##########
@@ -106,6 +176,50 @@ private TaskSnapshotRequest getHeartBeat() {
         return taskSnapshotRequest;
     }
 
+    /**
+     * build heartbeat message of agent
+     */
+    private HeartbeatMsg buildHeartbeatMsg() {
+        HeartbeatMsg heartbeatMsg = new HeartbeatMsg();
+        final String agentIp = AgentUtils.fetchLocalIp();
+        final int agentPort = conf.getInt(AGENT_HTTP_PORT, DEFAULT_AGENT_HTTP_PORT);
+        final String clusterName = conf.get(AGENT_CLUSTER_NAME);
+        final String clusterTag = conf.get(AGENT_CLUSTER_TAG);
+        heartbeatMsg.setIp(agentIp);
+        heartbeatMsg.setPort(agentPort);
+        heartbeatMsg.setComponentType(ComponentTypeEnum.Agent.getName());
+        heartbeatMsg.setReportTime(System.currentTimeMillis());
+        if (StringUtils.isNotBlank(clusterName)) {
+            heartbeatMsg.setClusterName(clusterName);
+        }
+        if (StringUtils.isNotBlank(clusterTag)) {
+            heartbeatMsg.setClusterTag(clusterTag);
+        }
+        Map<String, JobWrapper> jobWrapperMap = jobmanager.getJobs();
+        List<GroupHeartbeat> groupHeartbeats = Lists.newArrayList();
+        List<StreamHeartbeat> streamHeartbeats = Lists.newArrayList();
+        jobWrapperMap.values().stream().forEach(jobWrapper -> {
+            Job job = jobWrapper.getJob();
+            JobProfile jobProfile = job.getJobConf();
+            final String groupId = jobProfile.get(JOB_GROUP_ID);
+            final String streamId = jobProfile.get(JOB_STREAM_ID);
+            State currentState = jobWrapper.getCurrentState();
+            String status = currentState.name();
+            GroupHeartbeat groupHeartbeat = new GroupHeartbeat();
+            groupHeartbeat.setInlongGroupId(groupId);
+            groupHeartbeat.setStatus(status);
+            groupHeartbeats.add(groupHeartbeat);
+            StreamHeartbeat streamHeartbeat = new StreamHeartbeat();

Review Comment:
   not necessary +2 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@inlong.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [inlong] haibo-duan commented on a diff in pull request #5332: [INLONG-5222][Manager][Agent][DataProxy] Add heartbeat mechanism for Inlong component cluster

Posted by GitBox <gi...@apache.org>.
haibo-duan commented on code in PR #5332:
URL: https://github.com/apache/inlong/pull/5332#discussion_r936337763


##########
inlong-agent/agent-core/src/main/java/org/apache/inlong/agent/core/HeartbeatManager.java:
##########
@@ -70,13 +88,65 @@ public HeartbeatManager(AgentManager agentManager) {
         jobmanager = agentManager.getJobManager();
         httpManager = new HttpManager(conf);
         baseManagerUrl = buildBaseUrl();
-        reportSnapshotUrl = builReportSnapShotUrl(baseManagerUrl);
+        reportSnapshotUrl = buildReportSnapShotUrl(baseManagerUrl);
+        reportHeartbeatUrl = buildReportHeartbeatUrl();
+    }
+
+    @Override
+    public void start() throws Exception {
+        submitWorker(snapshotReportThread());
+        submitWorker(heartbeatReportThread());
+    }
+
+    private Runnable snapshotReportThread() {
+        return () -> {
+            while (isRunnable()) {
+                try {
+                    TaskSnapshotRequest taskSnapshotRequest = buildTaskSnapshotRequest();
+                    httpManager.doSentPost(reportSnapshotUrl, taskSnapshotRequest);
+                    if (LOGGER.isDebugEnabled()) {
+                        LOGGER.debug(" {} report to manager", taskSnapshotRequest);
+                    }
+                    int heartbeatInterval = conf.getInt(AGENT_HEARTBEAT_INTERVAL,

Review Comment:
   the variable 'heartbeatInterval' is only used once. I don't think it is necessary to define the variable.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@inlong.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [inlong] leosanqing commented on a diff in pull request #5332: [INLONG-5222][Manager][Agent][DataProxy] Add heartbeat mechanism for Inlong component cluster

Posted by GitBox <gi...@apache.org>.
leosanqing commented on code in PR #5332:
URL: https://github.com/apache/inlong/pull/5332#discussion_r936751297


##########
inlong-agent/agent-core/src/main/java/org/apache/inlong/agent/core/HeartbeatManager.java:
##########
@@ -106,6 +176,50 @@ private TaskSnapshotRequest getHeartBeat() {
         return taskSnapshotRequest;
     }
 
+    /**
+     * build heartbeat message of agent
+     */
+    private HeartbeatMsg buildHeartbeatMsg() {
+        HeartbeatMsg heartbeatMsg = new HeartbeatMsg();
+        final String agentIp = AgentUtils.fetchLocalIp();
+        final int agentPort = conf.getInt(AGENT_HTTP_PORT, DEFAULT_AGENT_HTTP_PORT);
+        final String clusterName = conf.get(AGENT_CLUSTER_NAME);
+        final String clusterTag = conf.get(AGENT_CLUSTER_TAG);
+        heartbeatMsg.setIp(agentIp);
+        heartbeatMsg.setPort(agentPort);
+        heartbeatMsg.setComponentType(ComponentTypeEnum.Agent.getName());
+        heartbeatMsg.setReportTime(System.currentTimeMillis());
+        if (StringUtils.isNotBlank(clusterName)) {
+            heartbeatMsg.setClusterName(clusterName);
+        }
+        if (StringUtils.isNotBlank(clusterTag)) {
+            heartbeatMsg.setClusterTag(clusterTag);
+        }
+        Map<String, JobWrapper> jobWrapperMap = jobmanager.getJobs();
+        List<GroupHeartbeat> groupHeartbeats = Lists.newArrayList();
+        List<StreamHeartbeat> streamHeartbeats = Lists.newArrayList();
+        jobWrapperMap.values().stream().forEach(jobWrapper -> {
+            Job job = jobWrapper.getJob();
+            JobProfile jobProfile = job.getJobConf();
+            final String groupId = jobProfile.get(JOB_GROUP_ID);
+            final String streamId = jobProfile.get(JOB_STREAM_ID);
+            State currentState = jobWrapper.getCurrentState();
+            String status = currentState.name();
+            GroupHeartbeat groupHeartbeat = new GroupHeartbeat();
+            groupHeartbeat.setInlongGroupId(groupId);
+            groupHeartbeat.setStatus(status);
+            groupHeartbeats.add(groupHeartbeat);
+            StreamHeartbeat streamHeartbeat = new StreamHeartbeat();

Review Comment:
   It is better to have a blank line between the fields of the group and the fields of the stream, for readability



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@inlong.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [inlong] kipshi commented on a diff in pull request #5332: [INLONG-5222][Manager][Agent][DataProxy] Add heartbeat mechanism for Inlong component cluster

Posted by GitBox <gi...@apache.org>.
kipshi commented on code in PR #5332:
URL: https://github.com/apache/inlong/pull/5332#discussion_r936422711


##########
inlong-agent/agent-common/src/main/java/org/apache/inlong/agent/constant/FetcherConstants.java:
##########
@@ -53,12 +53,13 @@ public class FetcherConstants {
     public static final String AGENT_MANAGER_REPORTSNAPSHOT_HTTP_PATH = "agent.manager.reportsnapshot.http.path";
     public static final String DEFAULT_AGENT_MANAGER_REPORTSNAPSHOT_HTTP_PATH = "/agent/reportSnapshot";
 
+    public static final String AGENT_MANAGER_HEARTBEAT_HTTP_PATH = "agent.manager.heartbeat.http.path";
+    public static final String DEFAULT_AGENT_MANAGER_HEARTBEAT_HTTP_PATH = "/openapi/heartbeat/report";

Review Comment:
   done



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@inlong.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


[GitHub] [inlong] kipshi commented on a diff in pull request #5332: [INLONG-5223][Manager] Add heartbeat Mechanism for Inlong component cluster

Posted by GitBox <gi...@apache.org>.
kipshi commented on code in PR #5332:
URL: https://github.com/apache/inlong/pull/5332#discussion_r935472570


##########
inlong-dataproxy/dataproxy-source/src/main/java/org/apache/inlong/dataproxy/heartbeat/HeartbeatManager.java:
##########
@@ -0,0 +1,150 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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 org.apache.inlong.dataproxy.heartbeat;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.http.client.config.RequestConfig;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClientBuilder;
+import org.apache.http.util.EntityUtils;
+import org.apache.inlong.common.enums.ComponentTypeEnum;
+import org.apache.inlong.common.heartbeat.AbstractHeartbeatManager;
+import org.apache.inlong.common.heartbeat.GroupHeartbeat;
+import org.apache.inlong.common.heartbeat.HeartbeatMsg;
+import org.apache.inlong.common.heartbeat.StreamHeartbeat;
+import org.apache.inlong.dataproxy.config.ConfigManager;
+import org.apache.inlong.dataproxy.consts.ConfigConstants;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.concurrent.TimeUnit;
+
+import static java.util.concurrent.TimeUnit.SECONDS;
+
+@Slf4j
+public class HeartbeatManager implements AbstractHeartbeatManager {
+
+    private CloseableHttpClient httpClient;
+    private Gson gson;
+
+    public HeartbeatManager() {
+        httpClient = constructHttpClient();
+        gson = new GsonBuilder().create();
+    }
+
+    public void start() {
+        Thread reportHeartbeatThread = new Thread(() -> {
+            while (true) {
+                HeartbeatMsg heartbeatMsg = new HeartbeatMsg();
+                reportHeartbeat(heartbeatMsg);
+                try {
+                    SECONDS.sleep(heartbeatInterval());
+                } catch (InterruptedException ex) {
+                    log.error("", ex);

Review Comment:
   interruptException need no description



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@inlong.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org