null, which turns on automatic resolution (resulting in the last known binlog and position). This is what\n * happens by default when you don't specify binary log filename explicitly.
\n *
\"\" (empty string), which instructs server to stream events starting from the oldest known binlog.
\n *
\n * @see #getBinlogFilename()\n */\n public void setBinlogFilename(String binlogFilename) {\n this.binlogFilename = binlogFilename;\n }\n\n /**\n * @return binary log position of the next event, 4 by default (which is a position of first event). Note that this\n * value changes with each incoming event.\n * @see #setBinlogPosition(long)\n */\n public long getBinlogPosition() {\n return binlogPosition;\n }\n\n /**\n * @param binlogPosition binary log position. Any value less than 4 gets automatically adjusted to 4 on connect.\n * @see #getBinlogPosition()\n */\n public void setBinlogPosition(long binlogPosition) {\n this.binlogPosition = binlogPosition;\n }\n\n /**\n * @return thread id\n */\n public long getConnectionId() {\n return connectionId;\n }\n\n /**\n * @return GTID set. Note that this value changes with each received GTID event (provided client is in GTID mode).\n * @see #setGtidSet(String)\n */\n public String getGtidSet() {\n synchronized (gtidSetAccessLock) {\n return gtidSet != null ? gtidSet.toString() : null;\n }\n }\n\n /**\n * @param gtidStr GTID set string (can be an empty string).\n *
NOTE #1: Any value but null will switch BinaryLogClient into a GTID mode (this will also set binlogFilename\n * to \"\" (provided it's null) forcing MySQL to send events starting from the oldest known binlog (keep in mind\n * that connection will fail if gtid_purged is anything but empty (unless\n * {@link #setGtidSetFallbackToPurged(boolean)} is set to true))).\n *
NOTE #2: GTID set is automatically updated with each incoming GTID event (provided GTID mode is on).\n * @see #getGtidSet()\n * @see #setGtidSetFallbackToPurged(boolean)\n */\n public void setGtidSet(String gtidStr) {\n if (gtidStr == null)\n return;\n\n synchronized (gtidSetAccessLock) {\n logger.info(\"Enabling GTID\");\n this.gtidEnabled = true;\n\n if (this.binlogFilename == null) {\n this.binlogFilename = \"\";\n }\n\n if (!gtidStr.equals(\"\")) {\n if (MariadbGtidSet.isMariaGtidSet(gtidStr)) {\n this.gtidSet = new MariadbGtidSet(gtidStr);\n } else {\n this.gtidSet = new GtidSet(gtidStr);\n }\n }\n }\n }\n\n /**\n * @return whether gtid_purged is used as a fallback\n * @see #setGtidSetFallbackToPurged(boolean)\n */\n public boolean isGtidSetFallbackToPurged() {\n return gtidSetFallbackToPurged;\n }\n\n /**\n * @param gtidSetFallbackToPurged true if gtid_purged should be used as a fallback when gtidSet is set to \"\" and\n * MySQL server has purged some of the binary logs, false otherwise (default).\n */\n public void setGtidSetFallbackToPurged(boolean gtidSetFallbackToPurged) {\n this.gtidSetFallbackToPurged = gtidSetFallbackToPurged;\n }\n\n /**\n * @return value of useBinlogFilenamePostionInGtidMode\n * @see #setUseBinlogFilenamePositionInGtidMode(boolean)\n */\n public boolean isUseBinlogFilenamePositionInGtidMode() {\n return useBinlogFilenamePositionInGtidMode;\n }\n\n /**\n * @param useBinlogFilenamePositionInGtidMode true if MySQL server should start streaming events from a given\n * {@link #getBinlogFilename()} and {@link #getBinlogPosition()} instead of \"the oldest known binlog\" when\n * {@link #getGtidSet()} is set, false otherwise (default).\n */\n public void setUseBinlogFilenamePositionInGtidMode(boolean useBinlogFilenamePositionInGtidMode) {\n this.useBinlogFilenamePositionInGtidMode = useBinlogFilenamePositionInGtidMode;\n }\n\n /**\n * @return true if \"keep alive\" thread should be automatically started (default), false otherwise.\n * @see #setKeepAlive(boolean)\n */\n public boolean isKeepAlive() {\n return keepAlive;\n }\n\n /**\n * @param keepAlive true if \"keep alive\" thread should be automatically started (recommended and true by default),\n * false otherwise.\n * @see #isKeepAlive()\n * @see #setKeepAliveInterval(long)\n */\n public void setKeepAlive(boolean keepAlive) {\n this.keepAlive = keepAlive;\n }\n\n /**\n * @return \"keep alive\" interval in milliseconds, 1 minute by default.\n * @see #setKeepAliveInterval(long)\n */\n public long getKeepAliveInterval() {\n return keepAliveInterval;\n }\n\n /**\n * @param keepAliveInterval \"keep alive\" interval in milliseconds.\n * @see #getKeepAliveInterval()\n * @see #setHeartbeatInterval(long)\n */\n public void setKeepAliveInterval(long keepAliveInterval) {\n this.keepAliveInterval = keepAliveInterval;\n }\n\n /**\n * @return \"keep alive\" connect timeout in milliseconds.\n * @see #setKeepAliveConnectTimeout(long)\n * @deprecated in favour of {@link #getConnectTimeout()}\n */\n public long getKeepAliveConnectTimeout() {\n return connectTimeout;\n }\n\n /**\n * @param connectTimeout \"keep alive\" connect timeout in milliseconds.\n * @see #getKeepAliveConnectTimeout()\n * @deprecated in favour of {@link #setConnectTimeout(long)}\n */\n public void setKeepAliveConnectTimeout(long connectTimeout) {\n this.connectTimeout = connectTimeout;\n }\n\n /**\n * @return heartbeat period in milliseconds (0 if not set (default)).\n * @see #setHeartbeatInterval(long)\n */\n public long getHeartbeatInterval() {\n return heartbeatInterval;\n }\n\n /**\n * @param heartbeatInterval heartbeat period in milliseconds.\n *
\n * If set (recommended)\n *
\n *
HEARTBEAT event will be emitted every \"heartbeatInterval\".\n *
if {@link #setKeepAlive(boolean)} is on then keepAlive thread will attempt to reconnect if no\n * HEARTBEAT events were received within {@link #setKeepAliveInterval(long)} (instead of trying to send\n * PING every {@link #setKeepAliveInterval(long)}, which is fundamentally flawed -\n * https://github.com/shyiko/mysql-binlog-connector-java/issues/118).\n *
\n * Note that when used together with keepAlive heartbeatInterval MUST be set less than keepAliveInterval.\n * @see #getHeartbeatInterval()\n */\n public void setHeartbeatInterval(long heartbeatInterval) {\n this.heartbeatInterval = heartbeatInterval;\n }\n\n /**\n * @return connect timeout in milliseconds, 3 seconds by default.\n * @see #setConnectTimeout(long)\n */\n public long getConnectTimeout() {\n return connectTimeout;\n }\n\n /**\n * @param connectTimeout connect timeout in milliseconds.\n * @see #getConnectTimeout()\n */\n public void setConnectTimeout(long connectTimeout) {\n this.connectTimeout = connectTimeout;\n }\n\n /**\n * @param eventDeserializer custom event deserializer\n */\n public void setEventDeserializer(EventDeserializer eventDeserializer) {\n if (eventDeserializer == null) {\n throw new IllegalArgumentException(\"Event deserializer cannot be NULL\");\n }\n this.eventDeserializer = eventDeserializer;\n }\n\n /**\n * @param socketFactory custom socket factory. If not provided, socket will be created with \"new Socket()\".\n */\n public void setSocketFactory(SocketFactory socketFactory) {\n this.socketFactory = socketFactory;\n }\n\n /**\n * @param sslSocketFactory custom ssl socket factory\n */\n public void setSslSocketFactory(SSLSocketFactory sslSocketFactory) {\n this.sslSocketFactory = sslSocketFactory;\n }\n\n /**\n * @param threadFactory custom thread factory. If not provided, threads will be created using simple \"new Thread()\".\n */\n public void setThreadFactory(ThreadFactory threadFactory) {\n this.threadFactory = threadFactory;\n }\n\n\n /**\n * @return true/false depending on whether we've connected to MariaDB. NULL if not connected.\n */\n public Boolean getMariaDB() {\n if (databaseVersion != null) {\n return databaseVersion.isMariaDb();\n }\n return null;\n }\n\n public boolean isUseSendAnnotateRowsEvent() {\n return useSendAnnotateRowsEvent;\n }\n\n public void setUseSendAnnotateRowsEvent(boolean useSendAnnotateRowsEvent) {\n this.useSendAnnotateRowsEvent = useSendAnnotateRowsEvent;\n }\n\n /**\n * @return the configured MariaDB slave compatibility level, defaults to 4.\n */\n public int getMariaDbSlaveCapability() {\n return mariaDbSlaveCapability;\n }\n\n /**\n * Set the client's MariaDB slave compatibility level. This only applies when connecting to MariaDB.\n *\n * @param mariaDbSlaveCapability the expected compatibility level\n */\n public void setMariaDbSlaveCapability(int mariaDbSlaveCapability) {\n this.mariaDbSlaveCapability = mariaDbSlaveCapability;\n }\n\n /**\n * Connect to the replication stream. Note that this method blocks until disconnected.\n *\n * @throws AuthenticationException if authentication fails\n * @throws ServerException if MySQL server responds with an error\n * @throws IOException if anything goes wrong while trying to connect\n * @throws IllegalStateException if binary log client is already connected\n */\n public void connect() throws IOException, IllegalStateException {\n logger.fine(\"Trying to connect to \" + hostname + \":\" + port);\n if (!connectLock.tryLock()) {\n throw new IllegalStateException(\"BinaryLogClient is already connected\");\n }\n boolean notifyWhenDisconnected = false;\n try {\n Callable cancelDisconnect = null;\n try {\n try {\n long start = System.currentTimeMillis();\n channel = openChannel();\n if (connectTimeout > 0 && !isKeepAliveThreadRunning()) {\n cancelDisconnect = scheduleDisconnectIn(connectTimeout -\n (System.currentTimeMillis() - start));\n }\n if (channel.getInputStream().peek() == -1) {\n throw new EOFException();\n }\n } catch (IOException e) {\n throw new IOException(\"Failed to connect to MySQL on \" + hostname + \":\" + port +\n \". Please make sure it's running.\", e);\n }\n GreetingPacket greetingPacket = receiveGreeting();\n\n resolveDatabaseVersion(greetingPacket);\n tryUpgradeToSSL(greetingPacket);\n\n new Authenticator(greetingPacket, channel, schema, username, password).authenticate();\n channel.authenticationComplete();\n\n connectionId = greetingPacket.getThreadId();\n if (\"\".equals(binlogFilename)) {\n setupGtidSet();\n }\n if (binlogFilename == null) {\n fetchBinlogFilenameAndPosition();\n }\n if (binlogPosition < 4) {\n if (logger.isLoggable(Level.WARNING)) {\n logger.warning(\"Binary log position adjusted from \" + binlogPosition + \" to \" + 4);\n }\n binlogPosition = 4;\n }\n setupConnection();\n gtid = null;\n tx = false;\n requestBinaryLogStream();\n } catch (IOException e) {\n disconnectChannel();\n throw e;\n } finally {\n if (cancelDisconnect != null) {\n try {\n cancelDisconnect.call();\n } catch (Exception e) {\n if (logger.isLoggable(Level.WARNING)) {\n logger.warning(\"\\\"\" + e.getMessage() +\n \"\\\" was thrown while canceling scheduled disconnect call\");\n }\n }\n }\n }\n connected = true;\n notifyWhenDisconnected = true;\n if (logger.isLoggable(Level.INFO)) {\n String position;\n synchronized (gtidSetAccessLock) {\n position = gtidSet != null ? gtidSet.toString() : binlogFilename + \"/\" + binlogPosition;\n }\n logger.info(\"Connected to \" + hostname + \":\" + port + \" at \" + position +\n \" (\" + (blocking ? \"sid:\" + serverId + \", \" : \"\") + \"cid:\" + connectionId + \")\");\n }\n for (LifecycleListener lifecycleListener : lifecycleListeners) {\n lifecycleListener.onConnect(this);\n }\n if (keepAlive && !isKeepAliveThreadRunning()) {\n spawnKeepAliveThread();\n }\n ensureEventDataDeserializer(EventType.ROTATE, RotateEventDataDeserializer.class);\n synchronized (gtidSetAccessLock) {\n if (this.gtidEnabled) {\n ensureGtidEventDataDeserializer();\n }\n }\n listenForEventPackets();\n } finally {\n connectLock.unlock();\n if (notifyWhenDisconnected) {\n for (LifecycleListener lifecycleListener : lifecycleListeners) {\n lifecycleListener.onDisconnect(this);\n }\n }\n }\n }\n\n private void resolveDatabaseVersion(GreetingPacket packet) {\n this.databaseVersion = BinaryLogDatabaseVersion.parse(packet.getServerVersion());\n logger.info(\"Database version: \" + this.databaseVersion);\n }\n\n /**\n * Apply additional options for connection before requesting binlog stream.\n */\n protected void setupConnection() throws IOException {\n ChecksumType checksumType = fetchBinlogChecksum();\n if (checksumType != ChecksumType.NONE) {\n confirmSupportOfChecksum(checksumType);\n }\n setMasterServerId();\n if (heartbeatInterval > 0) {\n enableHeartbeat();\n }\n }\n\n private PacketChannel openChannel() throws IOException {\n Socket socket = socketFactory != null ? socketFactory.createSocket() : new Socket();\n socket.connect(new InetSocketAddress(hostname, port), (int) connectTimeout);\n return new PacketChannel(socket);\n }\n\n private Callable scheduleDisconnectIn(final long timeout) {\n final BinaryLogClient self = this;\n final CountDownLatch connectLatch = new CountDownLatch(1);\n Map copyOfContextMap = MDC.getCopyOfContextMap();\n final Thread thread = newNamedThread(new Runnable() {\n @Override\n public void run() {\n // 改动\n if (CollUtil.isNotEmpty(copyOfContextMap)) {\n MDC.setContextMap(copyOfContextMap);\n }\n try {\n try {\n connectLatch.await(timeout, TimeUnit.MILLISECONDS);\n } catch (InterruptedException e) {\n if (logger.isLoggable(Level.WARNING)) {\n logger.log(Level.WARNING, e.getMessage());\n }\n }\n if (connectLatch.getCount() != 0) {\n if (logger.isLoggable(Level.WARNING)) {\n logger.warning(\"Failed to establish connection in \" + timeout + \"ms. \" +\n \"Forcing disconnect.\");\n }\n try {\n self.disconnectChannel();\n } catch (IOException e) {\n if (logger.isLoggable(Level.WARNING)) {\n logger.log(Level.WARNING, e.getMessage());\n }\n }\n }\n } finally {\n MDC.clear();\n }\n }\n }, \"blc-disconnect-\" + hostname + \":\" + port);\n thread.start();\n return new Callable() {\n\n public Object call() throws Exception {\n connectLatch.countDown();\n thread.join();\n return null;\n }\n };\n }\n\n protected void checkError(byte[] packet) throws IOException {\n if (packet[0] == (byte) 0xFF /* error */) {\n byte[] bytes = Arrays.copyOfRange(packet, 1, packet.length);\n ErrorPacket errorPacket = new ErrorPacket(bytes);\n throw new ServerException(errorPacket.getErrorMessage(), errorPacket.getErrorCode(),\n errorPacket.getSqlState());\n }\n }\n\n private GreetingPacket receiveGreeting() throws IOException {\n byte[] initialHandshakePacket = channel.read();\n checkError(initialHandshakePacket);\n\n return new GreetingPacket(initialHandshakePacket);\n }\n\n private boolean tryUpgradeToSSL(GreetingPacket greetingPacket) throws IOException {\n int collation = greetingPacket.getServerCollation();\n\n if (sslMode != SSLMode.DISABLED) {\n boolean serverSupportsSSL = (greetingPacket.getServerCapabilities() & ClientCapabilities.SSL) != 0;\n if (!serverSupportsSSL && (sslMode == SSLMode.REQUIRED || sslMode == SSLMode.VERIFY_CA ||\n sslMode == SSLMode.VERIFY_IDENTITY)) {\n throw new IOException(\"MySQL server does not support SSL\");\n }\n if (serverSupportsSSL) {\n SSLRequestCommand sslRequestCommand = new SSLRequestCommand();\n sslRequestCommand.setCollation(collation);\n channel.write(sslRequestCommand);\n SSLSocketFactory sslSocketFactory =\n this.sslSocketFactory != null ?\n this.sslSocketFactory :\n sslMode == SSLMode.REQUIRED || sslMode == SSLMode.PREFERRED ?\n DEFAULT_REQUIRED_SSL_MODE_SOCKET_FACTORY :\n DEFAULT_VERIFY_CA_SSL_MODE_SOCKET_FACTORY;\n channel.upgradeToSSL(sslSocketFactory,\n sslMode == SSLMode.VERIFY_IDENTITY ? new TLSHostnameVerifier() : null);\n logger.info(\"SSL enabled\");\n return true;\n }\n }\n return false;\n }\n\n private void enableHeartbeat() throws IOException {\n channel.write(new QueryCommand(\"set @master_heartbeat_period=\" + heartbeatInterval * 1000000));\n byte[] statementResult = channel.read();\n checkError(statementResult);\n }\n\n private void setMasterServerId() throws IOException {\n channel.write(new QueryCommand(\"select @@server_id\"));\n ResultSetRowPacket[] resultSet = readResultSet();\n if (resultSet.length >= 0) {\n this.masterServerId = Long.parseLong(resultSet[0].getValue(0));\n }\n }\n\n protected void requestBinaryLogStream() throws IOException {\n long serverId = blocking ? this.serverId : 0; // http://bugs.mysql.com/bug.php?id=71178\n if (this.databaseVersion.isMariaDb())\n requestBinaryLogStreamMaria(serverId);\n else\n requestBinaryLogStreamMysql(serverId);\n }\n\n private void requestBinaryLogStreamMysql(long serverId) throws IOException {\n Command dumpBinaryLogCommand;\n synchronized (gtidSetAccessLock) {\n if (this.gtidEnabled) {\n logger.info(\"Requesting streaming from position filename: \" + binlogFilename + \", position: \" + binlogPosition + \", GTID set: \" + gtidSet);\n dumpBinaryLogCommand = new DumpBinaryLogGtidCommand(serverId,\n useBinlogFilenamePositionInGtidMode ? binlogFilename : \"\",\n useBinlogFilenamePositionInGtidMode ? binlogPosition : 4,\n gtidSet);\n } else {\n logger.info(\"Requesting streaming from position filename: \" + binlogFilename + \", position: \" + binlogPosition);\n dumpBinaryLogCommand = new DumpBinaryLogCommand(serverId, binlogFilename, binlogPosition);\n }\n }\n channel.write(dumpBinaryLogCommand);\n }\n\n protected void requestBinaryLogStreamMaria(long serverId) throws IOException {\n Command dumpBinaryLogCommand;\n\n /*\n https://jira.mariadb.org/browse/MDEV-225\n */\n channel.write(new QueryCommand(\"SET @mariadb_slave_capability=\" + mariaDbSlaveCapability));\n checkError(channel.read());\n\n synchronized (gtidSetAccessLock) {\n if (this.gtidEnabled) {\n logger.info(\"Requesting streaming from GTID set: \" + gtidSet);\n channel.write(new QueryCommand(\"SET @slave_connect_state = '\" + gtidSet.toString() + \"'\"));\n checkError(channel.read());\n channel.write(new QueryCommand(\"SET @slave_gtid_strict_mode = 0\"));\n checkError(channel.read());\n channel.write(new QueryCommand(\"SET @slave_gtid_ignore_duplicates = 0\"));\n checkError(channel.read());\n dumpBinaryLogCommand = new DumpBinaryLogCommand(serverId, \"\", 0L, isUseSendAnnotateRowsEvent());\n } else {\n logger.info(\"Requesting streaming from position filename: \" + binlogFilename + \", position: \" + binlogPosition);\n dumpBinaryLogCommand = new DumpBinaryLogCommand(serverId, binlogFilename, binlogPosition, isUseSendAnnotateRowsEvent());\n }\n }\n channel.write(dumpBinaryLogCommand);\n }\n\n protected void ensureEventDataDeserializer(EventType eventType,\n Class extends EventDataDeserializer> eventDataDeserializerClass) {\n EventDataDeserializer eventDataDeserializer = eventDeserializer.getEventDataDeserializer(eventType);\n if (eventDataDeserializer.getClass() != eventDataDeserializerClass &&\n eventDataDeserializer.getClass() != EventDataWrapper.Deserializer.class) {\n EventDataDeserializer internalEventDataDeserializer;\n try {\n internalEventDataDeserializer = eventDataDeserializerClass.newInstance();\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n eventDeserializer.setEventDataDeserializer(eventType,\n new EventDataWrapper.Deserializer(internalEventDataDeserializer,\n eventDataDeserializer));\n }\n }\n\n protected void ensureGtidEventDataDeserializer() {\n ensureEventDataDeserializer(EventType.GTID, GtidEventDataDeserializer.class);\n ensureEventDataDeserializer(EventType.QUERY, QueryEventDataDeserializer.class);\n ensureEventDataDeserializer(EventType.ANNOTATE_ROWS, AnnotateRowsEventDataDeserializer.class);\n ensureEventDataDeserializer(EventType.MARIADB_GTID, MariadbGtidEventDataDeserializer.class);\n ensureEventDataDeserializer(EventType.MARIADB_GTID_LIST, MariadbGtidListEventDataDeserializer.class);\n }\n\n private void spawnKeepAliveThread() {\n final ExecutorService threadExecutor =\n Executors.newSingleThreadExecutor(new ThreadFactory() {\n\n @Override\n public Thread newThread(Runnable runnable) {\n return newNamedThread(runnable, \"blc-keepalive-\" + hostname + \":\" + port);\n }\n });\n try {\n keepAliveThreadExecutorLock.lock();\n // 改动\n Map copyOfContextMap = MDC.getCopyOfContextMap();\n threadExecutor.submit(new Runnable() {\n @Override\n public void run() {\n if (CollUtil.isNotEmpty(copyOfContextMap)) {\n MDC.setContextMap(copyOfContextMap);\n }\n try {\n while (!threadExecutor.isShutdown()) {\n try {\n Thread.sleep(keepAliveInterval);\n } catch (InterruptedException e) {\n // expected in case of disconnect\n }\n if (threadExecutor.isShutdown()) {\n logger.info(\"threadExecutor is shut down, terminating keepalive thread\");\n return;\n }\n boolean connectionLost = false;\n if (heartbeatInterval > 0) {\n connectionLost = System.currentTimeMillis() - eventLastSeen > keepAliveInterval;\n } else {\n try {\n channel.write(new PingCommand());\n } catch (IOException e) {\n connectionLost = true;\n }\n }\n if (connectionLost) {\n logger.info(\"Keepalive: Trying to restore lost connection to \" + hostname + \":\" + port);\n try {\n terminateConnect(useNonGracefulDisconnect);\n connect(connectTimeout);\n } catch (Exception ce) {\n logger.warning(\"keepalive: Failed to restore connection to \" + hostname + \":\" + port +\n \". Next attempt in \" + keepAliveInterval + \"ms\");\n }\n }\n }\n } finally {\n MDC.clear();\n }\n }\n });\n keepAliveThreadExecutor = threadExecutor;\n } finally {\n keepAliveThreadExecutorLock.unlock();\n }\n }\n\n private Thread newNamedThread(Runnable runnable, String threadName) {\n Thread thread = threadFactory == null ? new Thread(runnable) : threadFactory.newThread(runnable);\n thread.setName(threadName);\n return thread;\n }\n\n boolean isKeepAliveThreadRunning() {\n try {\n keepAliveThreadExecutorLock.lock();\n return keepAliveThreadExecutor != null && !keepAliveThreadExecutor.isShutdown();\n } finally {\n keepAliveThreadExecutorLock.unlock();\n }\n }\n\n /**\n * Connect to the replication stream in a separate thread.\n *\n * @param timeout timeout in milliseconds\n * @throws AuthenticationException if authentication fails\n * @throws ServerException if MySQL server responds with an error\n * @throws IOException if anything goes wrong while trying to connect\n * @throws TimeoutException if client was unable to connect within given time limit\n */\n public void connect(final long timeout) throws IOException, TimeoutException {\n final CountDownLatch countDownLatch = new CountDownLatch(1);\n AbstractLifecycleListener connectListener = new AbstractLifecycleListener() {\n @Override\n public void onConnect(BinaryLogClient client) {\n countDownLatch.countDown();\n }\n };\n registerLifecycleListener(connectListener);\n final AtomicReference exceptionReference = new AtomicReference();\n Map copyOfContextMap = MDC.getCopyOfContextMap();\n Runnable runnable = new Runnable() {\n\n @Override\n public void run() {\n if (CollUtil.isNotEmpty(copyOfContextMap)) {\n MDC.setContextMap(copyOfContextMap);\n }\n try {\n setConnectTimeout(timeout);\n connect();\n } catch (IOException e) {\n exceptionReference.set(e);\n countDownLatch.countDown(); // making sure we don't end up waiting whole \"timeout\"\n } catch (Exception e) {\n exceptionReference.set(new IOException(e)); // method is asynchronous, catch all exceptions so that they are not lost\n countDownLatch.countDown(); // making sure we don't end up waiting whole \"timeout\"\n } finally {\n MDC.clear();\n }\n }\n };\n newNamedThread(runnable, \"blc-\" + hostname + \":\" + port).start();\n boolean started = false;\n try {\n started = countDownLatch.await(timeout, TimeUnit.MILLISECONDS);\n } catch (InterruptedException e) {\n if (logger.isLoggable(Level.WARNING)) {\n logger.log(Level.WARNING, e.getMessage());\n }\n }\n unregisterLifecycleListener(connectListener);\n if (exceptionReference.get() != null) {\n throw exceptionReference.get();\n }\n if (!started) {\n try {\n terminateConnect();\n } finally {\n throw new TimeoutException(\"BinaryLogClient was unable to connect in \" + timeout + \"ms\");\n }\n }\n }\n\n /**\n * @return true if client is connected, false otherwise\n */\n public boolean isConnected() {\n return connected;\n }\n\n private String fetchGtidPurged() throws IOException {\n channel.write(new QueryCommand(\"show global variables like 'gtid_purged'\"));\n ResultSetRowPacket[] resultSet = readResultSet();\n if (resultSet.length != 0) {\n return resultSet[0].getValue(1).toUpperCase();\n }\n return \"\";\n }\n\n protected void setupGtidSet() throws IOException {\n synchronized (gtidSetAccessLock) {\n if (!this.gtidEnabled)\n return;\n\n if (this.databaseVersion.isMariaDb()) {\n if (gtidSet == null) {\n gtidSet = new MariadbGtidSet(\"\");\n } else if (!(gtidSet instanceof MariadbGtidSet)) {\n throw new RuntimeException(\"Connected to MariaDB but given a mysql GTID set!\");\n }\n } else {\n if (gtidSet == null && gtidSetFallbackToPurged) {\n gtidSet = new GtidSet(fetchGtidPurged());\n } else if (gtidSet == null) {\n gtidSet = new GtidSet(\"\");\n } else if (gtidSet instanceof MariadbGtidSet) {\n throw new RuntimeException(\"Connected to Mysql but given a MariaDB GTID set!\");\n }\n }\n }\n\n }\n\n private void fetchBinlogFilenameAndPosition() throws IOException {\n ResultSetRowPacket[] resultSet;\n if (!databaseVersion.isMariaDb() && databaseVersion.isGreaterThanOrEqualTo(8, 4)) {\n channel.write(new QueryCommand(\"show binary log status\"));\n } else {\n channel.write(new QueryCommand(\"show master status\"));\n }\n resultSet = readResultSet();\n if (resultSet.length == 0) {\n throw new IOException(\"Failed to determine binlog filename/position\");\n }\n ResultSetRowPacket resultSetRow = resultSet[0];\n binlogFilename = resultSetRow.getValue(0);\n binlogPosition = Long.parseLong(resultSetRow.getValue(1));\n }\n\n private ChecksumType fetchBinlogChecksum() throws IOException {\n channel.write(new QueryCommand(\"show global variables like 'binlog_checksum'\"));\n ResultSetRowPacket[] resultSet = readResultSet();\n if (resultSet.length == 0) {\n return ChecksumType.NONE;\n }\n return ChecksumType.valueOf(resultSet[0].getValue(1).toUpperCase());\n }\n\n private void confirmSupportOfChecksum(ChecksumType checksumType) throws IOException {\n channel.write(new QueryCommand(\"set @master_binlog_checksum= @@global.binlog_checksum\"));\n byte[] statementResult = channel.read();\n checkError(statementResult);\n eventDeserializer.setChecksumType(checksumType);\n }\n\n private void listenForEventPackets() throws IOException {\n ByteArrayInputStream inputStream = channel.getInputStream();\n boolean completeShutdown = false;\n try {\n while (inputStream.peek() != -1) {\n int packetLength = inputStream.readInteger(3);\n inputStream.skip(1); // 1 byte for sequence\n int marker = inputStream.read();\n if (marker == 0xFF) {\n ErrorPacket errorPacket = new ErrorPacket(inputStream.read(packetLength - 1));\n throw new ServerException(errorPacket.getErrorMessage(), errorPacket.getErrorCode(),\n errorPacket.getSqlState());\n }\n if (marker == 0xFE && !blocking) {\n completeShutdown = true;\n break;\n }\n Event event;\n try {\n event = eventDeserializer.nextEvent(packetLength == MAX_PACKET_LENGTH ?\n new ByteArrayInputStream(readPacketSplitInChunks(inputStream, packetLength - 1)) :\n inputStream);\n if (event == null) {\n throw new EOFException();\n }\n } catch (Exception e) {\n Throwable cause = e instanceof EventDataDeserializationException ? e.getCause() : e;\n if (cause instanceof EOFException || cause instanceof SocketException) {\n throw e;\n }\n if (isConnected()) {\n for (LifecycleListener lifecycleListener : lifecycleListeners) {\n lifecycleListener.onEventDeserializationFailure(this, e);\n }\n }\n continue;\n }\n if (isConnected()) {\n eventLastSeen = System.currentTimeMillis();\n updateGtidSet(event);\n notifyEventListeners(event);\n updateClientBinlogFilenameAndPosition(event);\n }\n }\n } catch (Exception e) {\n if (isConnected()) {\n for (LifecycleListener lifecycleListener : lifecycleListeners) {\n lifecycleListener.onCommunicationFailure(this, e);\n }\n }\n } finally {\n if (isConnected()) {\n if (completeShutdown) {\n disconnect(); // initiate complete shutdown sequence (which includes keep alive thread)\n } else {\n disconnectChannel();\n }\n }\n }\n }\n\n private byte[] readPacketSplitInChunks(ByteArrayInputStream inputStream, int packetLength) throws IOException {\n byte[] result = inputStream.read(packetLength);\n int chunkLength;\n do {\n chunkLength = inputStream.readInteger(3);\n inputStream.skip(1); // 1 byte for sequence\n result = Arrays.copyOf(result, result.length + chunkLength);\n inputStream.fill(result, result.length - chunkLength, chunkLength);\n } while (chunkLength == Packet.MAX_LENGTH);\n return result;\n }\n\n private void updateClientBinlogFilenameAndPosition(Event event) {\n EventHeader eventHeader = event.getHeader();\n EventType eventType = eventHeader.getEventType();\n if (eventType == EventType.ROTATE) {\n RotateEventData rotateEventData = (RotateEventData) EventDataWrapper.internal(event.getData());\n binlogFilename = rotateEventData.getBinlogFilename();\n binlogPosition = rotateEventData.getBinlogPosition();\n } else\n // do not update binlogPosition on TABLE_MAP so that in case of reconnect (using a different instance of\n // client) table mapping cache could be reconstructed before hitting row mutation event\n if (eventType != EventType.TABLE_MAP && eventHeader instanceof EventHeaderV4) {\n EventHeaderV4 trackableEventHeader = (EventHeaderV4) eventHeader;\n long nextBinlogPosition = trackableEventHeader.getNextPosition();\n if (nextBinlogPosition > 0) {\n binlogPosition = nextBinlogPosition;\n }\n }\n }\n\n protected void updateGtidSet(Event event) {\n synchronized (gtidSetAccessLock) {\n if (gtidSet == null) {\n return;\n }\n }\n EventHeader eventHeader = event.getHeader();\n switch (eventHeader.getEventType()) {\n case GTID:\n GtidEventData gtidEventData = (GtidEventData) EventDataWrapper.internal(event.getData());\n gtid = gtidEventData.getMySqlGtid();\n break;\n case XID:\n commitGtid();\n tx = false;\n break;\n case QUERY:\n QueryEventData queryEventData = (QueryEventData) EventDataWrapper.internal(event.getData());\n String sql = queryEventData.getSql();\n if (sql == null) {\n break;\n }\n commitGtid(sql);\n break;\n case ANNOTATE_ROWS:\n AnnotateRowsEventData annotateRowsEventData = (AnnotateRowsEventData) EventDeserializer.EventDataWrapper.internal(event.getData());\n sql = annotateRowsEventData.getRowsQuery();\n if (sql == null) {\n break;\n }\n commitGtid(sql);\n break;\n case MARIADB_GTID:\n MariadbGtidEventData mariadbGtidEventData = (MariadbGtidEventData) EventDeserializer.EventDataWrapper.internal(event.getData());\n mariadbGtidEventData.setServerId(eventHeader.getServerId());\n gtid = mariadbGtidEventData.toString();\n break;\n case MARIADB_GTID_LIST:\n MariadbGtidListEventData mariadbGtidListEventData = (MariadbGtidListEventData) EventDeserializer.EventDataWrapper.internal(event.getData());\n gtid = mariadbGtidListEventData.getMariaGTIDSet().toString();\n break;\n case TRANSACTION_PAYLOAD:\n commitGtid();\n break;\n default:\n }\n }\n\n protected void commitGtid(String sql) {\n if (\"BEGIN\".equals(sql)) {\n tx = true;\n } else if (\"COMMIT\".equals(sql) || \"ROLLBACK\".equals(sql)) {\n commitGtid();\n tx = false;\n } else if (!tx) {\n // auto-commit query, likely DDL\n commitGtid();\n }\n }\n\n private void commitGtid() {\n if (gtid != null) {\n synchronized (gtidSetAccessLock) {\n logger.finest(\"Adding GTID \" + gtid);\n gtidSet.addGtid(gtid);\n }\n }\n }\n\n private ResultSetRowPacket[] readResultSet() throws IOException {\n List resultSet = new LinkedList<>();\n byte[] statementResult = channel.read();\n checkError(statementResult);\n\n while ((channel.read())[0] != (byte) 0xFE /* eof */) { /* skip */ }\n for (byte[] bytes; (bytes = channel.read())[0] != (byte) 0xFE /* eof */; ) {\n checkError(bytes);\n resultSet.add(new ResultSetRowPacket(bytes));\n }\n return resultSet.toArray(new ResultSetRowPacket[resultSet.size()]);\n }\n\n /**\n * @return registered event listeners\n */\n public List getEventListeners() {\n return Collections.unmodifiableList(eventListeners);\n }\n\n /**\n * Register event listener. Note that multiple event listeners will be called in order they\n * where registered.\n *\n * @param eventListener event listener\n */\n public void registerEventListener(EventListener eventListener) {\n eventListeners.add(eventListener);\n }\n\n /**\n * Unregister all event listener of specific type.\n *\n * @param listenerClass event listener class to unregister\n */\n public void unregisterEventListener(Class extends EventListener> listenerClass) {\n for (EventListener eventListener : eventListeners) {\n if (listenerClass.isInstance(eventListener)) {\n eventListeners.remove(eventListener);\n }\n }\n }\n\n /**\n * Unregister single event listener.\n *\n * @param eventListener event listener to unregister\n */\n public void unregisterEventListener(EventListener eventListener) {\n eventListeners.remove(eventListener);\n }\n\n private void notifyEventListeners(Event event) {\n if (event.getData() instanceof EventDataWrapper) {\n event = new Event(event.getHeader(), ((EventDataWrapper) event.getData()).getExternal());\n }\n for (EventListener eventListener : eventListeners) {\n try {\n eventListener.onEvent(event);\n } catch (Exception e) {\n if (logger.isLoggable(Level.WARNING)) {\n logger.log(Level.WARNING, eventListener + \" choked on \" + event, e);\n }\n }\n }\n }\n\n /**\n * @return registered lifecycle listeners\n */\n public List getLifecycleListeners() {\n return Collections.unmodifiableList(lifecycleListeners);\n }\n\n /**\n * Register lifecycle listener. Note that multiple lifecycle listeners will be called in order they\n * where registered.\n *\n * @param lifecycleListener lifecycle listener to register\n */\n public void registerLifecycleListener(LifecycleListener lifecycleListener) {\n lifecycleListeners.add(lifecycleListener);\n }\n\n /**\n * Unregister all lifecycle listener of specific type.\n *\n * @param listenerClass lifecycle listener class to unregister\n */\n public void unregisterLifecycleListener(Class extends LifecycleListener> listenerClass) {\n for (LifecycleListener lifecycleListener : lifecycleListeners) {\n if (listenerClass.isInstance(lifecycleListener)) {\n lifecycleListeners.remove(lifecycleListener);\n }\n }\n }\n\n /**\n * Unregister single lifecycle listener.\n *\n * @param eventListener lifecycle listener to unregister\n */\n public void unregisterLifecycleListener(LifecycleListener eventListener) {\n lifecycleListeners.remove(eventListener);\n }\n\n /**\n * Disconnect from the replication stream.\n * Note that this does not cause binlogFilename/binlogPosition to be cleared out.\n * As the result following {@link #connect()} resumes client from where it left off.\n */\n public void disconnect() throws IOException {\n logger.fine(\"Disconnecting from \" + hostname + \":\" + port);\n terminateKeepAliveThread();\n terminateConnect();\n }\n\n private void terminateKeepAliveThread() {\n try {\n keepAliveThreadExecutorLock.lock();\n ExecutorService keepAliveThreadExecutor = this.keepAliveThreadExecutor;\n if (keepAliveThreadExecutor == null) {\n return;\n }\n keepAliveThreadExecutor.shutdownNow();\n } finally {\n keepAliveThreadExecutorLock.unlock();\n }\n while (!awaitTerminationInterruptibly(keepAliveThreadExecutor,\n Long.MAX_VALUE, TimeUnit.NANOSECONDS)) {\n // ignore\n }\n }\n\n private static boolean awaitTerminationInterruptibly(ExecutorService executorService, long timeout, TimeUnit unit) {\n try {\n return executorService.awaitTermination(timeout, unit);\n } catch (InterruptedException e) {\n return false;\n }\n }\n\n private void terminateConnect() throws IOException {\n terminateConnect(false);\n }\n\n private void terminateConnect(boolean force) throws IOException {\n do {\n disconnectChannel(force);\n } while (!tryLockInterruptibly(connectLock, 1000, TimeUnit.MILLISECONDS));\n connectLock.unlock();\n }\n\n private static boolean tryLockInterruptibly(Lock lock, long time, TimeUnit unit) {\n try {\n return lock.tryLock(time, unit);\n } catch (InterruptedException e) {\n return false;\n }\n }\n\n private void disconnectChannel() throws IOException {\n disconnectChannel(false);\n }\n\n private void disconnectChannel(boolean force) throws IOException {\n connected = false;\n if (channel != null && channel.isOpen()) {\n if (force) {\n channel.setShouldUseSoLinger0();\n }\n channel.close();\n }\n }\n\n /**\n * {@link BinaryLogClient}'s event listener.\n */\n public interface EventListener {\n\n void onEvent(Event event);\n }\n\n /**\n * {@link BinaryLogClient}'s lifecycle listener.\n */\n public interface LifecycleListener {\n\n /**\n * Called once client has successfully logged in but before started to receive binlog events.\n *\n * @param client the client that logged in\n */\n void onConnect(BinaryLogClient client);\n\n /**\n * It's guarantied to be called before {@link #onDisconnect(BinaryLogClient)}) in case of\n * communication failure.\n *\n * @param client the client that triggered the communication failure\n * @param ex The exception that triggered the communication failutre\n */\n void onCommunicationFailure(BinaryLogClient client, Exception ex);\n\n /**\n * Called in case of failed event deserialization. Note this type of error does NOT cause client to\n * disconnect. If you wish to stop receiving events you'll need to fire client.disconnect() manually.\n *\n * @param client the client that failed event deserialization\n * @param ex The exception that triggered the failutre\n */\n void onEventDeserializationFailure(BinaryLogClient client, Exception ex);\n\n /**\n * Called upon disconnect (regardless of the reason).\n *\n * @param client the client that disconnected\n */\n void onDisconnect(BinaryLogClient client);\n }\n\n /**\n * Default (no-op) implementation of {@link LifecycleListener}.\n */\n public static abstract class AbstractLifecycleListener implements LifecycleListener {\n\n public void onConnect(BinaryLogClient client) {\n }\n\n public void onCommunicationFailure(BinaryLogClient client, Exception ex) {\n }\n\n public void onEventDeserializationFailure(BinaryLogClient client, Exception ex) {\n }\n\n public void onDisconnect(BinaryLogClient client) {\n }\n\n }\n\n}\n"], ["/data-platform-open/data-platform-open-support/src/main/java/cn/dataplatform/open/support/service/alarm/impl/AlarmServiceImpl.java", "package cn.dataplatform.open.support.service.alarm.impl;\n\nimport cn.dataplatform.open.common.alarm.robot.DingTalkRobot;\nimport cn.dataplatform.open.common.alarm.robot.LarkRobot;\nimport cn.dataplatform.open.common.alarm.robot.Robot;\nimport cn.dataplatform.open.common.alarm.robot.WeComRobot;\nimport cn.dataplatform.open.common.alarm.robot.content.Content;\nimport cn.dataplatform.open.common.alarm.robot.content.LarkContent;\nimport cn.dataplatform.open.common.alarm.robot.content.TextContent;\nimport cn.dataplatform.open.common.body.AlarmMessageBody;\nimport cn.dataplatform.open.common.constant.Constant;\nimport cn.dataplatform.open.common.enums.*;\nimport cn.dataplatform.open.common.enums.alarm.AlarmLogStatus;\nimport cn.dataplatform.open.common.enums.alarm.AlarmRobotMode;\nimport cn.dataplatform.open.common.enums.alarm.AlarmRobotType;\nimport cn.dataplatform.open.common.util.ParallelStreamUtils;\nimport cn.dataplatform.open.common.vo.alarm.robot.Receive;\nimport cn.dataplatform.open.common.vo.alarm.robot.Silent;\nimport cn.dataplatform.open.support.excepiton.AlarmSilentException;\nimport cn.dataplatform.open.support.service.alarm.AlarmService;\nimport cn.dataplatform.open.support.store.entity.AlarmLog;\nimport cn.dataplatform.open.support.store.entity.AlarmRobot;\nimport cn.dataplatform.open.support.store.entity.AlarmTemplate;\nimport cn.dataplatform.open.support.store.mapper.AlarmLogMapper;\nimport cn.dataplatform.open.support.store.mapper.AlarmRobotMapper;\nimport cn.dataplatform.open.support.store.mapper.AlarmTemplateMapper;\nimport cn.dataplatform.open.support.util.FreeMarkerUtils;\nimport cn.hutool.core.collection.CollUtil;\nimport cn.hutool.core.date.LocalDateTimeUtil;\nimport cn.hutool.core.util.StrUtil;\nimport cn.hutool.extra.spring.SpringUtil;\nimport com.alibaba.fastjson2.JSON;\nimport com.baomidou.mybatisplus.core.toolkit.Wrappers;\nimport com.hankcs.algorithm.AhoCorasickDoubleArrayTrie;\nimport jakarta.annotation.Resource;\nimport lombok.SneakyThrows;\nimport lombok.extern.slf4j.Slf4j;\nimport org.redisson.api.RAtomicLong;\nimport org.redisson.api.RedissonClient;\nimport org.slf4j.MDC;\nimport org.springframework.stereotype.Service;\n\nimport java.util.*;\nimport java.util.stream.Collectors;\n\n/**\n * 〈一句话功能简述〉 \n * 〈〉\n *\n * @author dingqianwen\n * @date 2025/2/22\n * @since 1.0.0\n */\n@Slf4j\n@Service\npublic class AlarmServiceImpl implements AlarmService {\n\n /**\n * 内置模板参数\n */\n public static final String $_REQUEST_ID = \"$requestId\";\n public static final String SERVER_NAME = \"$serverName\";\n public static final String $_INSTANCE_ID = \"$instanceId\";\n public static final String $_ALARM_TIME = \"$alarmTime\";\n public static final String $_WORKSPACE_CODE = \"$workspaceCode\";\n\n @Resource\n private AlarmRobotMapper alarmRobotMapper;\n @Resource\n private AlarmTemplateMapper alarmTemplateMapper;\n @Resource\n private AlarmLogMapper alarmLogMapper;\n @Resource\n private RedissonClient redissonClient;\n\n /**\n * 告警\n *\n * @param alarmMessageBody 告警消息\n */\n @Override\n public void alarm(AlarmMessageBody alarmMessageBody) {\n this.alarm(alarmMessageBody, null);\n }\n\n /**\n * 告警\n *\n * @param alarmMessageBody 告警消息\n * @param sceneCode 场景编码\n */\n @Override\n public void alarm(AlarmMessageBody alarmMessageBody, String sceneCode) {\n String workspaceCode = alarmMessageBody.getWorkspaceCode();\n String robotCode = alarmMessageBody.getRobotCode();\n AlarmRobot alarmRobot = this.alarmRobotMapper.selectOne(Wrappers.lambdaQuery()\n .eq(AlarmRobot::getWorkspaceCode, workspaceCode)\n .eq(AlarmRobot::getCode, robotCode)\n );\n if (alarmRobot == null) {\n log.info(\"机器人不存在,告警消息被丢弃\");\n return;\n }\n // 是否启用\n if (!Status.ENABLE.name().equals(alarmRobot.getStatus())) {\n log.info(\"机器人未启用,告警消息被丢弃\");\n return;\n }\n String requestId = MDC.get(Constant.REQUEST_ID);\n // 内置参数处理,提前,需要记录日志\n this.builtInParameter(alarmMessageBody, requestId);\n Status recordLogSwitch = Status.valueOf(alarmRobot.getRecordLogSwitch());\n AlarmLog alarmLog = null;\n // 是否需要记录日志\n if (recordLogSwitch.equals(Status.ENABLE)) {\n alarmLog = new AlarmLog();\n alarmLog.setRequestId(requestId);\n alarmLog.setSceneCode(sceneCode);\n alarmLog.setStatus(AlarmLogStatus.SENDING.name());\n alarmLog.setRobotCode(alarmMessageBody.getRobotCode());\n alarmLog.setTemplateCode(alarmMessageBody.getTemplateCode());\n alarmLog.setServerName(alarmMessageBody.getServerName());\n alarmLog.setInstanceId(alarmMessageBody.getInstanceId());\n alarmLog.setWorkspaceCode(alarmMessageBody.getWorkspaceCode());\n alarmLog.setParameter(JSON.toJSONString(alarmMessageBody.getParameter()));\n alarmLog.setCreateTime(alarmMessageBody.getAlarmTime());\n this.alarmLogMapper.insert(alarmLog);\n }\n try {\n this.doAlarm(alarmRobot, alarmMessageBody);\n log.info(\"发送告警消息成功\");\n if (alarmLog != null) {\n alarmLog.setStatus(AlarmLogStatus.SUCCESS.name());\n this.alarmLogMapper.updateById(alarmLog);\n }\n } catch (AlarmSilentException alarmSilentException) {\n if (alarmLog != null) {\n alarmLog.setStatus(AlarmLogStatus.SILENT.name());\n alarmLog.setErrorReason(StrUtil.maxLength(alarmSilentException.getMessage(), 2000));\n this.alarmLogMapper.updateById(alarmLog);\n }\n } catch (Exception e) {\n log.warn(\"发送告警消息失败\", e);\n if (alarmLog != null) {\n alarmLog.setStatus(AlarmLogStatus.FAILED.name());\n alarmLog.setErrorReason(StrUtil.maxLength(e.getMessage(), 2000));\n this.alarmLogMapper.updateById(alarmLog);\n }\n }\n }\n\n /**\n * 初始化内置请求参数-方便模板配置,以$开头\n *\n * @param alarmMessageBody 告警消息\n * @param requestId 请求ID\n */\n private void builtInParameter(AlarmMessageBody alarmMessageBody, String requestId) {\n Map parameter = alarmMessageBody.getParameter();\n String workspaceCode = alarmMessageBody.getWorkspaceCode();\n if (!parameter.containsKey($_REQUEST_ID)) {\n parameter.put($_REQUEST_ID, requestId);\n }\n if (!parameter.containsKey(SERVER_NAME)) {\n parameter.put(SERVER_NAME, alarmMessageBody.getServerName());\n }\n if (!parameter.containsKey($_INSTANCE_ID)) {\n parameter.put($_INSTANCE_ID, alarmMessageBody.getInstanceId());\n }\n if (!parameter.containsKey($_ALARM_TIME)) {\n parameter.put($_ALARM_TIME, LocalDateTimeUtil.format(alarmMessageBody.getAlarmTime(), Constant.DATE_TIME_FORMAT));\n }\n if (!parameter.containsKey($_WORKSPACE_CODE)) {\n parameter.put($_WORKSPACE_CODE, workspaceCode);\n }\n }\n\n /**\n * 发送告警\n *\n * @param alarmRobot 机器人\n * @param alarmMessageBody 告警消息\n */\n @SneakyThrows\n private void doAlarm(AlarmRobot alarmRobot, AlarmMessageBody alarmMessageBody) {\n String workspaceCode = alarmMessageBody.getWorkspaceCode();\n String robotCode = alarmMessageBody.getRobotCode();\n String templateCode = alarmMessageBody.getTemplateCode();\n Map parameter = alarmMessageBody.getParameter();\n AlarmTemplate alarmTemplate = this.alarmTemplateMapper.selectOne(Wrappers.lambdaQuery()\n .eq(AlarmTemplate::getWorkspaceCode, workspaceCode)\n .eq(AlarmTemplate::getCode, templateCode)\n );\n if (alarmTemplate == null) {\n throw new RuntimeException(\"模板不存在\");\n }\n // 是否启用\n if (!Status.ENABLE.name().equals(alarmTemplate.getStatus())) {\n throw new RuntimeException(\"模板未启用\");\n }\n String templateContent = alarmTemplate.getTemplateContent();\n // 模板套入参数\n if (StrUtil.isNotBlank(templateContent)) {\n // 使用FreeMarker模板引擎处理模板\n templateContent = FreeMarkerUtils.processTemplate(alarmTemplate.getCode(), templateContent, parameter);\n }\n String type = alarmRobot.getType();\n AlarmRobotType alarmRobotType = AlarmRobotType.valueOf(type);\n Content content;\n Robot robot = switch (alarmRobotType) {\n case LARK -> {\n if (StrUtil.isNotBlank(alarmTemplate.getExternalTemplateCode())) {\n LarkContent larkContent = new LarkContent();\n // 外部系统的模板编码,例如飞书的消息卡片 外部\n larkContent.setTemplateId(alarmTemplate.getExternalTemplateCode());\n // 外部消息模板参数\n larkContent.setTemplateParameter(parameter);\n content = larkContent;\n } else {\n content = new TextContent(templateContent);\n }\n yield SpringUtil.getBean(LarkRobot.class);\n }\n case DING_TALK -> {\n content = new TextContent(templateContent);\n yield SpringUtil.getBean(DingTalkRobot.class);\n }\n case WE_COM -> {\n content = new TextContent(templateContent);\n yield SpringUtil.getBean(WeComRobot.class);\n }\n default -> throw new RuntimeException(\"不支持的机器人类型\");\n };\n // 告警沉默判断\n List silents = JSON.parseArray(alarmRobot.getSilent(), Silent.class);\n {\n // 发送的内容,一大串字符串\n String ct = JSON.toJSONString(content);\n if (CollUtil.isNotEmpty(silents)) {\n // 过滤掉过期的规则\n silents.removeIf(silent -> silent.getExpire() != null && silent.getExpire().isBefore(alarmMessageBody.getAlarmTime()));\n // 存在沉默规则\n if (CollUtil.isNotEmpty(silents)) {\n // 收集所有的关键词\n Map keyMap = silents.stream()\n .map(Silent::getKeys).flatMap(Set::stream).collect(Collectors.toMap(k -> k, k -> k));\n // 使用 Aho - Corasick 算法构建关键词匹配器\n AhoCorasickDoubleArrayTrie trie = new AhoCorasickDoubleArrayTrie<>();\n trie.build(keyMap);\n // 进行匹配\n Collection> hits = trie.parseText(ct);\n if (!hits.isEmpty()) {\n // 存在匹配的关键词,不发送消息\n List collect = hits.stream()\n // 最多打印5个命中的关键词\n .limit(5).map(m -> m.value).toList();\n String jsonString = JSON.toJSONString(collect);\n log.info(\"告警消息被沉默,告警消息中包含关键词:{}\", jsonString);\n throw new AlarmSilentException(jsonString);\n }\n }\n }\n }\n List receives = JSON.parseArray(alarmRobot.getReceives(), Receive.class);\n // 判断发送模式\n String mode = alarmRobot.getMode();\n if (Objects.equals(mode, AlarmRobotMode.BROADCAST.name())) {\n // 全部发送\n ParallelStreamUtils.forEach(receives, receive -> {\n robot.send(receive.getKey(), content);\n }, false);\n } else if (Objects.equals(mode, AlarmRobotMode.POLLING.name())) {\n // 轮询发送\n RAtomicLong atomicLong = this.redissonClient.getAtomicLong(RedisKey.ALARM_ROBOT_POLLING.build(workspaceCode + robotCode));\n // 当前自增索引\n long index = atomicLong.incrementAndGet();\n // 总机器人数量\n int size = receives.size();\n // 获取当前要发送的机器人\n Receive receive = receives.get((int) (index % size));\n robot.send(receive.getKey(), content);\n // 如果index超出long最大值,重置\n if (index ==\n // 提前重置\n Long.MAX_VALUE - 10000) {\n // 告警不需要高精度轮询\n atomicLong.set(0);\n }\n } else if (Objects.equals(mode, AlarmRobotMode.RANDOM.name())) {\n // 随机发送\n Receive receive = receives.get((int) (Math.random() * receives.size()));\n robot.send(receive.getKey(), content);\n } else {\n throw new RuntimeException(\"不支持的发送模式\");\n }\n }\n\n}\n"], ["/data-platform-open/data-platform-open-web/src/main/java/cn/dataplatform/open/web/interceptor/WorkspaceInterceptor.java", "package cn.dataplatform.open.web.interceptor;\n\n\nimport cn.dataplatform.open.common.component.OrikaMapper;\nimport cn.dataplatform.open.common.enums.ErrorCode;\nimport cn.dataplatform.open.common.exception.ApiException;\nimport cn.dataplatform.open.web.config.Context;\nimport cn.dataplatform.open.web.service.UserWorkspaceService;\nimport cn.dataplatform.open.web.service.WorkspaceService;\nimport cn.dataplatform.open.web.store.entity.UserWorkspace;\nimport cn.dataplatform.open.web.store.entity.Workspace;\nimport cn.dataplatform.open.web.vo.user.UserData;\nimport cn.dataplatform.open.web.vo.workspace.WorkspaceData;\nimport cn.hutool.core.util.StrUtil;\nimport jakarta.annotation.Resource;\nimport jakarta.servlet.http.HttpServletRequest;\nimport jakarta.servlet.http.HttpServletResponse;\nimport lombok.extern.slf4j.Slf4j;\nimport org.springframework.lang.NonNull;\nimport org.springframework.stereotype.Component;\nimport org.springframework.web.servlet.AsyncHandlerInterceptor;\n\nimport java.util.Objects;\n\n/**\n * 工作空间权限校验,并把当前工作空间设置到上下文中\n *\n * @author dingqianwen\n * @date 2025/1/19\n * @since 1.0.0\n */\n@Slf4j\n@Component\npublic class WorkspaceInterceptor implements AsyncHandlerInterceptor {\n\n /**\n * http header 中的工作空间\n */\n public static final String X_WORKSPACE = \"X-Workspace\";\n\n @Resource\n private WorkspaceService workspaceService;\n @Resource\n private UserWorkspaceService userWorkspaceService;\n @Resource\n private OrikaMapper orikaMapper;\n\n /**\n * 校验工作空间权限\n *\n * @param request 请求\n * @param response 响应\n * @param handler 处理器\n * @return 是否通过\n */\n @Override\n public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) {\n String xWorkspace = request.getHeader(WorkspaceInterceptor.X_WORKSPACE);\n if (StrUtil.isEmpty(xWorkspace)) {\n throw new ApiException(ErrorCode.DP_10011041);\n }\n Long workspaceId = Long.valueOf(xWorkspace);\n log.info(\"当前工作空间:{}\", workspaceId);\n Workspace workspace = this.workspaceService.lambdaQuery().eq(Workspace::getId, workspaceId).one();\n if (workspace == null) {\n throw new ApiException(ErrorCode.DP_10011040);\n }\n // 部分场景可能不需要登录状态,也就是没有用户信息\n UserData userData = Context.getUser();\n // 1为工作空间管理员\n Integer isWorkspaceAdmin = 0;\n if (userData != null &&\n // 不是管理员才需要校验\n !Objects.equals(userData.getUsername(), UserData.ADMIN)) {\n UserWorkspace userWorkspace = this.userWorkspaceService.lambdaQuery()\n .eq(UserWorkspace::getUserId, userData.getId())\n .eq(UserWorkspace::getWorkspaceId, workspaceId).one();\n if (userWorkspace == null) {\n throw new ApiException(\"用户没有权限访问此工作空间\");\n }\n isWorkspaceAdmin = userWorkspace.getIsAdmin();\n }\n WorkspaceData data = new WorkspaceData();\n this.orikaMapper.map(workspace, data);\n data.setIsWorkspaceAdmin(isWorkspaceAdmin == 1);\n Context.setWorkspace(data);\n return true;\n }\n\n\n}\n"], ["/data-platform-open/data-platform-open-flow/src/main/java/cn/dataplatform/open/flow/listener/DataSourceMessageListener.java", "package cn.dataplatform.open.flow.listener;\n\nimport cn.dataplatform.open.common.alarm.scene.ServerMessageExceptionScene;\nimport cn.dataplatform.open.common.body.AlarmSceneMessageBody;\nimport cn.dataplatform.open.common.body.DataSourceMessageBody;\nimport cn.dataplatform.open.common.constant.Constant;\nimport cn.dataplatform.open.common.event.AlarmSceneEvent;\nimport cn.dataplatform.open.flow.config.RabbitConfig;\nimport cn.dataplatform.open.flow.service.DataSourceService;\nimport jakarta.annotation.Resource;\nimport lombok.extern.slf4j.Slf4j;\nimport org.slf4j.MDC;\nimport org.springframework.amqp.core.ExchangeTypes;\nimport org.springframework.amqp.rabbit.annotation.Exchange;\nimport org.springframework.amqp.rabbit.annotation.Queue;\nimport org.springframework.amqp.rabbit.annotation.QueueBinding;\nimport org.springframework.amqp.rabbit.annotation.RabbitListener;\nimport org.springframework.context.ApplicationEventPublisher;\nimport org.springframework.messaging.Message;\nimport org.springframework.stereotype.Component;\n\n/**\n * 〈一句话功能简述〉 \n * 〈〉\n *\n * @author dingqianwen\n * @date 2025/1/11\n * @since 1.0.0\n */\n@Slf4j\n@Component\npublic class DataSourceMessageListener {\n\n @Resource\n private DataSourceService dataSourceService;\n @Resource\n private ApplicationEventPublisher applicationEventPublisher;\n\n\n @RabbitListener(bindings = @QueueBinding(\n value = @Queue,\n exchange = @Exchange(value = RabbitConfig.SOURCE_EXCHANGE, type = ExchangeTypes.FANOUT)\n ))\n public void onMessage(Message messaging) {\n String requestId = messaging.getHeaders().get(Constant.REQUEST_ID, String.class);\n MDC.put(Constant.REQUEST_ID, requestId);\n DataSourceMessageBody dataSourceMessageBody = messaging.getPayload();\n try {\n log.info(\"数据源消息:{}\", dataSourceMessageBody);\n DataSourceMessageBody.Type type = dataSourceMessageBody.getType();\n switch (type) {\n case UPDATE:\n this.dataSourceService.remove(dataSourceMessageBody.getId());\n this.dataSourceService.load(dataSourceMessageBody.getId());\n break;\n case LOAD:\n this.dataSourceService.load(dataSourceMessageBody.getId());\n break;\n case REMOVE:\n this.dataSourceService.remove(dataSourceMessageBody.getId());\n break;\n default:\n break;\n }\n } catch (Exception e) {\n String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();\n ServerMessageExceptionScene scene = new ServerMessageExceptionScene(e);\n scene.setQueue(RabbitConfig.SOURCE_QUEUE);\n scene.setExchange(RabbitConfig.SOURCE_EXCHANGE);\n scene.setConsumerClassName(this.getClass().getName());\n scene.setConsumerMethodName(methodName);\n AlarmSceneMessageBody alarmSceneMessageBody = new AlarmSceneMessageBody(scene);\n alarmSceneMessageBody.setWorkspaceCode(dataSourceMessageBody.getWorkspaceCode());\n this.applicationEventPublisher.publishEvent(new AlarmSceneEvent(alarmSceneMessageBody));\n throw e;\n } finally {\n MDC.clear();\n }\n }\n\n}\n"], ["/data-platform-open/data-platform-open-common/src/main/java/cn/dataplatform/open/common/server/ServerManager.java", "package cn.dataplatform.open.common.server;\n\nimport cn.dataplatform.open.common.alarm.scene.ServiceOfflineNoticeScene;\nimport cn.dataplatform.open.common.alarm.scene.ServiceOnlineNoticeScene;\nimport cn.dataplatform.open.common.body.AlarmSceneMessageBody;\nimport cn.dataplatform.open.common.component.JsonJacksonCodec;\nimport cn.dataplatform.open.common.constant.Constant;\nimport cn.dataplatform.open.common.enums.RedisKey;\nimport cn.dataplatform.open.common.enums.ServerStatus;\nimport cn.dataplatform.open.common.event.AlarmSceneEvent;\nimport cn.dataplatform.open.common.util.IPUtils;\nimport cn.hutool.core.collection.CollUtil;\nimport cn.hutool.core.lang.UUID;\nimport jakarta.annotation.Resource;\nimport lombok.Getter;\nimport lombok.extern.slf4j.Slf4j;\nimport org.redisson.api.RMapCache;\nimport org.redisson.api.RedissonClient;\nimport org.slf4j.MDC;\nimport org.springframework.beans.factory.DisposableBean;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.boot.web.servlet.context.ServletWebServerInitializedEvent;\nimport org.springframework.context.ApplicationEventPublisher;\nimport org.springframework.context.ApplicationListener;\nimport org.springframework.context.annotation.DependsOn;\nimport org.springframework.core.annotation.Order;\nimport org.springframework.lang.NonNull;\nimport org.springframework.stereotype.Component;\n\nimport java.math.BigDecimal;\nimport java.time.LocalDateTime;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.ScheduledExecutorService;\nimport java.util.concurrent.TimeUnit;\n\n/**\n * DependsOn({\"redisson\", \"eventPublisherListener\"}) 解决优雅停机时此组件被提前关闭,例如 redisson is shutdown\n * o.s.beans.factory.support.DisposableBeanAdapter -[]- Invocation of destroy method failed on bean with name 'serverManager': org.springframework.amqp.AmqpApplicationContextClosedException:\n * The ApplicationContext is closed and the ConnectionFactory can no longer create connections.\n *\n * @author dingqianwen\n * @date 2025/1/26\n * @since 1.0.0\n */\n@DependsOn({\"redisson\", \"eventPublisherListener\"})\n@Order(0)\n@Slf4j\n@Component\npublic class ServerManager implements ApplicationListener, DisposableBean {\n\n /**\n * 启动时间\n */\n @Getter\n public LocalDateTime startTime;\n /**\n * 销毁时,先销毁此线程池,防止还在一直注册\n */\n private final ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();\n\n\n @Value(\"${server.port:}\")\n private Integer port;\n @Value(\"${spring.application.name:unknown}\")\n @Getter\n private String applicationName;\n\n @Resource\n private RedissonClient redissonClient;\n @Resource\n private ApplicationEventPublisher applicationEventPublisher;\n @Resource\n private ServerMonitor serverMonitor;\n\n /**\n * 服务注册\n *\n * @param event 事件\n */\n @Override\n public void onApplicationEvent(@NonNull ServletWebServerInitializedEvent event) {\n String requestId = UUID.randomUUID().toString(true);\n try {\n MDC.put(Constant.REQUEST_ID, requestId);\n log.info(\"服务启动成功,开始注册服务信息\");\n // 服务启动通知\n AlarmSceneMessageBody alarmSceneMessageBody = new AlarmSceneMessageBody(new ServiceOnlineNoticeScene());\n this.applicationEventPublisher.publishEvent(new AlarmSceneEvent(alarmSceneMessageBody));\n } finally {\n MDC.remove(Constant.REQUEST_ID);\n }\n String hostAddress = IPUtils.SERVER_IP;\n String instanceId = hostAddress + \":\" + this.port;\n RMapCache mapCache = this.redissonClient.getMapCache(RedisKey.SERVERS.build(this.applicationName)\n , new JsonJacksonCodec());\n // 注册服务实例,并定期心跳\n this.scheduledExecutorService.scheduleAtFixedRate(() -> {\n MDC.put(Constant.REQUEST_ID, requestId);\n try {\n Server server = mapCache.get(instanceId);\n // 如果之前没有注册过\n if (server == null) {\n server = new Server();\n server.setHost(hostAddress);\n server.setPort(this.port);\n server.setFastHeartbeat(LocalDateTime.now());\n } else {\n server.setStatus(null);\n }\n if (this.startTime == null) {\n this.startTime = LocalDateTime.now();\n // 当前服务启动时间\n server.setLatelyStartTime(startTime);\n }\n // bug修复,运行期间,手动删除redis数据\n if (server.getLatelyStartTime() == null) {\n server.setLatelyStartTime(this.startTime);\n }\n server.setLastHeartbeat(LocalDateTime.now());\n // 上报内存和cpu使用率,方便后续做负载均衡调度\n BigDecimal jvmCpuUsage = this.serverMonitor.getJvmCpuUsage();\n // 第一次获取可能为空,再次获取一次\n if (jvmCpuUsage.compareTo(BigDecimal.ZERO) == 0) {\n jvmCpuUsage = this.serverMonitor.getJvmCpuUsage();\n }\n server.setTotalMemory(this.serverMonitor.getJvmTotalMemory());\n server.setFreeMemory(this.serverMonitor.getJvmFreeMemory());\n server.setCpuUsageRatio(jvmCpuUsage);\n // 过期时间默认一周\n mapCache.put(instanceId, server, 24 * 7, TimeUnit.HOURS);\n log.debug(\"服务实例心跳 : {}\", instanceId);\n } catch (Exception e) {\n log.error(\"服务实例心跳异常\", e);\n } finally {\n MDC.clear();\n }\n }, 0, 10, TimeUnit.SECONDS);\n }\n\n /**\n * 主动销毁\n */\n @Override\n public void destroy() {\n String requestId = UUID.randomUUID().toString(true);\n try {\n MDC.put(Constant.REQUEST_ID, requestId);\n log.info(\"服务即将关闭,开始服务实例注销\");\n this.scheduledExecutorService.shutdown();\n String instanceId = this.instanceId();\n RMapCache