baomingyu commented on code in PR #9929:
URL: https://github.com/apache/inlong/pull/9929#discussion_r1554827785


##########
inlong-audit/audit-service/src/main/java/elector/impl/ElectorImpl.java:
##########
@@ -0,0 +1,198 @@
+/*
+ * 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 elector.impl;
+
+import elector.api.Elector;
+import elector.api.ElectorConfig;
+import elector.task.DBMonitorTask;
+import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Random;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Elector Impl
+ */
+public class ElectorImpl extends Elector {
+
+    private static final Logger logger = 
LoggerFactory.getLogger(ElectorImpl.class);
+    private final ElectorConfig electorConfig;
+    private ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
+    private boolean canElector = true;
+    private DBDataSource dbDataSource;
+    private long sleepTime = 0L;
+
+    public ElectorImpl(ElectorConfig electorConfig) {
+        this.electorConfig = electorConfig;
+        this.dbDataSource = new DBDataSource(electorConfig);
+    }
+
+    /**
+     * init
+     *
+     * @throws Exception
+     */
+    public void init() throws Exception {
+        try {
+            logger.info("Init elector impl...");
+
+            dbDataSource.init(false);
+
+            ElectorWorkerThread electorWorkerThread = new 
ElectorWorkerThread();
+            fixedThreadPool.execute(electorWorkerThread);
+
+            DBMonitorTask dbMonitorTask = new DBMonitorTask(electorConfig, 
dbDataSource);
+            fixedThreadPool.execute(dbMonitorTask);
+        } catch (Exception exception) {
+            logger.error("Exception :{}", exception.getMessage());
+        }
+    }
+
+    /**
+     * Judge where is leader
+     *
+     * @return
+     */
+    public boolean isLeader() {
+        return this.isLeader;
+    }
+
+    /**
+     * Release leader
+     */
+    public void releaseLeader() {
+        if (this.isLeader)
+            try {
+                dbDataSource.releaseLeader();
+            } catch (Exception exception) {
+                logger.error("Exception :{}", exception.getMessage());
+            }
+
+        try {
+            TimeUnit.SECONDS.sleep(40L);
+        } catch (Exception exception) {
+            logger.error("Exception :{}", exception.getMessage());
+        }
+    }
+
+    /**
+     * Replace leader
+     *
+     * @param newLeaderId
+     */
+    public void replaceLeader(String newLeaderId) {
+        sleepTime = (electorConfig.getTryToBeLeaderInterval() * 2);
+        dbDataSource.replaceLeader(newLeaderId);
+    }
+
+    /**
+     * Get leader
+     *
+     * @param serviceId
+     * @return
+     */
+    public String getLeader(String serviceId) {
+        return dbDataSource.getCurrentLeader();
+    }
+
+    /**
+     * Judge where can be elector
+     *
+     * @param canElector
+     */
+    public void canElector(boolean canElector) {
+        this.canElector = canElector;
+    }
+
+    /**
+     * Rebuild elector DBSource
+     *
+     * @return
+     */
+    public boolean reBuildElectorDBSource() {
+        canElector(false);
+        try {
+            releaseLeader();
+            dbDataSource.close();
+            dbDataSource.init(true);
+            canElector(true);
+        } catch (Exception exception) {
+            logger.error("Exception :{}", exception.getMessage());
+            return false;
+        }
+        return true;
+    }
+
+    /**
+     * close
+     *
+     * @return
+     */
+    public boolean close() {
+        return false;
+    }
+
+    class ElectorWorkerThread implements Runnable {
+
+        Random random;
+
+        ElectorWorkerThread() {
+            this.random = new Random();
+        }
+
+        public void run() {
+            while (true) {
+                if (canElector) {
+                    dbDataSource.leaderSelector();
+                }
+
+                String leaderId = dbDataSource.getCurrentLeader();
+                if (!StringUtils.isEmpty(leaderId)) {

Review Comment:
   can use isNotEmpty()



##########
inlong-audit/audit-service/src/main/java/elector/impl/ElectorImpl.java:
##########
@@ -0,0 +1,198 @@
+/*
+ * 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 elector.impl;
+
+import elector.api.Elector;
+import elector.api.ElectorConfig;
+import elector.task.DBMonitorTask;
+import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Random;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Elector Impl
+ */
+public class ElectorImpl extends Elector {
+
+    private static final Logger logger = 
LoggerFactory.getLogger(ElectorImpl.class);
+    private final ElectorConfig electorConfig;
+    private ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
+    private boolean canElector = true;
+    private DBDataSource dbDataSource;
+    private long sleepTime = 0L;
+
+    public ElectorImpl(ElectorConfig electorConfig) {
+        this.electorConfig = electorConfig;
+        this.dbDataSource = new DBDataSource(electorConfig);
+    }
+
+    /**
+     * init
+     *
+     * @throws Exception
+     */
+    public void init() throws Exception {
+        try {
+            logger.info("Init elector impl...");
+
+            dbDataSource.init(false);
+
+            ElectorWorkerThread electorWorkerThread = new 
ElectorWorkerThread();
+            fixedThreadPool.execute(electorWorkerThread);
+
+            DBMonitorTask dbMonitorTask = new DBMonitorTask(electorConfig, 
dbDataSource);
+            fixedThreadPool.execute(dbMonitorTask);
+        } catch (Exception exception) {
+            logger.error("Exception :{}", exception.getMessage());
+        }
+    }
+
+    /**
+     * Judge where is leader
+     *
+     * @return
+     */
+    public boolean isLeader() {
+        return this.isLeader;
+    }
+
+    /**
+     * Release leader
+     */
+    public void releaseLeader() {
+        if (this.isLeader)
+            try {
+                dbDataSource.releaseLeader();
+            } catch (Exception exception) {
+                logger.error("Exception :{}", exception.getMessage());
+            }
+
+        try {
+            TimeUnit.SECONDS.sleep(40L);
+        } catch (Exception exception) {
+            logger.error("Exception :{}", exception.getMessage());
+        }
+    }
+
+    /**
+     * Replace leader
+     *
+     * @param newLeaderId
+     */
+    public void replaceLeader(String newLeaderId) {
+        sleepTime = (electorConfig.getTryToBeLeaderInterval() * 2);
+        dbDataSource.replaceLeader(newLeaderId);
+    }
+
+    /**
+     * Get leader
+     *
+     * @param serviceId
+     * @return
+     */
+    public String getLeader(String serviceId) {
+        return dbDataSource.getCurrentLeader();
+    }
+
+    /**
+     * Judge where can be elector
+     *
+     * @param canElector
+     */
+    public void canElector(boolean canElector) {
+        this.canElector = canElector;
+    }
+
+    /**
+     * Rebuild elector DBSource
+     *
+     * @return
+     */
+    public boolean reBuildElectorDBSource() {
+        canElector(false);
+        try {
+            releaseLeader();
+            dbDataSource.close();
+            dbDataSource.init(true);
+            canElector(true);
+        } catch (Exception exception) {
+            logger.error("Exception :{}", exception.getMessage());
+            return false;
+        }
+        return true;
+    }
+
+    /**
+     * close
+     *
+     * @return
+     */
+    public boolean close() {
+        return false;
+    }
+
+    class ElectorWorkerThread implements Runnable {
+
+        Random random;
+
+        ElectorWorkerThread() {
+            this.random = new Random();
+        }
+
+        public void run() {
+            while (true) {
+                if (canElector) {

Review Comment:
   suggest use try {} catch() {} all while logic avoid any exception to select 
leader logic loss



##########
inlong-audit/audit-service/src/main/java/elector/impl/DBDataSource.java:
##########
@@ -0,0 +1,307 @@
+/*
+ * 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 elector.impl;
+
+import com.zaxxer.hikari.HikariConfig;
+import com.zaxxer.hikari.HikariDataSource;
+import elector.api.ElectorConfig;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.text.MessageFormat;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * DB data source
+ */
+public class DBDataSource {
+
+    private static final Logger logger = 
LoggerFactory.getLogger(DBDataSource.class);
+    private String electorSql =
+            "insert ignore into {0} (service_id, leader_id, last_seen_active) 
values (''{1}'', ''{2}'', now()) on duplicate key update leader_id = 
if(last_seen_active < now() - interval # second, values(leader_id), 
leader_id),last_seen_active = if(leader_id = values(leader_id), 
values(last_seen_active), last_seen_active)";
+    private String replaceLeaderSql =
+            "replace into {0} (\n   service_id, leader_id, last_seen_active 
)\nvalues (''{1}'', ''#'', now())";
+    private String reLeaseSql = "delete from {0} where service_id=''{1}'' and 
leader_id= ''{2}''";
+    private String isLeaderSql = "select count(*) as is_leader from {0} where 
service_id=''{1}'' and leader_id=''{2}''";
+    private String searchCurrentLeaderSql = "select leader_id as leader from 
{0} where service_id=''{1}''";
+    private ElectorConfig electorConfig;
+    private HikariDataSource datasource;
+    public AtomicInteger getConnectionFailTimes;
+
+    public DBDataSource(ElectorConfig electorConfig) {
+        this.electorConfig = electorConfig;
+        this.getConnectionFailTimes = new AtomicInteger(0);
+    }
+
+    /**
+     * init
+     *
+     * @param reBuildDataSource
+     * @throws Exception
+     */
+    public void init(boolean reBuildDataSource) throws Exception {
+        try {
+            if (!electorConfig.isUseDefaultLeader()) {
+                initDataSource();
+                if (!reBuildDataSource) {
+                    formatSql(electorConfig.getElectorDbName(), 
electorConfig.getServiceId(),
+                            electorConfig.getLeaderId());
+                }
+
+            }
+        } catch (Exception exception) {
+            logger.error(exception.getMessage());
+            throw exception;
+        }
+    }
+
+    /**
+     * init data source
+     *
+     * @throws Exception
+     */
+    public void initDataSource() throws Exception {
+        boolean initSucc = false;
+        int initCount = 0;
+
+        while (!initSucc && initCount < 2) {
+            try {
+                ++initCount;
+                if (datasource == null || datasource.isClosed()) {
+                    HikariConfig config = new HikariConfig();
+                    config.setDriverClassName(electorConfig.getDbDriver());
+                    logger.info("## init dataSource:" + 
electorConfig.getDbUrl());
+                    config.setJdbcUrl(electorConfig.getDbUrl());
+                    config.setUsername(electorConfig.getDbUser());
+                    config.setPassword(electorConfig.getDbPasswd());
+                    
config.setMaximumPoolSize(electorConfig.getMaximumPoolSize());
+                    config.setAutoCommit(true);
+                    config.setConnectionTimeout((long) 
electorConfig.getConnectionTimeout());
+                    config.setMaxLifetime((long) 
electorConfig.getMaxLifetime());
+                    config.addDataSourceProperty("cachePrepStmts", 
electorConfig.getCachePrepStmts());
+                    config.addDataSourceProperty("prepStmtCacheSize", 
electorConfig.getPrepStmtCacheSize());
+                    config.addDataSourceProperty("prepStmtCacheSqlLimit",
+                            electorConfig.getPrepStmtCacheSqlLimit());
+                    config.setConnectionTestQuery("SELECT 1");
+                    datasource = new HikariDataSource(config);
+                }
+
+                initSucc = true;
+            } catch (Exception exception) {
+                logger.error(exception.getMessage());
+            }
+        }
+
+        if (!initSucc) {
+            throw new Exception("## DBDataSource init Fail!");
+        }
+    }
+
+    /**
+     * close
+     */
+    public void close() {
+        datasource.close();
+    }
+
+    /**
+     * Execute update
+     *
+     * @param sql
+     * @return
+     */
+    private int executeUpdate(String sql) {
+        int result = 0;
+        try {
+            if ((null == datasource) || (datasource.isClosed())) {
+                initDataSource();
+            }
+
+            Connection connection = datasource.getConnection();
+            try {
+                PreparedStatement pstmt = connection.prepareStatement(sql);
+                try {
+                    result = pstmt.executeUpdate();
+                } catch (Exception executeUpdatEexception) {
+                    logger.error("Exception :{}", 
executeUpdatEexception.getMessage());
+                } finally {
+                    if (pstmt != null) {
+                        pstmt.close();
+                    }
+                }
+            } catch (Exception pstmtEexception) {
+                logger.error("Exception :{}", pstmtEexception.getMessage());
+            } finally {
+                if (connection != null) {
+                    connection.close();
+                }
+            }
+            getConnectionFailTimes.set(0);
+        } catch (Exception e) {
+            getConnectionFailTimes.addAndGet(1);
+            logger.warn("## get Connection fail ...");
+        }
+        return result;
+    }
+
+    /**
+     * Leader selector
+     */
+    public void leaderSelector() {
+        if (!electorConfig.isUseDefaultLeader()) {
+            try {
+                int result = executeUpdate(electorSql);
+                if (result == 2) {
+                    logger.info(electorConfig.getLeaderId() + " get the 
leader");
+                } else if (result == 1) {
+                    logger.info(electorConfig.getLeaderId() + " do not get the 
leader");
+                }
+            } catch (Exception wxception) {
+                logger.error("Exception: {} ,sql:{}", wxception.getMessage(), 
electorSql);
+            }
+
+        }
+    }
+
+    /**
+     * Replace leader
+     *
+     * @param replaceLeaderId
+     */
+    public void replaceLeader(String replaceLeaderId) {
+        replaceLeaderSql = replaceLeaderSql.replaceAll("#", replaceLeaderId);

Review Comment:
   When is this method called to update the status?



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to