You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@doris.apache.org by GitBox <gi...@apache.org> on 2021/03/21 14:31:07 UTC

[GitHub] [incubator-doris] morningman commented on a change in pull request #5452: [Audit][Stream Load] Support audit function for stream load

morningman commented on a change in pull request #5452:
URL: https://github.com/apache/incubator-doris/pull/5452#discussion_r598279486



##########
File path: be/src/common/config.h
##########
@@ -348,6 +348,12 @@ CONF_mInt32(streaming_load_rpc_max_alive_time_sec, "1200");
 CONF_Int32(tablet_writer_open_rpc_timeout_sec, "60");
 // You can ignore brpc error '[E1011]The server is overcrowded' when writing data.
 CONF_mBool(tablet_writer_ignore_eovercrowded, "false");
+// batch size of stream load record reported to FE
+CONF_mInt32(stream_load_record_batch_size, "50");
+// expire time of stream load record in rocksdb. 1000*1000*60*60*8=28800000000(8 hour)
+CONF_mInt64(stream_load_record_expire_time_us, "28800000000");

Review comment:
       better use more readable config, I suggest using HOUR.

##########
File path: be/src/olap/storage_engine.cpp
##########
@@ -225,6 +226,35 @@ Status StorageEngine::_init_store_map() {
     for (auto store : tmp_stores) {
         _store_map.emplace(store->path(), store);
     }
+
+    auto st = _init_stream_load_record();
+    if (!st.ok()) {
+        LOG(WARNING) << "status=" << st.to_string();

Review comment:
       Do we need to stop the startup if this error happen?

##########
File path: fe/fe-core/src/main/java/org/apache/doris/load/StreamLoadRecordMgr.java
##########
@@ -0,0 +1,112 @@
+// 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.doris.load;
+
+import com.google.common.collect.ImmutableMap;
+import org.apache.doris.catalog.Catalog;
+import org.apache.doris.common.ClientPool;
+import org.apache.doris.common.Config;
+import org.apache.doris.plugin.AuditEvent;
+import org.apache.doris.plugin.AuditEvent.EventType;
+import org.apache.doris.plugin.StreamLoadAuditEvent;
+import org.apache.doris.system.Backend;
+import org.apache.doris.thrift.BackendService;
+import org.apache.doris.thrift.TNetworkAddress;
+import org.apache.doris.thrift.TStreamLoadRecord;
+import org.apache.doris.thrift.TStreamLoadRecordResult;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+
+public class StreamLoadRecordMgr {
+    private static final Logger LOG = LogManager.getLogger(StreamLoadRecordMgr.class);
+    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
+
+    public StreamLoadRecordMgr() {
+        Thread pullStreamLoadRecordThread = new Thread(new PullStreamLoadRecordThread());
+        pullStreamLoadRecordThread.start();
+    }
+
+    private class PullStreamLoadRecordThread implements Runnable {
+        @Override
+        public void run() {
+            ImmutableMap<Long, Backend> backends = Catalog.getCurrentSystemInfo().getIdToBackend();
+
+            while (true) {
+                long start = System.currentTimeMillis();
+                for (Backend backend : backends.values()) {
+                    BackendService.Client client = null;
+                    TNetworkAddress address = null;
+                    boolean ok = false;
+                    try {
+                        address = new TNetworkAddress(backend.getHost(), backend.getBePort());
+                        client = ClientPool.backendPool.borrowObject(address);
+                        TStreamLoadRecordResult result = client.getStreamLoadRecord(backend.getLastStreamLoadTime());
+                        Map<String, TStreamLoadRecord> streamLoadRecordBatch = result.getStreamLoadRecord();
+                        LOG.info("receive stream load audit info from backend: {}. batch size: {}", backend.getHost(), streamLoadRecordBatch.size());
+                        for (Map.Entry<String, TStreamLoadRecord> entry : streamLoadRecordBatch.entrySet()) {
+                            TStreamLoadRecord streamLoadItem= entry.getValue();
+                            LOG.info("receive stream load record info from backend: {}. label: {}, db: {}, tbl: {}, user: {}, user_ip: {}," +

Review comment:
       Use debug level

##########
File path: be/src/http/action/stream_load.cpp
##########
@@ -132,9 +134,19 @@ void StreamLoadAction::handle(HttpRequest* req) {
     str = str + '\n';
     HttpChannel::send_reply(req, str);
 
+    auto stream_load_record = StorageEngine::instance()->get_stream_load_record();

Review comment:
       Extract a method for here and the same code in `on_header()`?

##########
File path: fe/fe-core/src/main/java/org/apache/doris/load/StreamLoadRecordMgr.java
##########
@@ -0,0 +1,112 @@
+// 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.doris.load;
+
+import com.google.common.collect.ImmutableMap;

Review comment:
       Reorder the import

##########
File path: fe/fe-core/src/main/java/org/apache/doris/system/Backend.java
##########
@@ -95,6 +95,8 @@
     // additional backendStatus information for BE, display in JSON format
     private BackendStatus backendStatus = new BackendStatus();
 
+    private String lastStreamLoadTime = "";

Review comment:
       Why not using timestamp as Long?
   And this field is not persisted. So every time the FE restart, this field will be reset to
   `1970`?

##########
File path: be/src/runtime/stream_load/stream_load_context.cpp
##########
@@ -89,6 +103,91 @@ std::string StreamLoadContext::to_json() const {
     return s.GetString();
 }
 
+void StreamLoadContext::parse_stream_load_record(std::string stream_load_record, TStreamLoadRecord& stream_load_item) {

Review comment:
       ```suggestion
   void StreamLoadContext::parse_stream_load_record(const std::string& stream_load_record, TStreamLoadRecord& stream_load_item) {
   ```

##########
File path: be/src/runtime/stream_load/stream_load_record.cpp
##########
@@ -0,0 +1,137 @@
+// 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.
+
+#include "runtime/stream_load/stream_load_record.h"
+
+#include "common/config.h"
+#include "common/status.h"
+#include "rocksdb/db.h"
+#include "rocksdb/slice.h"
+#include "rocksdb/options.h"
+#include "rocksdb/slice_transform.h"
+#include "util/time.h"
+
+
+namespace doris {
+const std::string STREAM_LOAD_POSTFIX = "/stream_load";
+const size_t PREFIX_LENGTH = 4;
+
+StreamLoadRecord::StreamLoadRecord(const std::string& root_path)
+        : _root_path(root_path),
+          _db(nullptr) {
+}
+
+StreamLoadRecord::~StreamLoadRecord() {
+    for (auto handle : _handles) {
+        _db->DestroyColumnFamilyHandle(handle);
+        handle = nullptr;
+    }
+    if (_db != nullptr) {
+        delete _db;
+        _db= nullptr;
+    }
+}
+
+Status StreamLoadRecord::init() {
+    // init db
+    rocksdb::DBOptions options;
+    options.IncreaseParallelism();
+    options.create_if_missing = true;
+    options.create_missing_column_families = true;
+    std::string db_path = _root_path + STREAM_LOAD_POSTFIX;
+    std::vector<rocksdb::ColumnFamilyDescriptor> column_families;
+    // default column family is required
+    column_families.emplace_back(DEFAULT_COLUMN_FAMILY, rocksdb::ColumnFamilyOptions());
+    // stream load column family add prefix extractor to improve performance and ensure correctness
+    rocksdb::ColumnFamilyOptions stream_load_column_family;
+    stream_load_column_family.prefix_extractor.reset(rocksdb::NewFixedPrefixTransform(PREFIX_LENGTH));
+    column_families.emplace_back(STREAM_LOAD_COLUMN_FAMILY, stream_load_column_family);
+    rocksdb::Status s = rocksdb::DB::Open(options, db_path, column_families, &_handles, &_db);
+    if (!s.ok() || _db == nullptr) {
+        LOG(WARNING) << "rocks db open failed, reason:" << s.ToString();
+        return Status::InternalError("Stream load record rocksdb open failed");
+    }
+    return Status::OK();
+}
+
+Status StreamLoadRecord::put(const std::string& key, const std::string& value) {
+    rocksdb::ColumnFamilyHandle* handle = _handles[1];
+    rocksdb::WriteOptions write_options;
+    write_options.sync = false;
+    rocksdb::Status s = _db->Put(write_options, handle, rocksdb::Slice(key), rocksdb::Slice(value));
+    if (!s.ok()) {
+        LOG(WARNING) << "rocks db put key:" << key << " failed, reason:" << s.ToString();
+        return Status::InternalError("Stream load record rocksdb put failed");
+    }
+    return Status::OK();
+}
+
+Status StreamLoadRecord::get_batch(const std::string& start, const int batch_size, std::map<std::string, std::string> &stream_load_records) {
+    rocksdb::ColumnFamilyHandle* handle = _handles[1];
+    std::unique_ptr<rocksdb::Iterator> it(_db->NewIterator(rocksdb::ReadOptions(), handle));
+    if (start == "") {
+        it->SeekToFirst();
+    } else {
+        it->Seek(start);
+        rocksdb::Status status = it->status();
+        if (!status.ok()) {
+            it->SeekToFirst();
+        }
+    }
+    rocksdb::Status status = it->status();
+    if (!status.ok()) {
+        LOG(WARNING) << "rocksdb seek failed. reason:" << status.ToString();
+        return Status::InternalError("Stream load record rocksdb seek failed");
+    }
+    int num = 0;
+    for (it->Next(); it->Valid(); it->Next()) {
+        std::string key = it->key().ToString();
+        std::string value = it->value().ToString();
+        stream_load_records[key] = value;
+        num++;
+        if (num >= batch_size) {
+            return Status::OK();
+        }
+    }
+    return Status::OK();
+}
+
+Status StreamLoadRecord::clean_expired_stream_load_record() {

Review comment:
       How about using TTL feature of rocksdb to do this.

##########
File path: be/src/runtime/stream_load/stream_load_record.cpp
##########
@@ -0,0 +1,137 @@
+// 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.
+
+#include "runtime/stream_load/stream_load_record.h"
+
+#include "common/config.h"
+#include "common/status.h"
+#include "rocksdb/db.h"
+#include "rocksdb/slice.h"
+#include "rocksdb/options.h"
+#include "rocksdb/slice_transform.h"
+#include "util/time.h"
+
+
+namespace doris {
+const std::string STREAM_LOAD_POSTFIX = "/stream_load";
+const size_t PREFIX_LENGTH = 4;
+
+StreamLoadRecord::StreamLoadRecord(const std::string& root_path)
+        : _root_path(root_path),
+          _db(nullptr) {
+}
+
+StreamLoadRecord::~StreamLoadRecord() {
+    for (auto handle : _handles) {
+        _db->DestroyColumnFamilyHandle(handle);
+        handle = nullptr;
+    }
+    if (_db != nullptr) {

Review comment:
       This logic is strange. If we need to check `_db` is null here, than the above `_db->DestroyColumnFamilyHandle(handle);` also need to check.

##########
File path: be/src/runtime/stream_load/stream_load_record.cpp
##########
@@ -0,0 +1,137 @@
+// 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.
+
+#include "runtime/stream_load/stream_load_record.h"
+
+#include "common/config.h"
+#include "common/status.h"
+#include "rocksdb/db.h"
+#include "rocksdb/slice.h"
+#include "rocksdb/options.h"
+#include "rocksdb/slice_transform.h"
+#include "util/time.h"
+
+
+namespace doris {
+const std::string STREAM_LOAD_POSTFIX = "/stream_load";
+const size_t PREFIX_LENGTH = 4;
+
+StreamLoadRecord::StreamLoadRecord(const std::string& root_path)
+        : _root_path(root_path),
+          _db(nullptr) {
+}
+
+StreamLoadRecord::~StreamLoadRecord() {
+    for (auto handle : _handles) {
+        _db->DestroyColumnFamilyHandle(handle);
+        handle = nullptr;
+    }
+    if (_db != nullptr) {
+        delete _db;
+        _db= nullptr;
+    }
+}
+
+Status StreamLoadRecord::init() {
+    // init db
+    rocksdb::DBOptions options;
+    options.IncreaseParallelism();
+    options.create_if_missing = true;
+    options.create_missing_column_families = true;
+    std::string db_path = _root_path + STREAM_LOAD_POSTFIX;
+    std::vector<rocksdb::ColumnFamilyDescriptor> column_families;
+    // default column family is required
+    column_families.emplace_back(DEFAULT_COLUMN_FAMILY, rocksdb::ColumnFamilyOptions());
+    // stream load column family add prefix extractor to improve performance and ensure correctness
+    rocksdb::ColumnFamilyOptions stream_load_column_family;
+    stream_load_column_family.prefix_extractor.reset(rocksdb::NewFixedPrefixTransform(PREFIX_LENGTH));
+    column_families.emplace_back(STREAM_LOAD_COLUMN_FAMILY, stream_load_column_family);
+    rocksdb::Status s = rocksdb::DB::Open(options, db_path, column_families, &_handles, &_db);
+    if (!s.ok() || _db == nullptr) {
+        LOG(WARNING) << "rocks db open failed, reason:" << s.ToString();
+        return Status::InternalError("Stream load record rocksdb open failed");
+    }
+    return Status::OK();
+}
+
+Status StreamLoadRecord::put(const std::string& key, const std::string& value) {
+    rocksdb::ColumnFamilyHandle* handle = _handles[1];
+    rocksdb::WriteOptions write_options;
+    write_options.sync = false;
+    rocksdb::Status s = _db->Put(write_options, handle, rocksdb::Slice(key), rocksdb::Slice(value));
+    if (!s.ok()) {
+        LOG(WARNING) << "rocks db put key:" << key << " failed, reason:" << s.ToString();
+        return Status::InternalError("Stream load record rocksdb put failed");
+    }
+    return Status::OK();
+}
+
+Status StreamLoadRecord::get_batch(const std::string& start, const int batch_size, std::map<std::string, std::string> &stream_load_records) {

Review comment:
       Use pointer to indicate the passout parameter, like:
   `std::map<std::string, std::string>* stream_load_records`

##########
File path: fe/fe-core/src/main/java/org/apache/doris/load/StreamLoadRecordMgr.java
##########
@@ -0,0 +1,112 @@
+// 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.doris.load;
+
+import com.google.common.collect.ImmutableMap;
+import org.apache.doris.catalog.Catalog;
+import org.apache.doris.common.ClientPool;
+import org.apache.doris.common.Config;
+import org.apache.doris.plugin.AuditEvent;
+import org.apache.doris.plugin.AuditEvent.EventType;
+import org.apache.doris.plugin.StreamLoadAuditEvent;
+import org.apache.doris.system.Backend;
+import org.apache.doris.thrift.BackendService;
+import org.apache.doris.thrift.TNetworkAddress;
+import org.apache.doris.thrift.TStreamLoadRecord;
+import org.apache.doris.thrift.TStreamLoadRecordResult;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+
+public class StreamLoadRecordMgr {
+    private static final Logger LOG = LogManager.getLogger(StreamLoadRecordMgr.class);
+    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
+
+    public StreamLoadRecordMgr() {
+        Thread pullStreamLoadRecordThread = new Thread(new PullStreamLoadRecordThread());
+        pullStreamLoadRecordThread.start();
+    }
+
+    private class PullStreamLoadRecordThread implements Runnable {
+        @Override
+        public void run() {
+            ImmutableMap<Long, Backend> backends = Catalog.getCurrentSystemInfo().getIdToBackend();
+
+            while (true) {
+                long start = System.currentTimeMillis();
+                for (Backend backend : backends.values()) {
+                    BackendService.Client client = null;
+                    TNetworkAddress address = null;
+                    boolean ok = false;
+                    try {
+                        address = new TNetworkAddress(backend.getHost(), backend.getBePort());
+                        client = ClientPool.backendPool.borrowObject(address);
+                        TStreamLoadRecordResult result = client.getStreamLoadRecord(backend.getLastStreamLoadTime());
+                        Map<String, TStreamLoadRecord> streamLoadRecordBatch = result.getStreamLoadRecord();
+                        LOG.info("receive stream load audit info from backend: {}. batch size: {}", backend.getHost(), streamLoadRecordBatch.size());
+                        for (Map.Entry<String, TStreamLoadRecord> entry : streamLoadRecordBatch.entrySet()) {
+                            TStreamLoadRecord streamLoadItem= entry.getValue();
+                            LOG.info("receive stream load record info from backend: {}. label: {}, db: {}, tbl: {}, user: {}, user_ip: {}," +
+                                            " status: {}, message: {}, error_url: {}, total_rows: {}, loaded_rows: {}, filtered_rows: {}," +
+                                            " unselected_rows: {}, load_bytes: {}, start_time: {}, finish_time: {}.",
+                                    backend.getHost(), streamLoadItem.getLabel(), streamLoadItem.getDb(), streamLoadItem.getTbl(), streamLoadItem.getUser(), streamLoadItem.getUserIp(),
+                                    streamLoadItem.getStatus(), streamLoadItem.getMessage(), streamLoadItem.getUrl(), streamLoadItem.getTotalRows(), streamLoadItem.getLoadedRows(),
+                                    streamLoadItem.getFilteredRows(), streamLoadItem.getUnselectedRows(), streamLoadItem.getLoadBytes(), streamLoadItem.getStartTime(),
+                                    streamLoadItem.getFinishTime());
+
+                            AuditEvent auditEvent = new StreamLoadAuditEvent.AuditEventBuilder().setEventType(EventType.STREAM_LOAD_FINISH)
+                                    .setLabel(streamLoadItem.getLabel()).setDb(streamLoadItem.getDb()).setTable(streamLoadItem.getTbl())
+                                    .setUser(streamLoadItem.getUser()).setClientIp(streamLoadItem.getUserIp()).setStatus(streamLoadItem.getStatus())
+                                    .setMessage(streamLoadItem.getMessage()).setUrl(streamLoadItem.getUrl()).setTotalRows(streamLoadItem.getTotalRows())
+                                    .setLoadedRows( streamLoadItem.getLoadedRows()).setFilteredRows(streamLoadItem.getFilteredRows())
+                                    .setUnselectedRows(streamLoadItem.getUnselectedRows()).setLoadBytes(streamLoadItem.getLoadBytes())
+                                    .setStartTime(streamLoadItem.getStartTime()).setFinishTime(streamLoadItem.getFinishTime())
+                                    .build();
+                            Catalog.getCurrentCatalog().getAuditEventProcessor().handleAuditEvent(auditEvent);
+                            if (entry.getKey().compareTo(backend.getLastStreamLoadTime()) > 0) {
+                                backend.setLastStreamLoadTime(entry.getKey());

Review comment:
       We can find the max timestamp of this batch and call `setLastStreamLoadTime` once.




-- 
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.

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



---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org