You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@seatunnel.apache.org by GitBox <gi...@apache.org> on 2022/10/27 05:07:33 UTC

[GitHub] [incubator-seatunnel] 531651225 commented on a diff in pull request #3164: [Feature][Connector-V2] Starrocks sink connector

531651225 commented on code in PR #3164:
URL: https://github.com/apache/incubator-seatunnel/pull/3164#discussion_r1006406674


##########
seatunnel-connectors-v2/connector-starrocks/src/main/java/org/apache/seatunnel/connectors/seatunnel/starrocks/client/StarRocksStreamLoadVisitor.java:
##########
@@ -0,0 +1,324 @@
+/*
+ * 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.seatunnel.connectors.seatunnel.starrocks.client;
+
+import org.apache.seatunnel.common.utils.JsonUtils;
+import org.apache.seatunnel.connectors.seatunnel.starrocks.config.SinkConfig;
+import org.apache.seatunnel.connectors.seatunnel.starrocks.serialize.StarRocksDelimiterParser;
+
+import org.apache.commons.codec.binary.Base64;
+import org.apache.http.HttpEntity;
+import org.apache.http.HttpStatus;
+import org.apache.http.client.config.RequestConfig;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpPut;
+import org.apache.http.entity.ByteArrayEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.DefaultRedirectStrategy;
+import org.apache.http.impl.client.HttpClientBuilder;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.util.EntityUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
+
+public class StarRocksStreamLoadVisitor {
+
+    private static final Logger LOG = LoggerFactory.getLogger(StarRocksStreamLoadVisitor.class);
+    private static final int CONNECT_TIMEOUT = 1000000;
+    private static final int MAX_SLEEP_TIME = 5;
+
+    private final SinkConfig sinkConfig;
+    private long pos;
+    private static final String RESULT_FAILED = "Fail";
+    private static final String RESULT_LABEL_EXISTED = "Label Already Exists";
+    private static final String LAEBL_STATE_VISIBLE = "VISIBLE";
+    private static final String LAEBL_STATE_COMMITTED = "COMMITTED";
+    private static final String RESULT_LABEL_PREPARE = "PREPARE";
+    private static final String RESULT_LABEL_ABORTED = "ABORTED";
+    private static final String RESULT_LABEL_UNKNOWN = "UNKNOWN";
+
+    private List<String> fieldNames;
+
+    public StarRocksStreamLoadVisitor(SinkConfig sinkConfig, List<String> fieldNames) {
+        this.sinkConfig = sinkConfig;
+        this.fieldNames = fieldNames;
+    }
+
+    public void doStreamLoad(StarRocksFlushTuple flushData) throws IOException {
+        String host = getAvailableHost();
+        if (null == host) {
+            throw new IOException("None of the host in `load_url` could be connected.");
+        }
+        String loadUrl = new StringBuilder(host)
+                .append("/api/")
+                .append(sinkConfig.getDatabase())
+                .append("/")
+                .append(sinkConfig.getTable())
+                .append("/_stream_load")
+                .toString();
+        if (LOG.isDebugEnabled()) {
+            LOG.debug(String.format("Start to join batch data: rows[%d] bytes[%d] label[%s].", flushData.getRows().size(), flushData.getBytes(), flushData.getLabel()));
+        }
+        Map<String, Object> loadResult = doHttpPut(loadUrl, flushData.getLabel(), joinRows(flushData.getRows(), flushData.getBytes().intValue()));
+        final String keyStatus = "Status";
+        if (null == loadResult || !loadResult.containsKey(keyStatus)) {
+            LOG.error("unknown result status. {}", loadResult);
+            throw new IOException("Unable to flush data to StarRocks: unknown result status. " + loadResult);
+        }
+        if (LOG.isDebugEnabled()) {
+            LOG.debug(new StringBuilder("StreamLoad response:\n").append(JsonUtils.toJsonString(loadResult)).toString());
+        }
+        if (RESULT_FAILED.equals(loadResult.get(keyStatus))) {
+            StringBuilder errorBuilder = new StringBuilder("Failed to flush data to StarRocks.\n");
+            if (loadResult.containsKey("Message")) {
+                errorBuilder.append(loadResult.get("Message"));
+                errorBuilder.append('\n');
+            }
+            if (loadResult.containsKey("ErrorURL")) {
+                LOG.error("StreamLoad response: {}", loadResult);
+                try {
+                    errorBuilder.append(doHttpGet(loadResult.get("ErrorURL").toString()));
+                    errorBuilder.append('\n');
+                } catch (IOException e) {
+                    LOG.warn("Get Error URL failed. {} ", loadResult.get("ErrorURL"), e);
+                }
+            } else {
+                errorBuilder.append(JsonUtils.toJsonString(loadResult));
+                errorBuilder.append('\n');
+            }
+            throw new IOException(errorBuilder.toString());
+        } else if (RESULT_LABEL_EXISTED.equals(loadResult.get(keyStatus))) {
+            LOG.debug(new StringBuilder("StreamLoad response:\n").append(JsonUtils.toJsonString(loadResult)).toString());
+            // has to block-checking the state to get the final result
+            checkLabelState(host, flushData.getLabel());
+        }
+    }
+
+    private String getAvailableHost() {
+        List<String> hostList = sinkConfig.getNodeUrls();
+        long tmp = pos + hostList.size();
+        for (; pos < tmp; pos++) {
+            String host = new StringBuilder("http://").append(hostList.get((int) (pos % hostList.size()))).toString();
+            if (tryHttpConnection(host)) {
+                return host;
+            }
+        }
+        return null;
+    }
+
+    private boolean tryHttpConnection(String host) {
+        try {
+            URL url = new URL(host);
+            HttpURLConnection co = (HttpURLConnection) url.openConnection();
+            co.setConnectTimeout(CONNECT_TIMEOUT);
+            co.connect();
+            co.disconnect();
+            return true;
+        } catch (Exception e1) {
+            LOG.warn("Failed to connect to address:{}", host, e1);
+            return false;
+        }
+    }
+
+    private byte[] joinRows(List<byte[]> rows, int totalBytes) {
+        if (SinkConfig.StreamLoadFormat.CSV.equals(sinkConfig.getLoadFormat())) {
+            Map<String, Object> props = sinkConfig.getStreamLoadProps();
+            byte[] lineDelimiter = StarRocksDelimiterParser.parse((String) props.get("row_delimiter"), "\n").getBytes(StandardCharsets.UTF_8);
+            ByteBuffer bos = ByteBuffer.allocate(totalBytes + rows.size() * lineDelimiter.length);
+            for (byte[] row : rows) {
+                bos.put(row);
+                bos.put(lineDelimiter);
+            }
+            return bos.array();
+        }
+
+        if (SinkConfig.StreamLoadFormat.JSON.equals(sinkConfig.getLoadFormat())) {
+            ByteBuffer bos = ByteBuffer.allocate(totalBytes + (rows.isEmpty() ? 2 : rows.size() + 1));
+            bos.put("[".getBytes(StandardCharsets.UTF_8));
+            byte[] jsonDelimiter = ",".getBytes(StandardCharsets.UTF_8);
+            boolean isFirstElement = true;
+            for (byte[] row : rows) {
+                if (!isFirstElement) {
+                    bos.put(jsonDelimiter);
+                }
+                bos.put(row);
+                isFirstElement = false;
+            }
+            bos.put("]".getBytes(StandardCharsets.UTF_8));
+            return bos.array();
+        }
+        throw new RuntimeException("Failed to join rows data, unsupported `format` from stream load properties:");
+    }
+
+    @SuppressWarnings("unchecked")
+    private void checkLabelState(String host, String label) throws IOException {
+        int idx = 0;
+        while (true) {
+            try {
+                TimeUnit.SECONDS.sleep(Math.min(++idx, MAX_SLEEP_TIME));
+            } catch (InterruptedException ex) {
+                break;
+            }
+            try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
+                HttpGet httpGet = new HttpGet(new StringBuilder(host).append("/api/").append(sinkConfig.getDatabase()).append("/get_load_state?label=").append(label).toString());
+                httpGet.setHeader("Authorization", getBasicAuthHeader(sinkConfig.getUsername(), sinkConfig.getPassword()));
+                httpGet.setHeader("Connection", "close");
+                try (CloseableHttpResponse resp = httpclient.execute(httpGet)) {
+                    HttpEntity respEntity = getHttpEntity(resp);
+                    if (respEntity == null) {
+                        throw new IOException(String.format("Failed to flush data to StarRocks, Error " +
+                                "could not get the final state of label[%s].\n", label), null);
+                    }
+
+                    Map<String, Object> result = JsonUtils.parseObject(EntityUtils.toString(respEntity), Map.class);
+                    String labelState = (String) result.get("state");
+                    if (null == labelState) {
+                        throw new IOException(String.format("Failed to flush data to StarRocks, Error " +
+                                "could not get the final state of label[%s]. response[%s]\n", label, EntityUtils.toString(respEntity)), null);
+                    }
+                    LOG.info(String.format("Checking label[%s] state[%s]\n", label, labelState));
+                    switch (labelState) {
+                        case LAEBL_STATE_VISIBLE:
+                        case LAEBL_STATE_COMMITTED:
+                            return;
+                        case RESULT_LABEL_PREPARE:
+                            continue;
+                        case RESULT_LABEL_ABORTED:
+                            throw new StarRocksStreamLoadFailedException(String.format("Failed to flush data to StarRocks, Error " +
+                                    "label[%s] state[%s]\n", label, labelState), null, true);
+                        case RESULT_LABEL_UNKNOWN:
+                        default:
+                            throw new StarRocksStreamLoadFailedException(String.format("Failed to flush data to StarRocks, Error " +
+                                    "label[%s] state[%s]\n", label, labelState), null);
+                    }
+                }
+            }
+        }
+    }
+
+    @SuppressWarnings("unchecked")
+    private Map<String, Object> doHttpPut(String loadUrl, String label, byte[] data) throws IOException {

Review Comment:
   > How about Http related methods written in a separate class?
   
   thinks,i have fixed above . PTAL



-- 
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@seatunnel.apache.org

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