DBImpl.cpp 97.5 KB
Newer Older
1
// Copyright (C) 2019-2020 Zilliz. All rights reserved.
J
jinhai 已提交
2
//
3 4
// Licensed 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
J
jinhai 已提交
5
//
6 7 8 9 10
// 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.
J
jinhai 已提交
11

S
starlord 已提交
12
#include "db/DBImpl.h"
Z
Zhiru Zhu 已提交
13 14

#include <assert.h>
15
#include <fiu-local.h>
Z
Zhiru Zhu 已提交
16 17 18 19 20

#include <algorithm>
#include <boost/filesystem.hpp>
#include <chrono>
#include <cstring>
21
#include <functional>
Z
Zhiru Zhu 已提交
22
#include <iostream>
23
#include <limits>
24
#include <queue>
Z
Zhiru Zhu 已提交
25 26
#include <set>
#include <thread>
27
#include <unordered_map>
Z
Zhiru Zhu 已提交
28 29
#include <utility>

S
starlord 已提交
30
#include "Utils.h"
S
starlord 已提交
31 32
#include "cache/CpuCacheMgr.h"
#include "cache/GpuCacheMgr.h"
33
#include "db/IDGenerator.h"
S
starlord 已提交
34
#include "engine/EngineFactory.h"
35
#include "index/thirdparty/faiss/utils/distances.h"
36
#include "insert/MemManagerFactory.h"
S
starlord 已提交
37
#include "meta/MetaConsts.h"
S
starlord 已提交
38 39
#include "meta/MetaFactory.h"
#include "meta/SqliteMetaImpl.h"
G
groot 已提交
40
#include "metrics/Metrics.h"
G
groot 已提交
41
#include "scheduler/Definition.h"
S
starlord 已提交
42
#include "scheduler/SchedInst.h"
Y
Yu Kun 已提交
43
#include "scheduler/job/BuildIndexJob.h"
S
starlord 已提交
44 45
#include "scheduler/job/DeleteJob.h"
#include "scheduler/job/SearchJob.h"
46 47 48
#include "segment/SegmentReader.h"
#include "segment/SegmentWriter.h"
#include "utils/Exception.h"
S
starlord 已提交
49
#include "utils/Log.h"
G
groot 已提交
50
#include "utils/StringHelpFunctions.h"
S
starlord 已提交
51
#include "utils/TimeRecorder.h"
52 53
#include "utils/ValidationUtil.h"
#include "wal/WalDefinations.h"
X
Xu Peng 已提交
54

55 56
#include "search/TaskInst.h"

J
jinhai 已提交
57
namespace milvus {
X
Xu Peng 已提交
58
namespace engine {
X
Xu Peng 已提交
59

G
groot 已提交
60
namespace {
G
groot 已提交
61 62
constexpr uint64_t BACKGROUND_METRIC_INTERVAL = 1;
constexpr uint64_t BACKGROUND_INDEX_INTERVAL = 1;
G
groot 已提交
63
constexpr uint64_t WAIT_BUILD_INDEX_INTERVAL = 5;
G
groot 已提交
64

65 66 67 68 69 70 71 72
constexpr const char* JSON_ROW_COUNT = "row_count";
constexpr const char* JSON_PARTITIONS = "partitions";
constexpr const char* JSON_PARTITION_TAG = "tag";
constexpr const char* JSON_SEGMENTS = "segments";
constexpr const char* JSON_SEGMENT_NAME = "name";
constexpr const char* JSON_INDEX_NAME = "index_name";
constexpr const char* JSON_DATA_SIZE = "data_size";

G
groot 已提交
73
static const Status SHUTDOWN_ERROR = Status(DB_ERROR, "Milvus server is shutdown!");
G
groot 已提交
74

S
starlord 已提交
75
}  // namespace
G
groot 已提交
76

Y
Yu Kun 已提交
77
DBImpl::DBImpl(const DBOptions& options)
78
    : options_(options), initialized_(false), merge_thread_pool_(1, 1), index_thread_pool_(1, 1) {
S
starlord 已提交
79
    meta_ptr_ = MetaFactory::Build(options.meta_, options.mode_);
Z
zhiru 已提交
80
    mem_mgr_ = MemManagerFactory::Build(meta_ptr_, options_);
81 82 83 84 85 86 87 88 89 90

    if (options_.wal_enable_) {
        wal::MXLogConfiguration mxlog_config;
        mxlog_config.recovery_error_ignore = options_.recovery_error_ignore_;
        // 2 buffers in the WAL
        mxlog_config.buffer_size = options_.buffer_size_ / 2;
        mxlog_config.mxlog_path = options_.mxlog_path_;
        wal_mgr_ = std::make_shared<wal::WalManager>(mxlog_config);
    }

91 92
    SetIdentity("DBImpl");
    AddCacheInsertDataListener();
93
    AddUseBlasThresholdListener();
94

S
starlord 已提交
95 96 97 98 99 100 101
    Start();
}

DBImpl::~DBImpl() {
    Stop();
}

S
starlord 已提交
102
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
S
starlord 已提交
103
// external api
S
starlord 已提交
104
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
S
starlord 已提交
105 106
Status
DBImpl::Start() {
107
    if (initialized_.load(std::memory_order_acquire)) {
S
starlord 已提交
108 109 110
        return Status::OK();
    }

111
    // LOG_ENGINE_TRACE_ << "DB service start";
112
    initialized_.store(true, std::memory_order_release);
S
starlord 已提交
113

114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
    // wal
    if (options_.wal_enable_) {
        auto error_code = DB_ERROR;
        if (wal_mgr_ != nullptr) {
            error_code = wal_mgr_->Init(meta_ptr_);
        }
        if (error_code != WAL_SUCCESS) {
            throw Exception(error_code, "Wal init error!");
        }

        // recovery
        while (1) {
            wal::MXLogRecord record;
            auto error_code = wal_mgr_->GetNextRecovery(record);
            if (error_code != WAL_SUCCESS) {
                throw Exception(error_code, "Wal recovery error!");
            }
            if (record.type == wal::MXLogType::None) {
                break;
            }

            ExecWalRecord(record);
        }

        // for distribute version, some nodes are read only
        if (options_.mode_ != DBOptions::MODE::CLUSTER_READONLY) {
G
groot 已提交
140 141
            // background wal thread
            bg_wal_thread_ = std::thread(&DBImpl::BackgroundWalThread, this);
142 143 144 145
        }
    } else {
        // for distribute version, some nodes are read only
        if (options_.mode_ != DBOptions::MODE::CLUSTER_READONLY) {
G
groot 已提交
146 147
            // background flush thread
            bg_flush_thread_ = std::thread(&DBImpl::BackgroundFlushThread, this);
148
        }
Z
update  
zhiru 已提交
149
    }
S
starlord 已提交
150

G
groot 已提交
151 152 153 154 155 156 157 158 159
    // for distribute version, some nodes are read only
    if (options_.mode_ != DBOptions::MODE::CLUSTER_READONLY) {
        // background build index thread
        bg_index_thread_ = std::thread(&DBImpl::BackgroundIndexThread, this);
    }

    // background metric thread
    bg_metric_thread_ = std::thread(&DBImpl::BackgroundMetricThread, this);

S
starlord 已提交
160 161 162
    return Status::OK();
}

S
starlord 已提交
163 164
Status
DBImpl::Stop() {
165
    if (!initialized_.load(std::memory_order_acquire)) {
S
starlord 已提交
166 167
        return Status::OK();
    }
168

169
    initialized_.store(false, std::memory_order_release);
S
starlord 已提交
170

171 172
    if (options_.mode_ != DBOptions::MODE::CLUSTER_READONLY) {
        if (options_.wal_enable_) {
G
groot 已提交
173 174
            // wait wal thread finish
            swn_wal_.Notify();
175 176
            bg_wal_thread_.join();
        } else {
G
groot 已提交
177
            // flush all without merge
178 179 180 181
            wal::MXLogRecord record;
            record.type = wal::MXLogType::Flush;
            ExecWalRecord(record);

G
groot 已提交
182 183 184
            // wait flush thread finish
            swn_flush_.Notify();
            bg_flush_thread_.join();
185
        }
S
starlord 已提交
186

187 188
        WaitMergeFileFinish();

G
groot 已提交
189 190 191
        swn_index_.Notify();
        bg_index_thread_.join();

192
        meta_ptr_->CleanUpShadowFiles();
S
starlord 已提交
193 194
    }

G
groot 已提交
195 196 197 198
    // wait metric thread exit
    swn_metric_.Notify();
    bg_metric_thread_.join();

199
    // LOG_ENGINE_TRACE_ << "DB service stop";
S
starlord 已提交
200
    return Status::OK();
X
Xu Peng 已提交
201 202
}

S
starlord 已提交
203 204
Status
DBImpl::DropAll() {
S
starlord 已提交
205 206 207
    return meta_ptr_->DropAll();
}

S
starlord 已提交
208
Status
209
DBImpl::CreateCollection(meta::CollectionSchema& collection_schema) {
210
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
211
        return SHUTDOWN_ERROR;
S
starlord 已提交
212 213
    }

214
    meta::CollectionSchema temp_schema = collection_schema;
B
bigbraver 已提交
215
    temp_schema.index_file_size_ *= MB;  // store as MB
216
    if (options_.wal_enable_) {
217
        temp_schema.flush_lsn_ = wal_mgr_->CreateCollection(collection_schema.collection_id_);
218 219
    }

220
    return meta_ptr_->CreateCollection(temp_schema);
221 222
}

223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
Status
DBImpl::CreateHybridCollection(meta::CollectionSchema& collection_schema, meta::hybrid::FieldsSchema& fields_schema) {
    if (!initialized_.load(std::memory_order_acquire)) {
        return SHUTDOWN_ERROR;
    }

    meta::CollectionSchema temp_schema = collection_schema;
    if (options_.wal_enable_) {
        // TODO(yukun): wal_mgr_->CreateHybridCollection()
    }

    return meta_ptr_->CreateHybridCollection(temp_schema, fields_schema);
}

Status
DBImpl::DescribeHybridCollection(meta::CollectionSchema& collection_schema,
                                 milvus::engine::meta::hybrid::FieldsSchema& fields_schema) {
    if (!initialized_.load(std::memory_order_acquire)) {
        return SHUTDOWN_ERROR;
    }

    auto stat = meta_ptr_->DescribeHybridCollection(collection_schema, fields_schema);
    return stat;
}

S
starlord 已提交
248
Status
249
DBImpl::DropCollection(const std::string& collection_id) {
250
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
251
        return SHUTDOWN_ERROR;
S
starlord 已提交
252 253
    }

254
    if (options_.wal_enable_) {
255
        wal_mgr_->DropCollection(collection_id);
256 257
    }

258
    return DropCollectionRecursively(collection_id);
G
groot 已提交
259 260
}

S
starlord 已提交
261
Status
262
DBImpl::DescribeCollection(meta::CollectionSchema& collection_schema) {
263
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
264
        return SHUTDOWN_ERROR;
S
starlord 已提交
265 266
    }

267
    auto stat = meta_ptr_->DescribeCollection(collection_schema);
B
bigbraver 已提交
268
    collection_schema.index_file_size_ /= MB;  // return as MB
S
starlord 已提交
269
    return stat;
270 271
}

S
starlord 已提交
272
Status
273
DBImpl::HasCollection(const std::string& collection_id, bool& has_or_not) {
274
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
275
        return SHUTDOWN_ERROR;
S
starlord 已提交
276 277
    }

278
    return meta_ptr_->HasCollection(collection_id, has_or_not);
279 280
}

281
Status
282
DBImpl::HasNativeCollection(const std::string& collection_id, bool& has_or_not_) {
283 284 285 286
    if (!initialized_.load(std::memory_order_acquire)) {
        return SHUTDOWN_ERROR;
    }

287 288 289
    engine::meta::CollectionSchema collection_schema;
    collection_schema.collection_id_ = collection_id;
    auto status = DescribeCollection(collection_schema);
290 291 292 293
    if (!status.ok()) {
        has_or_not_ = false;
        return status;
    } else {
294
        if (!collection_schema.owner_collection_.empty()) {
295 296 297 298 299 300 301 302 303
            has_or_not_ = false;
            return Status(DB_NOT_FOUND, "");
        }

        has_or_not_ = true;
        return Status::OK();
    }
}

S
starlord 已提交
304
Status
305
DBImpl::AllCollections(std::vector<meta::CollectionSchema>& collection_schema_array) {
306
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
307
        return SHUTDOWN_ERROR;
S
starlord 已提交
308 309
    }

310 311
    std::vector<meta::CollectionSchema> all_collections;
    auto status = meta_ptr_->AllCollections(all_collections);
312

313 314 315 316 317
    // only return real collections, dont return partition collections
    collection_schema_array.clear();
    for (auto& schema : all_collections) {
        if (schema.owner_collection_.empty()) {
            collection_schema_array.push_back(schema);
318 319 320 321
        }
    }

    return status;
G
groot 已提交
322 323
}

324
Status
325
DBImpl::GetCollectionInfo(const std::string& collection_id, std::string& collection_info) {
326 327 328 329 330
    if (!initialized_.load(std::memory_order_acquire)) {
        return SHUTDOWN_ERROR;
    }

    // step1: get all partition ids
J
Jin Hai 已提交
331 332
    std::vector<meta::CollectionSchema> partition_array;
    auto status = meta_ptr_->ShowPartitions(collection_id, partition_array);
333

J
Jin Hai 已提交
334 335
    std::vector<int> file_types{meta::SegmentSchema::FILE_TYPE::RAW, meta::SegmentSchema::FILE_TYPE::TO_INDEX,
                                meta::SegmentSchema::FILE_TYPE::INDEX};
336

337 338 339
    milvus::json json_info;
    milvus::json json_partitions;
    size_t total_row_count = 0;
340

341
    auto get_info = [&](const std::string& col_id, const std::string& tag) {
342
        meta::SegmentsSchema collection_files;
343
        status = meta_ptr_->FilesByType(col_id, file_types, collection_files);
344
        if (!status.ok()) {
J
Jin Hai 已提交
345
            std::string err_msg = "Failed to get collection info: " + status.ToString();
346
            LOG_ENGINE_ERROR_ << err_msg;
347 348 349
            return Status(DB_ERROR, err_msg);
        }

350 351 352 353 354
        milvus::json json_partition;
        json_partition[JSON_PARTITION_TAG] = tag;

        milvus::json json_segments;
        size_t row_count = 0;
355
        for (auto& file : collection_files) {
356 357 358 359 360 361 362 363 364
            milvus::json json_segment;
            json_segment[JSON_SEGMENT_NAME] = file.segment_id_;
            json_segment[JSON_ROW_COUNT] = file.row_count_;
            json_segment[JSON_INDEX_NAME] = utils::GetIndexName(file.engine_type_);
            json_segment[JSON_DATA_SIZE] = (int64_t)file.file_size_;
            json_segments.push_back(json_segment);

            row_count += file.row_count_;
            total_row_count += file.row_count_;
365 366
        }

367 368 369 370 371 372 373
        json_partition[JSON_ROW_COUNT] = row_count;
        json_partition[JSON_SEGMENTS] = json_segments;

        json_partitions.push_back(json_partition);

        return Status::OK();
    };
374

375 376 377 378
    // step2: get default partition info
    status = get_info(collection_id, milvus::engine::DEFAULT_PARTITON_TAG);
    if (!status.ok()) {
        return status;
379 380
    }

381 382 383 384 385 386 387 388 389 390 391 392 393
    // step3: get partitions info
    for (auto& schema : partition_array) {
        status = get_info(schema.collection_id_, schema.partition_tag_);
        if (!status.ok()) {
            return status;
        }
    }

    json_info[JSON_ROW_COUNT] = total_row_count;
    json_info[JSON_PARTITIONS] = json_partitions;

    collection_info = json_info.dump();

394 395 396
    return Status::OK();
}

S
starlord 已提交
397
Status
398
DBImpl::PreloadCollection(const std::string& collection_id) {
399
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
400
        return SHUTDOWN_ERROR;
S
starlord 已提交
401 402
    }

J
Jin Hai 已提交
403 404 405
    // step 1: get all collection files from parent collection
    meta::SegmentsSchema files_array;
    auto status = GetFilesToSearch(collection_id, files_array);
Y
Yu Kun 已提交
406 407 408
    if (!status.ok()) {
        return status;
    }
Y
Yu Kun 已提交
409

410
    // step 2: get files from partition collections
J
Jin Hai 已提交
411 412
    std::vector<meta::CollectionSchema> partition_array;
    status = meta_ptr_->ShowPartitions(collection_id, partition_array);
G
groot 已提交
413
    for (auto& schema : partition_array) {
J
Jin Hai 已提交
414
        status = GetFilesToSearch(schema.collection_id_, files_array);
G
groot 已提交
415 416
    }

Y
Yu Kun 已提交
417 418
    int64_t size = 0;
    int64_t cache_total = cache::CpuCacheMgr::GetInstance()->CacheCapacity();
Y
Yu Kun 已提交
419 420
    int64_t cache_usage = cache::CpuCacheMgr::GetInstance()->CacheUsage();
    int64_t available_size = cache_total - cache_usage;
Y
Yu Kun 已提交
421

422
    // step 3: load file one by one
423 424
    LOG_ENGINE_DEBUG_ << "Begin pre-load collection:" + collection_id + ", totally " << files_array.size()
                      << " files need to be pre-loaded";
J
Jin Hai 已提交
425
    TimeRecorderAuto rc("Pre-load collection:" + collection_id);
G
groot 已提交
426
    for (auto& file : files_array) {
427
        EngineType engine_type;
J
Jin Hai 已提交
428 429 430
        if (file.file_type_ == meta::SegmentSchema::FILE_TYPE::RAW ||
            file.file_type_ == meta::SegmentSchema::FILE_TYPE::TO_INDEX ||
            file.file_type_ == meta::SegmentSchema::FILE_TYPE::BACKUP) {
431 432
            engine_type =
                utils::IsBinaryMetricType(file.metric_type_) ? EngineType::FAISS_BIN_IDMAP : EngineType::FAISS_IDMAP;
433 434 435
        } else {
            engine_type = (EngineType)file.engine_type_;
        }
436 437 438 439

        auto json = milvus::json::parse(file.index_params_);
        ExecutionEnginePtr engine =
            EngineFactory::Build(file.dimension_, file.location_, engine_type, (MetricType)file.metric_type_, json);
440
        fiu_do_on("DBImpl.PreloadCollection.null_engine", engine = nullptr);
G
groot 已提交
441
        if (engine == nullptr) {
442
            LOG_ENGINE_ERROR_ << "Invalid engine type";
G
groot 已提交
443 444
            return Status(DB_ERROR, "Invalid engine type");
        }
Y
Yu Kun 已提交
445

446
        fiu_do_on("DBImpl.PreloadCollection.exceed_cache", size = available_size + 1);
447 448

        try {
449
            fiu_do_on("DBImpl.PreloadCollection.engine_throw_exception", throw std::exception());
450 451 452 453 454 455
            std::string msg = "Pre-loaded file: " + file.file_id_ + " size: " + std::to_string(file.file_size_);
            TimeRecorderAuto rc_1(msg);
            engine->Load(true);

            size += engine->Size();
            if (size > available_size) {
456
                LOG_ENGINE_DEBUG_ << "Pre-load cancelled since cache is almost full";
457
                return Status(SERVER_CACHE_FULL, "Cache is full");
Y
Yu Kun 已提交
458
            }
459
        } catch (std::exception& ex) {
J
Jin Hai 已提交
460
            std::string msg = "Pre-load collection encounter exception: " + std::string(ex.what());
461
            LOG_ENGINE_ERROR_ << msg;
462
            return Status(DB_ERROR, msg);
Y
Yu Kun 已提交
463 464
        }
    }
G
groot 已提交
465

Y
Yu Kun 已提交
466
    return Status::OK();
Y
Yu Kun 已提交
467 468
}

S
starlord 已提交
469
Status
470
DBImpl::UpdateCollectionFlag(const std::string& collection_id, int64_t flag) {
471
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
472
        return SHUTDOWN_ERROR;
S
starlord 已提交
473 474
    }

475
    return meta_ptr_->UpdateCollectionFlag(collection_id, flag);
S
starlord 已提交
476 477
}

S
starlord 已提交
478
Status
479
DBImpl::GetCollectionRowCount(const std::string& collection_id, uint64_t& row_count) {
480
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
481 482 483
        return SHUTDOWN_ERROR;
    }

484
    return GetCollectionRowCountRecursively(collection_id, row_count);
G
groot 已提交
485 486 487
}

Status
J
Jin Hai 已提交
488
DBImpl::CreatePartition(const std::string& collection_id, const std::string& partition_name,
G
groot 已提交
489
                        const std::string& partition_tag) {
490
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
491 492 493
        return SHUTDOWN_ERROR;
    }

494
    uint64_t lsn = 0;
495
    meta_ptr_->GetCollectionFlushLSN(collection_id, lsn);
J
Jin Hai 已提交
496
    return meta_ptr_->CreatePartition(collection_id, partition_name, partition_tag, lsn);
G
groot 已提交
497 498 499 500
}

Status
DBImpl::DropPartition(const std::string& partition_name) {
501
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
502
        return SHUTDOWN_ERROR;
S
starlord 已提交
503 504
    }

505
    mem_mgr_->EraseMemVector(partition_name);                // not allow insert
J
Jin Hai 已提交
506
    auto status = meta_ptr_->DropPartition(partition_name);  // soft delete collection
507
    if (!status.ok()) {
508
        LOG_ENGINE_ERROR_ << status.message();
509 510
        return status;
    }
G
groot 已提交
511

J
Jin Hai 已提交
512
    // scheduler will determine when to delete collection files
G
groot 已提交
513 514 515 516 517 518
    auto nres = scheduler::ResMgrInst::GetInstance()->GetNumOfComputeResource();
    scheduler::DeleteJobPtr job = std::make_shared<scheduler::DeleteJob>(partition_name, meta_ptr_, nres);
    scheduler::JobMgrInst::GetInstance()->Put(job);
    job->WaitAndDelete();

    return Status::OK();
G
groot 已提交
519 520
}

S
starlord 已提交
521
Status
J
Jin Hai 已提交
522
DBImpl::DropPartitionByTag(const std::string& collection_id, const std::string& partition_tag) {
523
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
524 525 526 527
        return SHUTDOWN_ERROR;
    }

    std::string partition_name;
J
Jin Hai 已提交
528
    auto status = meta_ptr_->GetPartitionName(collection_id, partition_tag, partition_name);
529
    if (!status.ok()) {
530
        LOG_ENGINE_ERROR_ << status.message();
531 532 533
        return status;
    }

G
groot 已提交
534 535 536 537
    return DropPartition(partition_name);
}

Status
J
Jin Hai 已提交
538
DBImpl::ShowPartitions(const std::string& collection_id, std::vector<meta::CollectionSchema>& partition_schema_array) {
539
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
540 541 542
        return SHUTDOWN_ERROR;
    }

J
Jin Hai 已提交
543
    return meta_ptr_->ShowPartitions(collection_id, partition_schema_array);
G
groot 已提交
544 545 546
}

Status
J
Jin Hai 已提交
547
DBImpl::InsertVectors(const std::string& collection_id, const std::string& partition_tag, VectorsData& vectors) {
548
    //    LOG_ENGINE_DEBUG_ << "Insert " << n << " vectors to cache";
549
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
550
        return SHUTDOWN_ERROR;
S
starlord 已提交
551
    }
Y
yu yunfeng 已提交
552

J
Jin Hai 已提交
553
    // insert vectors into target collection
554 555
    // (zhiru): generate ids
    if (vectors.id_array_.empty()) {
J
Jin Hai 已提交
556 557 558
        SafeIDGenerator& id_generator = SafeIDGenerator::GetInstance();
        Status status = id_generator.GetNextIDNumbers(vectors.vector_count_, vectors.id_array_);
        if (!status.ok()) {
559
            LOG_ENGINE_ERROR_ << LogOut("[%s][%ld] Get next id number fail: %s", "insert", 0, status.message().c_str());
J
Jin Hai 已提交
560 561
            return status;
        }
562 563
    }

564
    Status status;
565
    if (options_.wal_enable_) {
566 567
        std::string target_collection_name;
        status = GetPartitionByTag(collection_id, partition_tag, target_collection_name);
G
groot 已提交
568
        if (!status.ok()) {
569
            LOG_ENGINE_ERROR_ << LogOut("[%s][%ld] Get partition fail: %s", "insert", 0, status.message().c_str());
G
groot 已提交
570 571
            return status;
        }
572 573

        if (!vectors.float_data_.empty()) {
J
Jin Hai 已提交
574
            wal_mgr_->Insert(collection_id, partition_tag, vectors.id_array_, vectors.float_data_);
575
        } else if (!vectors.binary_data_.empty()) {
J
Jin Hai 已提交
576
            wal_mgr_->Insert(collection_id, partition_tag, vectors.id_array_, vectors.binary_data_);
577
        }
G
groot 已提交
578
        swn_wal_.Notify();
579 580 581
    } else {
        wal::MXLogRecord record;
        record.lsn = 0;  // need to get from meta ?
J
Jin Hai 已提交
582
        record.collection_id = collection_id;
583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598
        record.partition_tag = partition_tag;
        record.ids = vectors.id_array_.data();
        record.length = vectors.vector_count_;
        if (vectors.binary_data_.empty()) {
            record.type = wal::MXLogType::InsertVector;
            record.data = vectors.float_data_.data();
            record.data_size = vectors.float_data_.size() * sizeof(float);
        } else {
            record.type = wal::MXLogType::InsertBinary;
            record.ids = vectors.id_array_.data();
            record.length = vectors.vector_count_;
            record.data = vectors.binary_data_.data();
            record.data_size = vectors.binary_data_.size() * sizeof(uint8_t);
        }

        status = ExecWalRecord(record);
G
groot 已提交
599 600
    }

601 602 603
    return status;
}

604
Status
605 606
DBImpl::InsertEntities(const std::string& collection_id, const std::string& partition_tag,
                       const std::vector<std::string>& field_names, Entity& entity,
607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
                       std::unordered_map<std::string, meta::hybrid::DataType>& attr_types) {
    if (!initialized_.load(std::memory_order_acquire)) {
        return SHUTDOWN_ERROR;
    }

    // Generate id
    if (entity.id_array_.empty()) {
        SafeIDGenerator& id_generator = SafeIDGenerator::GetInstance();
        Status status = id_generator.GetNextIDNumbers(entity.entity_count_, entity.id_array_);
        if (!status.ok()) {
            return status;
        }
    }

    Status status;
    // insert entities: collection_name is field id
    wal::MXLogRecord record;
    record.lsn = 0;
    record.collection_id = collection_id;
    record.partition_tag = partition_tag;
    record.ids = entity.id_array_.data();
    record.length = entity.entity_count_;

    auto vector_it = entity.vector_data_.begin();
    if (vector_it->second.binary_data_.empty()) {
        record.type = wal::MXLogType::Entity;
        record.data = vector_it->second.float_data_.data();
        record.data_size = vector_it->second.float_data_.size() * sizeof(float);
    } else {
        //        record.type = wal::MXLogType::InsertBinary;
        //        record.data = entities.vector_data_[0].binary_data_.data();
        //        record.length = entities.vector_data_[0].binary_data_.size() * sizeof(uint8_t);
    }

641 642 643
    uint64_t offset = 0;
    for (auto field_name : field_names) {
        switch (attr_types.at(field_name)) {
644 645 646 647
            case meta::hybrid::DataType::INT8: {
                std::vector<uint8_t> data;
                data.resize(entity.entity_count_ * sizeof(int8_t));

648 649 650 651 652 653 654 655 656 657 658 659 660 661
                std::vector<int64_t> attr_value(entity.entity_count_, 0);
                memcpy(attr_value.data(), entity.attr_value_.data() + offset, entity.entity_count_ * sizeof(int64_t));
                offset += entity.entity_count_ * sizeof(int64_t);

                std::vector<int8_t> raw_value(entity.entity_count_, 0);
                for (uint64_t i = 0; i < entity.entity_count_; ++i) {
                    raw_value[i] = attr_value[i];
                }

                memcpy(data.data(), raw_value.data(), entity.entity_count_ * sizeof(int8_t));
                record.attr_data.insert(std::make_pair(field_name, data));

                record.attr_nbytes.insert(std::make_pair(field_name, sizeof(int8_t)));
                record.attr_data_size.insert(std::make_pair(field_name, entity.entity_count_ * sizeof(int8_t)));
662 663 664 665 666 667
                break;
            }
            case meta::hybrid::DataType::INT16: {
                std::vector<uint8_t> data;
                data.resize(entity.entity_count_ * sizeof(int16_t));

668 669 670 671 672 673 674 675 676 677 678 679 680 681
                std::vector<int64_t> attr_value(entity.entity_count_, 0);
                memcpy(attr_value.data(), entity.attr_value_.data() + offset, entity.entity_count_ * sizeof(int64_t));
                offset += entity.entity_count_ * sizeof(int64_t);

                std::vector<int16_t> raw_value(entity.entity_count_, 0);
                for (uint64_t i = 0; i < entity.entity_count_; ++i) {
                    raw_value[i] = attr_value[i];
                }

                memcpy(data.data(), raw_value.data(), entity.entity_count_ * sizeof(int16_t));
                record.attr_data.insert(std::make_pair(field_name, data));

                record.attr_nbytes.insert(std::make_pair(field_name, sizeof(int16_t)));
                record.attr_data_size.insert(std::make_pair(field_name, entity.entity_count_ * sizeof(int16_t)));
682 683 684 685 686 687
                break;
            }
            case meta::hybrid::DataType::INT32: {
                std::vector<uint8_t> data;
                data.resize(entity.entity_count_ * sizeof(int32_t));

688 689 690 691 692 693 694 695 696 697 698 699 700 701
                std::vector<int64_t> attr_value(entity.entity_count_, 0);
                memcpy(attr_value.data(), entity.attr_value_.data() + offset, entity.entity_count_ * sizeof(int64_t));
                offset += entity.entity_count_ * sizeof(int64_t);

                std::vector<int32_t> raw_value(entity.entity_count_, 0);
                for (uint64_t i = 0; i < entity.entity_count_; ++i) {
                    raw_value[i] = attr_value[i];
                }

                memcpy(data.data(), raw_value.data(), entity.entity_count_ * sizeof(int32_t));
                record.attr_data.insert(std::make_pair(field_name, data));

                record.attr_nbytes.insert(std::make_pair(field_name, sizeof(int32_t)));
                record.attr_data_size.insert(std::make_pair(field_name, entity.entity_count_ * sizeof(int32_t)));
702 703 704 705 706
                break;
            }
            case meta::hybrid::DataType::INT64: {
                std::vector<uint8_t> data;
                data.resize(entity.entity_count_ * sizeof(int64_t));
707 708
                memcpy(data.data(), entity.attr_value_.data() + offset, entity.entity_count_ * sizeof(int64_t));
                record.attr_data.insert(std::make_pair(field_name, data));
709

710 711 712
                record.attr_nbytes.insert(std::make_pair(field_name, sizeof(int64_t)));
                record.attr_data_size.insert(std::make_pair(field_name, entity.entity_count_ * sizeof(int64_t)));
                offset += entity.entity_count_ * sizeof(int64_t);
713 714 715 716 717 718
                break;
            }
            case meta::hybrid::DataType::FLOAT: {
                std::vector<uint8_t> data;
                data.resize(entity.entity_count_ * sizeof(float));

719 720 721
                std::vector<double> attr_value(entity.entity_count_, 0);
                memcpy(attr_value.data(), entity.attr_value_.data() + offset, entity.entity_count_ * sizeof(double));
                offset += entity.entity_count_ * sizeof(double);
722

723 724 725 726 727 728 729 730 731 732
                std::vector<float> raw_value(entity.entity_count_, 0);
                for (uint64_t i = 0; i < entity.entity_count_; ++i) {
                    raw_value[i] = attr_value[i];
                }

                memcpy(data.data(), raw_value.data(), entity.entity_count_ * sizeof(float));
                record.attr_data.insert(std::make_pair(field_name, data));

                record.attr_nbytes.insert(std::make_pair(field_name, sizeof(float)));
                record.attr_data_size.insert(std::make_pair(field_name, entity.entity_count_ * sizeof(float)));
733 734 735 736 737
                break;
            }
            case meta::hybrid::DataType::DOUBLE: {
                std::vector<uint8_t> data;
                data.resize(entity.entity_count_ * sizeof(double));
738 739
                memcpy(data.data(), entity.attr_value_.data() + offset, entity.entity_count_ * sizeof(double));
                record.attr_data.insert(std::make_pair(field_name, data));
740

741 742 743
                record.attr_nbytes.insert(std::make_pair(field_name, sizeof(double)));
                record.attr_data_size.insert(std::make_pair(field_name, entity.entity_count_ * sizeof(double)));
                offset += entity.entity_count_ * sizeof(double);
744 745
                break;
            }
746 747
            default:
                break;
748 749 750 751 752 753 754
        }
    }

    status = ExecWalRecord(record);
    return status;
}

755
Status
J
Jin Hai 已提交
756
DBImpl::DeleteVector(const std::string& collection_id, IDNumber vector_id) {
757 758
    IDNumbers ids;
    ids.push_back(vector_id);
J
Jin Hai 已提交
759
    return DeleteVectors(collection_id, ids);
760 761 762
}

Status
J
Jin Hai 已提交
763
DBImpl::DeleteVectors(const std::string& collection_id, IDNumbers vector_ids) {
764 765 766 767 768 769
    if (!initialized_.load(std::memory_order_acquire)) {
        return SHUTDOWN_ERROR;
    }

    Status status;
    if (options_.wal_enable_) {
J
Jin Hai 已提交
770
        wal_mgr_->DeleteById(collection_id, vector_ids);
G
groot 已提交
771
        swn_wal_.Notify();
772 773 774 775
    } else {
        wal::MXLogRecord record;
        record.lsn = 0;  // need to get from meta ?
        record.type = wal::MXLogType::Delete;
J
Jin Hai 已提交
776
        record.collection_id = collection_id;
777 778 779 780 781 782 783 784 785 786
        record.ids = vector_ids.data();
        record.length = vector_ids.size();

        status = ExecWalRecord(record);
    }

    return status;
}

Status
J
Jin Hai 已提交
787
DBImpl::Flush(const std::string& collection_id) {
788 789 790 791 792
    if (!initialized_.load(std::memory_order_acquire)) {
        return SHUTDOWN_ERROR;
    }

    Status status;
793 794
    bool has_collection;
    status = HasCollection(collection_id, has_collection);
795 796 797
    if (!status.ok()) {
        return status;
    }
798
    if (!has_collection) {
799
        LOG_ENGINE_ERROR_ << "Collection to flush does not exist: " << collection_id;
J
Jin Hai 已提交
800
        return Status(DB_NOT_FOUND, "Collection to flush does not exist");
801 802
    }

803
    LOG_ENGINE_DEBUG_ << "Begin flush collection: " << collection_id;
804 805

    if (options_.wal_enable_) {
806
        LOG_ENGINE_DEBUG_ << "WAL flush";
J
Jin Hai 已提交
807
        auto lsn = wal_mgr_->Flush(collection_id);
808
        if (lsn != 0) {
G
groot 已提交
809 810
            swn_wal_.Notify();
            flush_req_swn_.Wait();
811 812 813
        }

    } else {
814
        LOG_ENGINE_DEBUG_ << "MemTable flush";
G
groot 已提交
815
        InternalFlush(collection_id);
816 817
    }

818
    LOG_ENGINE_DEBUG_ << "End flush collection: " << collection_id;
819 820 821 822 823 824 825 826 827 828

    return status;
}

Status
DBImpl::Flush() {
    if (!initialized_.load(std::memory_order_acquire)) {
        return SHUTDOWN_ERROR;
    }

829
    LOG_ENGINE_DEBUG_ << "Begin flush all collections";
830 831 832

    Status status;
    if (options_.wal_enable_) {
833
        LOG_ENGINE_DEBUG_ << "WAL flush";
834 835
        auto lsn = wal_mgr_->Flush();
        if (lsn != 0) {
G
groot 已提交
836 837
            swn_wal_.Notify();
            flush_req_swn_.Wait();
838 839
        }
    } else {
840
        LOG_ENGINE_DEBUG_ << "MemTable flush";
G
groot 已提交
841
        InternalFlush();
842 843
    }

844
    LOG_ENGINE_DEBUG_ << "End flush all collections";
845 846 847 848 849

    return status;
}

Status
J
Jin Hai 已提交
850
DBImpl::Compact(const std::string& collection_id) {
851 852 853 854
    if (!initialized_.load(std::memory_order_acquire)) {
        return SHUTDOWN_ERROR;
    }

855 856 857
    engine::meta::CollectionSchema collection_schema;
    collection_schema.collection_id_ = collection_id;
    auto status = DescribeCollection(collection_schema);
858 859
    if (!status.ok()) {
        if (status.code() == DB_NOT_FOUND) {
860
            LOG_ENGINE_ERROR_ << "Collection to compact does not exist: " << collection_id;
J
Jin Hai 已提交
861
            return Status(DB_NOT_FOUND, "Collection to compact does not exist");
862 863 864 865
        } else {
            return status;
        }
    } else {
866
        if (!collection_schema.owner_collection_.empty()) {
867
            LOG_ENGINE_ERROR_ << "Collection to compact does not exist: " << collection_id;
J
Jin Hai 已提交
868
            return Status(DB_NOT_FOUND, "Collection to compact does not exist");
869 870 871
        }
    }

872
    LOG_ENGINE_DEBUG_ << "Before compacting, wait for build index thread to finish...";
873

Z
update  
Zhiru Zhu 已提交
874
    // WaitBuildIndexFinish();
875

Z
update  
Zhiru Zhu 已提交
876
    const std::lock_guard<std::mutex> index_lock(build_index_mutex_);
Z
Zhiru Zhu 已提交
877
    const std::lock_guard<std::mutex> merge_lock(flush_merge_compact_mutex_);
Z
Zhiru Zhu 已提交
878

879
    LOG_ENGINE_DEBUG_ << "Compacting collection: " << collection_id;
Z
Zhiru Zhu 已提交
880

881
    // Get files to compact from meta.
J
Jin Hai 已提交
882 883 884 885
    std::vector<int> file_types{meta::SegmentSchema::FILE_TYPE::RAW, meta::SegmentSchema::FILE_TYPE::TO_INDEX,
                                meta::SegmentSchema::FILE_TYPE::BACKUP};
    meta::SegmentsSchema files_to_compact;
    status = meta_ptr_->FilesByType(collection_id, file_types, files_to_compact);
886 887
    if (!status.ok()) {
        std::string err_msg = "Failed to get files to compact: " + status.message();
888
        LOG_ENGINE_ERROR_ << err_msg;
889 890 891
        return Status(DB_ERROR, err_msg);
    }

892
    LOG_ENGINE_DEBUG_ << "Found " << files_to_compact.size() << " segment to compact";
893 894

    OngoingFileChecker::GetInstance().MarkOngoingFiles(files_to_compact);
Z
Zhiru Zhu 已提交
895 896

    Status compact_status;
Z
Zhiru Zhu 已提交
897
    for (auto iter = files_to_compact.begin(); iter != files_to_compact.end();) {
J
Jin Hai 已提交
898
        meta::SegmentSchema file = *iter;
G
groot 已提交
899 900
        iter = files_to_compact.erase(iter);

Z
Zhiru Zhu 已提交
901 902 903
        // Check if the segment needs compacting
        std::string segment_dir;
        utils::GetParentPath(file.location_, segment_dir);
904

Z
Zhiru Zhu 已提交
905
        segment::SegmentReader segment_reader(segment_dir);
Z
Zhiru Zhu 已提交
906 907
        size_t deleted_docs_size;
        status = segment_reader.ReadDeletedDocsSize(deleted_docs_size);
Z
Zhiru Zhu 已提交
908
        if (!status.ok()) {
G
groot 已提交
909 910
            OngoingFileChecker::GetInstance().UnmarkOngoingFile(file);
            continue;  // skip this file and try compact next one
Z
Zhiru Zhu 已提交
911 912
        }

J
Jin Hai 已提交
913
        meta::SegmentsSchema files_to_update;
Z
Zhiru Zhu 已提交
914
        if (deleted_docs_size != 0) {
J
Jin Hai 已提交
915
            compact_status = CompactFile(collection_id, file, files_to_update);
Z
Zhiru Zhu 已提交
916 917

            if (!compact_status.ok()) {
918 919
                LOG_ENGINE_ERROR_ << "Compact failed for segment " << file.segment_id_ << ": "
                                  << compact_status.message();
G
groot 已提交
920 921
                OngoingFileChecker::GetInstance().UnmarkOngoingFile(file);
                continue;  // skip this file and try compact next one
Z
Zhiru Zhu 已提交
922 923
            }
        } else {
G
groot 已提交
924
            OngoingFileChecker::GetInstance().UnmarkOngoingFile(file);
925
            LOG_ENGINE_DEBUG_ << "Segment " << file.segment_id_ << " has no deleted data. No need to compact";
G
groot 已提交
926
            continue;  // skip this file and try compact next one
927
        }
Z
Zhiru Zhu 已提交
928

929
        LOG_ENGINE_DEBUG_ << "Updating meta after compaction...";
930
        status = meta_ptr_->UpdateCollectionFiles(files_to_update);
G
groot 已提交
931
        OngoingFileChecker::GetInstance().UnmarkOngoingFile(file);
G
groot 已提交
932 933 934 935
        if (!status.ok()) {
            compact_status = status;
            break;  // meta error, could not go on
        }
Z
Zhiru Zhu 已提交
936 937
    }

938 939
    OngoingFileChecker::GetInstance().UnmarkOngoingFiles(files_to_compact);

G
groot 已提交
940
    if (compact_status.ok()) {
941
        LOG_ENGINE_DEBUG_ << "Finished compacting collection: " << collection_id;
G
groot 已提交
942
    }
943

G
groot 已提交
944
    return compact_status;
945 946 947
}

Status
J
Jin Hai 已提交
948 949
DBImpl::CompactFile(const std::string& collection_id, const meta::SegmentSchema& file,
                    meta::SegmentsSchema& files_to_update) {
950
    LOG_ENGINE_DEBUG_ << "Compacting segment " << file.segment_id_ << " for collection: " << collection_id;
951

J
Jin Hai 已提交
952 953 954
    // Create new collection file
    meta::SegmentSchema compacted_file;
    compacted_file.collection_id_ = collection_id;
955
    // compacted_file.date_ = date;
J
Jin Hai 已提交
956
    compacted_file.file_type_ = meta::SegmentSchema::NEW_MERGE;  // TODO: use NEW_MERGE for now
957
    Status status = meta_ptr_->CreateCollectionFile(compacted_file);
958 959

    if (!status.ok()) {
960
        LOG_ENGINE_ERROR_ << "Failed to create collection file: " << status.message();
961 962 963
        return status;
    }

J
Jin Hai 已提交
964
    // Compact (merge) file to the newly created collection file
965 966 967 968 969 970 971 972

    std::string new_segment_dir;
    utils::GetParentPath(compacted_file.location_, new_segment_dir);
    auto segment_writer_ptr = std::make_shared<segment::SegmentWriter>(new_segment_dir);

    std::string segment_dir_to_merge;
    utils::GetParentPath(file.location_, segment_dir_to_merge);

973
    LOG_ENGINE_DEBUG_ << "Compacting begin...";
974 975 976
    segment_writer_ptr->Merge(segment_dir_to_merge, compacted_file.file_id_);

    // Serialize
977
    LOG_ENGINE_DEBUG_ << "Serializing compacted segment...";
978 979
    status = segment_writer_ptr->Serialize();
    if (!status.ok()) {
980
        LOG_ENGINE_ERROR_ << "Failed to serialize compacted segment: " << status.message();
J
Jin Hai 已提交
981
        compacted_file.file_type_ = meta::SegmentSchema::TO_DELETE;
982
        auto mark_status = meta_ptr_->UpdateCollectionFile(compacted_file);
983
        if (mark_status.ok()) {
984
            LOG_ENGINE_DEBUG_ << "Mark file: " << compacted_file.file_id_ << " to to_delete";
985 986 987 988
        }
        return status;
    }

989 990 991 992 993 994 995
    // Update compacted file state, if origin file is backup or to_index, set compected file to to_index
    compacted_file.file_size_ = segment_writer_ptr->Size();
    compacted_file.row_count_ = segment_writer_ptr->VectorCount();
    if ((file.file_type_ == (int32_t)meta::SegmentSchema::BACKUP ||
         file.file_type_ == (int32_t)meta::SegmentSchema::TO_INDEX) &&
        (compacted_file.row_count_ > meta::BUILD_INDEX_THRESHOLD)) {
        compacted_file.file_type_ = meta::SegmentSchema::TO_INDEX;
996
    } else {
J
Jin Hai 已提交
997
        compacted_file.file_type_ = meta::SegmentSchema::RAW;
998 999 1000
    }

    if (compacted_file.row_count_ == 0) {
1001
        LOG_ENGINE_DEBUG_ << "Compacted segment is empty. Mark it as TO_DELETE";
J
Jin Hai 已提交
1002
        compacted_file.file_type_ = meta::SegmentSchema::TO_DELETE;
1003 1004
    }

Z
Zhiru Zhu 已提交
1005
    files_to_update.emplace_back(compacted_file);
Z
Zhiru Zhu 已提交
1006

Z
Zhiru Zhu 已提交
1007 1008
    // Set all files in segment to TO_DELETE
    auto& segment_id = file.segment_id_;
J
Jin Hai 已提交
1009
    meta::SegmentsSchema segment_files;
1010
    status = meta_ptr_->GetCollectionFilesBySegmentId(segment_id, segment_files);
Z
Zhiru Zhu 已提交
1011 1012 1013 1014
    if (!status.ok()) {
        return status;
    }
    for (auto& f : segment_files) {
J
Jin Hai 已提交
1015
        f.file_type_ = meta::SegmentSchema::FILE_TYPE::TO_DELETE;
Z
Zhiru Zhu 已提交
1016 1017
        files_to_update.emplace_back(f);
    }
1018

1019 1020 1021
    LOG_ENGINE_DEBUG_ << "Compacted segment " << compacted_file.segment_id_ << " from "
                      << std::to_string(file.file_size_) << " bytes to " << std::to_string(compacted_file.file_size_)
                      << " bytes";
1022 1023 1024 1025 1026 1027 1028 1029 1030

    if (options_.insert_cache_immediately_) {
        segment_writer_ptr->Cache();
    }

    return status;
}

Status
1031 1032
DBImpl::GetVectorsByID(const std::string& collection_id, const IDNumbers& id_array,
                       std::vector<engine::VectorsData>& vectors) {
1033 1034 1035 1036
    if (!initialized_.load(std::memory_order_acquire)) {
        return SHUTDOWN_ERROR;
    }

1037 1038 1039
    bool has_collection;
    auto status = HasCollection(collection_id, has_collection);
    if (!has_collection) {
1040
        LOG_ENGINE_ERROR_ << "Collection " << collection_id << " does not exist: ";
J
Jin Hai 已提交
1041
        return Status(DB_NOT_FOUND, "Collection does not exist");
1042 1043 1044 1045 1046
    }
    if (!status.ok()) {
        return status;
    }

J
Jin Hai 已提交
1047 1048 1049
    meta::SegmentsSchema files_to_query;
    std::vector<int> file_types{meta::SegmentSchema::FILE_TYPE::RAW, meta::SegmentSchema::FILE_TYPE::TO_INDEX,
                                meta::SegmentSchema::FILE_TYPE::BACKUP};
1050

J
Jin Hai 已提交
1051
    status = meta_ptr_->FilesByType(collection_id, file_types, files_to_query);
1052
    if (!status.ok()) {
1053
        std::string err_msg = "Failed to get files for GetVectorsByID: " + status.message();
1054
        LOG_ENGINE_ERROR_ << err_msg;
1055 1056 1057
        return status;
    }

J
Jin Hai 已提交
1058 1059
    OngoingFileChecker::GetInstance().MarkOngoingFiles(files_to_query);

J
Jin Hai 已提交
1060 1061
    std::vector<meta::CollectionSchema> partition_array;
    status = meta_ptr_->ShowPartitions(collection_id, partition_array);
1062
    for (auto& schema : partition_array) {
J
Jin Hai 已提交
1063 1064
        meta::SegmentsSchema files;
        status = meta_ptr_->FilesByType(schema.collection_id_, file_types, files);
1065
        if (!status.ok()) {
1066
            OngoingFileChecker::GetInstance().UnmarkOngoingFiles(files_to_query);
1067
            std::string err_msg = "Failed to get files for GetVectorByID: " + status.message();
1068
            LOG_ENGINE_ERROR_ << err_msg;
1069 1070
            return status;
        }
J
Jin Hai 已提交
1071 1072

        OngoingFileChecker::GetInstance().MarkOngoingFiles(files);
1073 1074 1075 1076 1077
        files_to_query.insert(files_to_query.end(), std::make_move_iterator(files.begin()),
                              std::make_move_iterator(files.end()));
    }

    if (files_to_query.empty()) {
1078
        OngoingFileChecker::GetInstance().UnmarkOngoingFiles(files_to_query);
1079
        LOG_ENGINE_DEBUG_ << "No files to get vector by id from";
J
Jin Hai 已提交
1080
        return Status(DB_NOT_FOUND, "Collection is empty");
1081 1082 1083 1084
    }

    cache::CpuCacheMgr::GetInstance()->PrintInfo();

1085
    status = GetVectorsByIdHelper(collection_id, id_array, vectors, files_to_query);
1086 1087 1088 1089 1090 1091 1092 1093

    OngoingFileChecker::GetInstance().UnmarkOngoingFiles(files_to_query);
    cache::CpuCacheMgr::GetInstance()->PrintInfo();

    return status;
}

Status
J
Jin Hai 已提交
1094
DBImpl::GetVectorIDs(const std::string& collection_id, const std::string& segment_id, IDNumbers& vector_ids) {
1095 1096 1097 1098
    if (!initialized_.load(std::memory_order_acquire)) {
        return SHUTDOWN_ERROR;
    }

J
Jin Hai 已提交
1099
    // step 1: check collection existence
1100 1101 1102
    bool has_collection;
    auto status = HasCollection(collection_id, has_collection);
    if (!has_collection) {
1103
        LOG_ENGINE_ERROR_ << "Collection " << collection_id << " does not exist: ";
J
Jin Hai 已提交
1104
        return Status(DB_NOT_FOUND, "Collection does not exist");
1105 1106 1107 1108 1109 1110
    }
    if (!status.ok()) {
        return status;
    }

    //  step 2: find segment
1111 1112
    meta::SegmentsSchema collection_files;
    status = meta_ptr_->GetCollectionFilesBySegmentId(segment_id, collection_files);
1113 1114 1115 1116
    if (!status.ok()) {
        return status;
    }

1117
    if (collection_files.empty()) {
1118 1119 1120
        return Status(DB_NOT_FOUND, "Segment does not exist");
    }

J
Jin Hai 已提交
1121
    // check the segment is belong to this collection
1122
    if (collection_files[0].collection_id_ != collection_id) {
J
Jin Hai 已提交
1123
        // the segment could be in a partition under this collection
1124 1125 1126 1127
        meta::CollectionSchema collection_schema;
        collection_schema.collection_id_ = collection_files[0].collection_id_;
        status = DescribeCollection(collection_schema);
        if (collection_schema.owner_collection_ != collection_id) {
J
Jin Hai 已提交
1128
            return Status(DB_NOT_FOUND, "Segment does not belong to this collection");
1129 1130 1131 1132 1133
        }
    }

    // step 3: load segment ids and delete offset
    std::string segment_dir;
1134
    engine::utils::GetParentPath(collection_files[0].location_, segment_dir);
1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
    segment::SegmentReader segment_reader(segment_dir);

    std::vector<segment::doc_id_t> uids;
    status = segment_reader.LoadUids(uids);
    if (!status.ok()) {
        return status;
    }

    segment::DeletedDocsPtr deleted_docs_ptr;
    status = segment_reader.LoadDeletedDocs(deleted_docs_ptr);
    if (!status.ok()) {
        return status;
    }

    // step 4: construct id array
    // avoid duplicate offset and erase from max offset to min offset
    auto& deleted_offset = deleted_docs_ptr->GetDeletedDocs();
    std::set<segment::offset_t, std::greater<segment::offset_t>> ordered_offset;
    for (segment::offset_t offset : deleted_offset) {
        ordered_offset.insert(offset);
    }
    for (segment::offset_t offset : ordered_offset) {
        uids.erase(uids.begin() + offset);
    }
    vector_ids.swap(uids);
S
starlord 已提交
1160

G
groot 已提交
1161
    return status;
X
Xu Peng 已提交
1162 1163
}

1164
Status
1165 1166 1167
DBImpl::GetVectorsByIdHelper(const std::string& collection_id, const IDNumbers& id_array,
                             std::vector<engine::VectorsData>& vectors, const meta::SegmentsSchema& files) {
    LOG_ENGINE_DEBUG_ << "Getting vector by id in " << files.size() << " files, id count = " << id_array.size();
J
Jin Hai 已提交
1168

1169 1170 1171 1172 1173 1174 1175
    // sometimes not all of id_array can be found, we need to return empty vector for id not found
    // for example:
    // id_array = [1, -1, 2, -1, 3]
    // vectors should return [valid_vector, empty_vector, valid_vector, empty_vector, valid_vector]
    // the ID2RAW is to ensure returned vector sequence is consist with id_array
    using ID2VECTOR = std::map<int64_t, VectorsData>;
    ID2VECTOR map_id2vector;
1176

1177 1178 1179
    vectors.clear();

    IDNumbers temp_ids = id_array;
1180 1181 1182 1183 1184 1185 1186 1187
    for (auto& file : files) {
        // Load bloom filter
        std::string segment_dir;
        engine::utils::GetParentPath(file.location_, segment_dir);
        segment::SegmentReader segment_reader(segment_dir);
        segment::IdBloomFilterPtr id_bloom_filter_ptr;
        segment_reader.LoadBloomFilter(id_bloom_filter_ptr);

1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
        for (IDNumbers::iterator it = temp_ids.begin(); it != temp_ids.end();) {
            int64_t vector_id = *it;
            // each id must has a VectorsData
            // if vector not found for an id, its VectorsData's vector_count = 0, else 1
            VectorsData& vector_ref = map_id2vector[vector_id];

            // Check if the id is present in bloom filter.
            if (id_bloom_filter_ptr->Check(vector_id)) {
                // Load uids and check if the id is indeed present. If yes, find its offset.
                std::vector<segment::doc_id_t> uids;
                auto status = segment_reader.LoadUids(uids);
1199 1200 1201
                if (!status.ok()) {
                    return status;
                }
1202 1203 1204 1205 1206 1207 1208 1209

                auto found = std::find(uids.begin(), uids.end(), vector_id);
                if (found != uids.end()) {
                    auto offset = std::distance(uids.begin(), found);

                    // Check whether the id has been deleted
                    segment::DeletedDocsPtr deleted_docs_ptr;
                    status = segment_reader.LoadDeletedDocs(deleted_docs_ptr);
1210
                    if (!status.ok()) {
J
Jin Hai 已提交
1211
                        LOG_ENGINE_ERROR_ << status.message();
1212 1213
                        return status;
                    }
1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
                    auto& deleted_docs = deleted_docs_ptr->GetDeletedDocs();

                    auto deleted = std::find(deleted_docs.begin(), deleted_docs.end(), offset);
                    if (deleted == deleted_docs.end()) {
                        // Load raw vector
                        bool is_binary = utils::IsBinaryMetricType(file.metric_type_);
                        size_t single_vector_bytes = is_binary ? file.dimension_ / 8 : file.dimension_ * sizeof(float);
                        std::vector<uint8_t> raw_vector;
                        status =
                            segment_reader.LoadVectors(offset * single_vector_bytes, single_vector_bytes, raw_vector);
                        if (!status.ok()) {
                            LOG_ENGINE_ERROR_ << status.message();
                            return status;
                        }

                        vector_ref.vector_count_ = 1;
                        if (is_binary) {
                            vector_ref.binary_data_.swap(raw_vector);
                        } else {
                            std::vector<float> float_vector;
                            float_vector.resize(file.dimension_);
                            memcpy(float_vector.data(), raw_vector.data(), single_vector_bytes);
                            vector_ref.float_data_.swap(float_vector);
                        }
                        temp_ids.erase(it);
                        continue;
1240 1241 1242
                    }
                }
            }
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255

            it++;
        }
    }

    for (auto id : id_array) {
        VectorsData& vector_ref = map_id2vector[id];

        VectorsData data;
        data.vector_count_ = vector_ref.vector_count_;
        if (data.vector_count_ > 0) {
            data.float_data_.swap(vector_ref.float_data_);
            data.binary_data_.swap(vector_ref.binary_data_);
1256
        }
1257
        vectors.emplace_back(data);
1258 1259
    }

1260 1261
    if (vectors.empty()) {
        std::string msg = "Vectors not found in collection " + collection_id;
J
Jin Hai 已提交
1262 1263 1264
        LOG_ENGINE_DEBUG_ << msg;
    }

1265 1266 1267
    return Status::OK();
}

S
starlord 已提交
1268
Status
1269
DBImpl::CreateIndex(const std::string& collection_id, const CollectionIndex& index) {
1270
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
1271 1272 1273
        return SHUTDOWN_ERROR;
    }

G
groot 已提交
1274
    // serialize memory data
1275 1276
    //    std::set<std::string> sync_collection_ids;
    //    auto status = SyncMemData(sync_collection_ids);
1277
    auto status = Flush();
G
groot 已提交
1278

S
starlord 已提交
1279 1280 1281
    {
        std::unique_lock<std::mutex> lock(build_index_mutex_);

S
starlord 已提交
1282
        // step 1: check index difference
1283
        CollectionIndex old_index;
J
Jin Hai 已提交
1284
        status = DescribeIndex(collection_id, old_index);
S
starlord 已提交
1285
        if (!status.ok()) {
1286
            LOG_ENGINE_ERROR_ << "Failed to get collection index info for collection: " << collection_id;
S
starlord 已提交
1287 1288 1289
            return status;
        }

S
starlord 已提交
1290
        // step 2: update index info
1291 1292
        CollectionIndex new_index = index;
        new_index.metric_type_ = old_index.metric_type_;  // dont change metric type, it was defined by CreateCollection
S
starlord 已提交
1293
        if (!utils::IsSameIndex(old_index, new_index)) {
1294
            status = UpdateCollectionIndexRecursively(collection_id, new_index);
S
starlord 已提交
1295 1296 1297 1298 1299 1300
            if (!status.ok()) {
                return status;
            }
        }
    }

S
starlord 已提交
1301 1302
    // step 3: let merge file thread finish
    // to avoid duplicate data bug
1303 1304
    WaitMergeFileFinish();

S
starlord 已提交
1305
    // step 4: wait and build index
1306 1307
    status = index_failed_checker_.CleanFailedIndexFileOfCollection(collection_id);
    status = WaitCollectionIndexRecursively(collection_id, index);
S
starlord 已提交
1308

G
groot 已提交
1309
    return status;
S
starlord 已提交
1310 1311
}

S
starlord 已提交
1312
Status
1313
DBImpl::DescribeIndex(const std::string& collection_id, CollectionIndex& index) {
1314
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
1315 1316 1317
        return SHUTDOWN_ERROR;
    }

1318
    return meta_ptr_->DescribeCollectionIndex(collection_id, index);
S
starlord 已提交
1319 1320
}

S
starlord 已提交
1321
Status
J
Jin Hai 已提交
1322
DBImpl::DropIndex(const std::string& collection_id) {
1323
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
1324 1325 1326
        return SHUTDOWN_ERROR;
    }

1327
    LOG_ENGINE_DEBUG_ << "Drop index for collection: " << collection_id;
1328
    return DropCollectionIndexRecursively(collection_id);
S
starlord 已提交
1329 1330
}

S
starlord 已提交
1331
Status
1332 1333 1334
DBImpl::QueryByIDs(const std::shared_ptr<server::Context>& context, const std::string& collection_id,
                   const std::vector<std::string>& partition_tags, uint64_t k, const milvus::json& extra_params,
                   const IDNumbers& id_array, ResultIds& result_ids, ResultDistances& result_distances) {
1335
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
1336
        return SHUTDOWN_ERROR;
S
starlord 已提交
1337 1338
    }

1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455
    if (id_array.empty()) {
        return Status(DB_ERROR, "Empty id array during query by id");
    }

    TimeRecorder rc("Query by id in collection:" + collection_id);

    // get collection schema
    engine::meta::CollectionSchema collection_schema;
    collection_schema.collection_id_ = collection_id;
    auto status = DescribeCollection(collection_schema);
    if (!status.ok()) {
        if (status.code() == DB_NOT_FOUND) {
            std::string msg = "Collection to search does not exist: " + collection_id;
            LOG_ENGINE_ERROR_ << msg;
            return Status(DB_NOT_FOUND, msg);
        } else {
            return status;
        }
    } else {
        if (!collection_schema.owner_collection_.empty()) {
            std::string msg = "Collection to search does not exist: " + collection_id;
            LOG_ENGINE_ERROR_ << msg;
            return Status(DB_NOT_FOUND, msg);
        }
    }

    rc.RecordSection("get collection schema");

    // get target vectors data
    std::vector<milvus::engine::VectorsData> vectors;
    status = GetVectorsByID(collection_id, id_array, vectors);
    if (!status.ok()) {
        std::string msg = "Failed to get vector data for collection: " + collection_id;
        LOG_ENGINE_ERROR_ << msg;
        return status;
    }

    // some vectors could not be found, no need to search them
    uint64_t valid_count = 0;
    bool is_binary = utils::IsBinaryMetricType(collection_schema.metric_type_);
    for (auto& vector : vectors) {
        if (vector.vector_count_ > 0) {
            valid_count++;
        }
    }

    // copy valid vectors data for search input
    uint64_t dimension = collection_schema.dimension_;
    VectorsData valid_vectors;
    valid_vectors.vector_count_ = valid_count;
    if (is_binary) {
        valid_vectors.binary_data_.resize(valid_count * dimension / 8);
    } else {
        valid_vectors.float_data_.resize(valid_count * dimension * sizeof(float));
    }

    int64_t valid_index = 0;
    for (size_t i = 0; i < vectors.size(); i++) {
        if (vectors[i].vector_count_ == 0) {
            continue;
        }
        if (is_binary) {
            memcpy(valid_vectors.binary_data_.data() + valid_index * dimension / 8, vectors[i].binary_data_.data(),
                   vectors[i].binary_data_.size());
        } else {
            memcpy(valid_vectors.float_data_.data() + valid_index * dimension, vectors[i].float_data_.data(),
                   vectors[i].float_data_.size() * sizeof(float));
        }
        valid_index++;
    }

    rc.RecordSection("construct query input");

    // search valid vectors
    ResultIds valid_result_ids;
    ResultDistances valid_result_distances;
    status = Query(context, collection_id, partition_tags, k, extra_params, valid_vectors, valid_result_ids,
                   valid_result_distances);
    if (!status.ok()) {
        std::string msg = "Failed to query by id in collection " + collection_id + ", error: " + status.message();
        LOG_ENGINE_ERROR_ << msg;
        return status;
    }

    if (valid_result_ids.size() != valid_count * k || valid_result_distances.size() != valid_count * k) {
        std::string msg = "Failed to query by id in collection " + collection_id + ", result doesn't match id count";
        return Status(DB_ERROR, msg);
    }

    rc.RecordSection("query vealid vectors");

    // construct result
    if (valid_count == id_array.size()) {
        result_ids.swap(valid_result_ids);
        result_distances.swap(valid_result_distances);
    } else {
        result_ids.resize(vectors.size() * k);
        result_distances.resize(vectors.size() * k);
        int64_t valid_index = 0;
        for (uint64_t i = 0; i < vectors.size(); i++) {
            if (vectors[i].vector_count_ > 0) {
                memcpy(result_ids.data() + i * k, valid_result_ids.data() + valid_index * k, k * sizeof(int64_t));
                memcpy(result_distances.data() + i * k, valid_result_distances.data() + valid_index * k,
                       k * sizeof(float));
                valid_index++;
            } else {
                memset(result_ids.data() + i * k, -1, k * sizeof(int64_t));
                for (uint64_t j = i * k; j < i * k + k; j++) {
                    result_distances[j] = std::numeric_limits<float>::max();
                }
            }
        }
    }

    rc.RecordSection("construct result");

    return status;
X
Xu Peng 已提交
1456 1457
}

1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525
Status
DBImpl::HybridQuery(const std::shared_ptr<server::Context>& context, const std::string& collection_id,
                    const std::vector<std::string>& partition_tags,
                    context::HybridSearchContextPtr hybrid_search_context, query::GeneralQueryPtr general_query,
                    std::unordered_map<std::string, engine::meta::hybrid::DataType>& attr_type, uint64_t& nq,
                    ResultIds& result_ids, ResultDistances& result_distances) {
    auto query_ctx = context->Child("Query");

    if (!initialized_.load(std::memory_order_acquire)) {
        return SHUTDOWN_ERROR;
    }

    Status status;
    meta::SegmentsSchema files_array;

    if (partition_tags.empty()) {
        // no partition tag specified, means search in whole table
        // get all table files from parent table
        status = GetFilesToSearch(collection_id, files_array);
        if (!status.ok()) {
            return status;
        }

        std::vector<meta::CollectionSchema> partition_array;
        status = meta_ptr_->ShowPartitions(collection_id, partition_array);
        if (!status.ok()) {
            return status;
        }
        for (auto& schema : partition_array) {
            status = GetFilesToSearch(schema.collection_id_, files_array);
            if (!status.ok()) {
                return Status(DB_ERROR, "GetFilesToSearch failed in HybridQuery");
            }
        }

        if (files_array.empty()) {
            return Status::OK();
        }
    } else {
        // get files from specified partitions
        std::set<std::string> partition_name_array;
        GetPartitionsByTags(collection_id, partition_tags, partition_name_array);

        for (auto& partition_name : partition_name_array) {
            status = GetFilesToSearch(partition_name, files_array);
            if (!status.ok()) {
                return Status(DB_ERROR, "GetFilesToSearch failed in HybridQuery");
            }
        }

        if (files_array.empty()) {
            return Status::OK();
        }
    }

    cache::CpuCacheMgr::GetInstance()->PrintInfo();  // print cache info before query
    status = HybridQueryAsync(query_ctx, collection_id, files_array, hybrid_search_context, general_query, attr_type,
                              nq, result_ids, result_distances);
    if (!status.ok()) {
        return status;
    }
    cache::CpuCacheMgr::GetInstance()->PrintInfo();  // print cache info after query

    query_ctx->GetTraceContext()->GetSpan()->Finish();

    return status;
}

S
starlord 已提交
1526
Status
J
Jin Hai 已提交
1527
DBImpl::Query(const std::shared_ptr<server::Context>& context, const std::string& collection_id,
1528 1529
              const std::vector<std::string>& partition_tags, uint64_t k, const milvus::json& extra_params,
              const VectorsData& vectors, ResultIds& result_ids, ResultDistances& result_distances) {
1530
    milvus::server::ContextChild tracer(context, "Query");
Z
Zhiru Zhu 已提交
1531

1532
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
1533
        return SHUTDOWN_ERROR;
S
starlord 已提交
1534 1535
    }

G
groot 已提交
1536
    Status status;
J
Jin Hai 已提交
1537
    meta::SegmentsSchema files_array;
1538

G
groot 已提交
1539
    if (partition_tags.empty()) {
J
Jin Hai 已提交
1540 1541 1542
        // no partition tag specified, means search in whole collection
        // get all collection files from parent collection
        status = GetFilesToSearch(collection_id, files_array);
G
groot 已提交
1543 1544 1545 1546
        if (!status.ok()) {
            return status;
        }

J
Jin Hai 已提交
1547 1548
        std::vector<meta::CollectionSchema> partition_array;
        status = meta_ptr_->ShowPartitions(collection_id, partition_array);
G
groot 已提交
1549
        for (auto& schema : partition_array) {
J
Jin Hai 已提交
1550
            status = GetFilesToSearch(schema.collection_id_, files_array);
1551 1552 1553 1554
        }

        if (files_array.empty()) {
            return Status::OK();
G
groot 已提交
1555 1556 1557 1558
        }
    } else {
        // get files from specified partitions
        std::set<std::string> partition_name_array;
J
Jin Hai 已提交
1559
        status = GetPartitionsByTags(collection_id, partition_tags, partition_name_array);
T
Tinkerrr 已提交
1560 1561 1562
        if (!status.ok()) {
            return status;  // didn't match any partition.
        }
G
groot 已提交
1563 1564

        for (auto& partition_name : partition_name_array) {
1565
            status = GetFilesToSearch(partition_name, files_array);
1566 1567 1568 1569
        }

        if (files_array.empty()) {
            return Status::OK();
1570 1571 1572
        }
    }

S
starlord 已提交
1573
    cache::CpuCacheMgr::GetInstance()->PrintInfo();  // print cache info before query
1574
    status = QueryAsync(tracer.Context(), files_array, k, extra_params, vectors, result_ids, result_distances);
S
starlord 已提交
1575
    cache::CpuCacheMgr::GetInstance()->PrintInfo();  // print cache info after query
Z
Zhiru Zhu 已提交
1576

S
starlord 已提交
1577
    return status;
G
groot 已提交
1578
}
X
Xu Peng 已提交
1579

S
starlord 已提交
1580
Status
1581 1582 1583
DBImpl::QueryByFileID(const std::shared_ptr<server::Context>& context, const std::vector<std::string>& file_ids,
                      uint64_t k, const milvus::json& extra_params, const VectorsData& vectors, ResultIds& result_ids,
                      ResultDistances& result_distances) {
1584
    milvus::server::ContextChild tracer(context, "Query by file id");
Z
Zhiru Zhu 已提交
1585

1586
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
1587
        return SHUTDOWN_ERROR;
S
starlord 已提交
1588 1589
    }

S
starlord 已提交
1590
    // get specified files
1591
    std::vector<size_t> ids;
Y
Yu Kun 已提交
1592
    for (auto& id : file_ids) {
1593
        std::string::size_type sz;
J
jinhai 已提交
1594
        ids.push_back(std::stoul(id, &sz));
1595 1596
    }

J
Jin Hai 已提交
1597
    meta::SegmentsSchema search_files;
1598
    auto status = meta_ptr_->FilesByID(ids, search_files);
1599 1600
    if (!status.ok()) {
        return status;
1601 1602
    }

1603 1604
    fiu_do_on("DBImpl.QueryByFileID.empty_files_array", search_files.clear());
    if (search_files.empty()) {
S
starlord 已提交
1605
        return Status(DB_ERROR, "Invalid file id");
G
groot 已提交
1606 1607
    }

S
starlord 已提交
1608
    cache::CpuCacheMgr::GetInstance()->PrintInfo();  // print cache info before query
1609
    status = QueryAsync(tracer.Context(), search_files, k, extra_params, vectors, result_ids, result_distances);
S
starlord 已提交
1610
    cache::CpuCacheMgr::GetInstance()->PrintInfo();  // print cache info after query
Z
Zhiru Zhu 已提交
1611

S
starlord 已提交
1612
    return status;
1613 1614
}

S
starlord 已提交
1615
Status
Y
Yu Kun 已提交
1616
DBImpl::Size(uint64_t& result) {
1617
    if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
1618
        return SHUTDOWN_ERROR;
S
starlord 已提交
1619 1620
    }

S
starlord 已提交
1621
    return meta_ptr_->Size(result);
S
starlord 已提交
1622 1623 1624
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
S
starlord 已提交
1625
// internal methods
S
starlord 已提交
1626
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
S
starlord 已提交
1627
Status
J
Jin Hai 已提交
1628
DBImpl::QueryAsync(const std::shared_ptr<server::Context>& context, const meta::SegmentsSchema& files, uint64_t k,
1629 1630
                   const milvus::json& extra_params, const VectorsData& vectors, ResultIds& result_ids,
                   ResultDistances& result_distances) {
1631
    milvus::server::ContextChild tracer(context, "Query Async");
G
groot 已提交
1632
    server::CollectQueryMetrics metrics(vectors.vector_count_);
Y
Yu Kun 已提交
1633

G
groot 已提交
1634 1635 1636
    if (files.size() > milvus::scheduler::TASK_TABLE_MAX_COUNT) {
        std::string msg =
            "Search files count exceed scheduler limit: " + std::to_string(milvus::scheduler::TASK_TABLE_MAX_COUNT);
1637
        LOG_ENGINE_ERROR_ << msg;
G
groot 已提交
1638 1639 1640
        return Status(DB_ERROR, msg);
    }

S
starlord 已提交
1641
    TimeRecorder rc("");
G
groot 已提交
1642

1643
    // step 1: construct search job
1644
    auto status = OngoingFileChecker::GetInstance().MarkOngoingFiles(files);
1645

1646
    LOG_ENGINE_DEBUG_ << LogOut("Engine query begin, index file count: %ld", files.size());
1647
    scheduler::SearchJobPtr job = std::make_shared<scheduler::SearchJob>(tracer.Context(), k, extra_params, vectors);
Y
Yu Kun 已提交
1648
    for (auto& file : files) {
J
Jin Hai 已提交
1649
        scheduler::SegmentSchemaPtr file_ptr = std::make_shared<meta::SegmentSchema>(file);
W
wxyu 已提交
1650
        job->AddIndexFile(file_ptr);
G
groot 已提交
1651 1652
    }

1653
    // step 2: put search job to scheduler and wait result
S
starlord 已提交
1654
    scheduler::JobMgrInst::GetInstance()->Put(job);
W
wxyu 已提交
1655
    job->WaitResult();
1656

1657
    status = OngoingFileChecker::GetInstance().UnmarkOngoingFiles(files);
W
wxyu 已提交
1658 1659
    if (!job->GetStatus().ok()) {
        return job->GetStatus();
1660
    }
G
groot 已提交
1661

1662
    // step 3: construct results
G
groot 已提交
1663 1664
    result_ids = job->GetResultIds();
    result_distances = job->GetResultDistances();
S
starlord 已提交
1665
    rc.ElapseFromBegin("Engine query totally cost");
G
groot 已提交
1666 1667 1668 1669

    return Status::OK();
}

1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733
Status
DBImpl::HybridQueryAsync(const std::shared_ptr<server::Context>& context, const std::string& table_id,
                         const meta::SegmentsSchema& files, context::HybridSearchContextPtr hybrid_search_context,
                         query::GeneralQueryPtr general_query,
                         std::unordered_map<std::string, engine::meta::hybrid::DataType>& attr_type, uint64_t& nq,
                         ResultIds& result_ids, ResultDistances& result_distances) {
    auto query_async_ctx = context->Child("Query Async");

#if 0
    // Construct tasks
    for (auto file : files) {
        std::unordered_map<std::string, engine::DataType> types;
        auto it = attr_type.begin();
        for (; it != attr_type.end(); it++) {
            types.insert(std::make_pair(it->first, (engine::DataType)it->second));
        }

        auto file_ptr = std::make_shared<meta::TableFileSchema>(file);
        search::TaskPtr
            task = std::make_shared<search::Task>(context, file_ptr, general_query, types, hybrid_search_context);
        search::TaskInst::GetInstance().load_queue().push(task);
        search::TaskInst::GetInstance().load_cv().notify_one();
        hybrid_search_context->tasks_.emplace_back(task);
    }

#endif

    //#if 0
    TimeRecorder rc("");

    // step 1: construct search job
    auto status = OngoingFileChecker::GetInstance().MarkOngoingFiles(files);

    VectorsData vectors;

    LOG_ENGINE_DEBUG_ << LogOut("Engine query begin, index file count: %ld", files.size());
    scheduler::SearchJobPtr job =
        std::make_shared<scheduler::SearchJob>(query_async_ctx, general_query, attr_type, vectors);
    for (auto& file : files) {
        scheduler::SegmentSchemaPtr file_ptr = std::make_shared<meta::SegmentSchema>(file);
        job->AddIndexFile(file_ptr);
    }

    // step 2: put search job to scheduler and wait result
    scheduler::JobMgrInst::GetInstance()->Put(job);
    job->WaitResult();

    status = OngoingFileChecker::GetInstance().UnmarkOngoingFiles(files);
    if (!job->GetStatus().ok()) {
        return job->GetStatus();
    }

    // step 3: construct results
    nq = job->vector_count();
    result_ids = job->GetResultIds();
    result_distances = job->GetResultDistances();
    rc.ElapseFromBegin("Engine query totally cost");

    query_async_ctx->GetTraceContext()->GetSpan()->Finish();
    //#endif

    return Status::OK();
}

S
starlord 已提交
1734
void
G
groot 已提交
1735
DBImpl::BackgroundIndexThread() {
Y
yu yunfeng 已提交
1736
    server::SystemInfo::GetInstance().Init();
X
Xu Peng 已提交
1737
    while (true) {
1738
        if (!initialized_.load(std::memory_order_acquire)) {
1739 1740
            WaitMergeFileFinish();
            WaitBuildIndexFinish();
S
starlord 已提交
1741

1742
            LOG_ENGINE_DEBUG_ << "DB background thread exit";
G
groot 已提交
1743 1744
            break;
        }
X
Xu Peng 已提交
1745

G
groot 已提交
1746
        swn_index_.Wait_For(std::chrono::seconds(BACKGROUND_INDEX_INTERVAL));
X
Xu Peng 已提交
1747

G
groot 已提交
1748
        WaitMergeFileFinish();
G
groot 已提交
1749 1750
        StartBuildIndexTask();
    }
X
Xu Peng 已提交
1751 1752
}

S
starlord 已提交
1753 1754
void
DBImpl::WaitMergeFileFinish() {
1755
    //    LOG_ENGINE_DEBUG_ << "Begin WaitMergeFileFinish";
1756 1757
    std::lock_guard<std::mutex> lck(merge_result_mutex_);
    for (auto& iter : merge_thread_results_) {
1758 1759
        iter.wait();
    }
1760
    //    LOG_ENGINE_DEBUG_ << "End WaitMergeFileFinish";
1761 1762
}

S
starlord 已提交
1763 1764
void
DBImpl::WaitBuildIndexFinish() {
1765
    //    LOG_ENGINE_DEBUG_ << "Begin WaitBuildIndexFinish";
1766
    std::lock_guard<std::mutex> lck(index_result_mutex_);
Y
Yu Kun 已提交
1767
    for (auto& iter : index_thread_results_) {
1768 1769
        iter.wait();
    }
1770
    //    LOG_ENGINE_DEBUG_ << "End WaitBuildIndexFinish";
1771 1772
}

S
starlord 已提交
1773 1774
void
DBImpl::StartMetricTask() {
G
groot 已提交
1775
    server::Metrics::GetInstance().KeepingAliveCounterIncrement(BACKGROUND_METRIC_INTERVAL);
G
groot 已提交
1776 1777
    int64_t cache_usage = cache::CpuCacheMgr::GetInstance()->CacheUsage();
    int64_t cache_total = cache::CpuCacheMgr::GetInstance()->CacheCapacity();
S
shengjh 已提交
1778 1779
    fiu_do_on("DBImpl.StartMetricTask.InvalidTotalCache", cache_total = 0);

J
JinHai-CN 已提交
1780 1781 1782 1783 1784 1785 1786
    if (cache_total > 0) {
        double cache_usage_double = cache_usage;
        server::Metrics::GetInstance().CpuCacheUsageGaugeSet(cache_usage_double * 100 / cache_total);
    } else {
        server::Metrics::GetInstance().CpuCacheUsageGaugeSet(0);
    }

Y
Yu Kun 已提交
1787
    server::Metrics::GetInstance().GpuCacheUsageGaugeSet();
G
groot 已提交
1788 1789 1790 1791 1792 1793 1794 1795
    uint64_t size;
    Size(size);
    server::Metrics::GetInstance().DataFileSizeGaugeSet(size);
    server::Metrics::GetInstance().CPUUsagePercentSet();
    server::Metrics::GetInstance().RAMUsagePercentSet();
    server::Metrics::GetInstance().GPUPercentGaugeSet();
    server::Metrics::GetInstance().GPUMemoryUsageGaugeSet();
    server::Metrics::GetInstance().OctetsSet();
S
starlord 已提交
1796

K
kun yu 已提交
1797
    server::Metrics::GetInstance().CPUCoreUsagePercentSet();
K
kun yu 已提交
1798 1799
    server::Metrics::GetInstance().GPUTemperature();
    server::Metrics::GetInstance().CPUTemperature();
1800
    server::Metrics::GetInstance().PushToGateway();
G
groot 已提交
1801 1802
}

S
starlord 已提交
1803
void
1804
DBImpl::StartMergeTask() {
1805
    // LOG_ENGINE_DEBUG_ << "Begin StartMergeTask";
1806
    // merge task has been finished?
1807
    {
1808 1809
        std::lock_guard<std::mutex> lck(merge_result_mutex_);
        if (!merge_thread_results_.empty()) {
1810
            std::chrono::milliseconds span(10);
1811 1812
            if (merge_thread_results_.back().wait_for(span) == std::future_status::ready) {
                merge_thread_results_.pop_back();
1813
            }
G
groot 已提交
1814 1815
        }
    }
X
Xu Peng 已提交
1816

1817
    // add new merge task
1818
    {
1819 1820
        std::lock_guard<std::mutex> lck(merge_result_mutex_);
        if (merge_thread_results_.empty()) {
1821 1822
            // collect merge files for all collections(if merge_collection_ids_ is empty) for two reasons:
            // 1. other collections may still has un-merged files
1823
            // 2. server may be closed unexpected, these un-merge files need to be merged when server restart
1824 1825 1826 1827 1828
            if (merge_collection_ids_.empty()) {
                std::vector<meta::CollectionSchema> collection_schema_array;
                meta_ptr_->AllCollections(collection_schema_array);
                for (auto& schema : collection_schema_array) {
                    merge_collection_ids_.insert(schema.collection_id_);
1829 1830 1831 1832
                }
            }

            // start merge file thread
1833
            merge_thread_results_.push_back(
1834 1835
                merge_thread_pool_.enqueue(&DBImpl::BackgroundMerge, this, merge_collection_ids_));
            merge_collection_ids_.clear();
1836
        }
G
groot 已提交
1837
    }
1838

1839
    // LOG_ENGINE_DEBUG_ << "End StartMergeTask";
X
Xu Peng 已提交
1840 1841
}

S
starlord 已提交
1842
Status
J
Jin Hai 已提交
1843
DBImpl::MergeFiles(const std::string& collection_id, const meta::SegmentsSchema& files) {
Z
Zhiru Zhu 已提交
1844
    // const std::lock_guard<std::mutex> lock(flush_merge_compact_mutex_);
1845

1846
    LOG_ENGINE_DEBUG_ << "Merge files for collection: " << collection_id;
S
starlord 已提交
1847

J
Jin Hai 已提交
1848
    // step 1: create collection file
1849 1850 1851 1852
    meta::SegmentSchema collection_file;
    collection_file.collection_id_ = collection_id;
    collection_file.file_type_ = meta::SegmentSchema::NEW_MERGE;
    Status status = meta_ptr_->CreateCollectionFile(collection_file);
X
Xu Peng 已提交
1853

1854
    if (!status.ok()) {
1855
        LOG_ENGINE_ERROR_ << "Failed to create collection: " << status.ToString();
1856 1857 1858
        return status;
    }

S
starlord 已提交
1859
    // step 2: merge files
1860
    /*
G
groot 已提交
1861
    ExecutionEnginePtr index =
1862 1863
        EngineFactory::Build(collection_file.dimension_, collection_file.location_,
    (EngineType)collection_file.engine_type_, (MetricType)collection_file.metric_type_, collection_file.nlist_);
1864
*/
J
Jin Hai 已提交
1865
    meta::SegmentsSchema updated;
1866 1867

    std::string new_segment_dir;
1868
    utils::GetParentPath(collection_file.location_, new_segment_dir);
1869
    auto segment_writer_ptr = std::make_shared<segment::SegmentWriter>(new_segment_dir);
1870

Y
Yu Kun 已提交
1871
    for (auto& file : files) {
Y
Yu Kun 已提交
1872
        server::CollectMergeFilesMetrics metrics;
1873 1874
        std::string segment_dir_to_merge;
        utils::GetParentPath(file.location_, segment_dir_to_merge);
1875
        segment_writer_ptr->Merge(segment_dir_to_merge, collection_file.file_id_);
1876
        auto file_schema = file;
J
Jin Hai 已提交
1877
        file_schema.file_type_ = meta::SegmentSchema::TO_DELETE;
1878
        updated.push_back(file_schema);
1879 1880
        auto size = segment_writer_ptr->Size();
        if (size >= file_schema.index_file_size_) {
S
starlord 已提交
1881
            break;
S
starlord 已提交
1882
        }
1883 1884
    }

S
starlord 已提交
1885
    // step 3: serialize to disk
S
starlord 已提交
1886
    try {
1887
        status = segment_writer_ptr->Serialize();
S
shengjh 已提交
1888 1889
        fiu_do_on("DBImpl.MergeFiles.Serialize_ThrowException", throw std::exception());
        fiu_do_on("DBImpl.MergeFiles.Serialize_ErrorStatus", status = Status(DB_ERROR, ""));
Y
Yu Kun 已提交
1890
    } catch (std::exception& ex) {
S
starlord 已提交
1891
        std::string msg = "Serialize merged index encounter exception: " + std::string(ex.what());
1892
        LOG_ENGINE_ERROR_ << msg;
G
groot 已提交
1893 1894
        status = Status(DB_ERROR, msg);
    }
Y
yu yunfeng 已提交
1895

G
groot 已提交
1896
    if (!status.ok()) {
1897
        LOG_ENGINE_ERROR_ << "Failed to persist merged segment: " << new_segment_dir << ". Error: " << status.message();
1898

G
groot 已提交
1899
        // if failed to serialize merge file to disk
1900
        // typical error: out of disk space, out of memory or permission denied
1901 1902
        collection_file.file_type_ = meta::SegmentSchema::TO_DELETE;
        status = meta_ptr_->UpdateCollectionFile(collection_file);
1903 1904
        LOG_ENGINE_DEBUG_ << "Failed to update file to index, mark file: " << collection_file.file_id_
                          << " to to_delete";
X
Xu Peng 已提交
1905

G
groot 已提交
1906
        return status;
S
starlord 已提交
1907 1908
    }

J
Jin Hai 已提交
1909
    // step 4: update collection files state
1910
    // if index type isn't IDMAP, set file type to TO_INDEX if file size exceed index_file_size
S
starlord 已提交
1911
    // else set file type to RAW, no need to build index
1912 1913 1914 1915
    if (!utils::IsRawIndexType(collection_file.engine_type_)) {
        collection_file.file_type_ = (segment_writer_ptr->Size() >= collection_file.index_file_size_)
                                         ? meta::SegmentSchema::TO_INDEX
                                         : meta::SegmentSchema::RAW;
1916
    } else {
1917
        collection_file.file_type_ = meta::SegmentSchema::RAW;
1918
    }
1919 1920 1921 1922
    collection_file.file_size_ = segment_writer_ptr->Size();
    collection_file.row_count_ = segment_writer_ptr->VectorCount();
    updated.push_back(collection_file);
    status = meta_ptr_->UpdateCollectionFiles(updated);
1923 1924
    LOG_ENGINE_DEBUG_ << "New merged segment " << collection_file.segment_id_ << " of size "
                      << segment_writer_ptr->Size() << " bytes";
1925

S
starlord 已提交
1926
    if (options_.insert_cache_immediately_) {
1927
        segment_writer_ptr->Cache();
S
starlord 已提交
1928
    }
X
Xu Peng 已提交
1929

1930 1931 1932
    return status;
}

1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022
Status
DBImpl::MergeHybridFiles(const std::string& collection_id, const milvus::engine::meta::SegmentsSchema& files) {
    // const std::lock_guard<std::mutex> lock(flush_merge_compact_mutex_);

    LOG_ENGINE_DEBUG_ << "Merge files for collection: " << collection_id;

    // step 1: create table file
    meta::SegmentSchema table_file;
    table_file.collection_id_ = collection_id;
    table_file.file_type_ = meta::SegmentSchema::NEW_MERGE;
    Status status = meta_ptr_->CreateHybridCollectionFile(table_file);

    if (!status.ok()) {
        LOG_ENGINE_ERROR_ << "Failed to create collection: " << status.ToString();
        return status;
    }

    // step 2: merge files
    /*
    ExecutionEnginePtr index =
        EngineFactory::Build(table_file.dimension_, table_file.location_, (EngineType)table_file.engine_type_,
                             (MetricType)table_file.metric_type_, table_file.nlist_);
*/
    meta::SegmentsSchema updated;

    std::string new_segment_dir;
    utils::GetParentPath(table_file.location_, new_segment_dir);
    auto segment_writer_ptr = std::make_shared<segment::SegmentWriter>(new_segment_dir);

    for (auto& file : files) {
        server::CollectMergeFilesMetrics metrics;
        std::string segment_dir_to_merge;
        utils::GetParentPath(file.location_, segment_dir_to_merge);
        segment_writer_ptr->Merge(segment_dir_to_merge, table_file.file_id_);
        auto file_schema = file;
        file_schema.file_type_ = meta::SegmentSchema::TO_DELETE;
        updated.push_back(file_schema);
        auto size = segment_writer_ptr->Size();
        if (size >= file_schema.index_file_size_) {
            break;
        }
    }

    // step 3: serialize to disk
    try {
        status = segment_writer_ptr->Serialize();
        fiu_do_on("DBImpl.MergeFiles.Serialize_ThrowException", throw std::exception());
        fiu_do_on("DBImpl.MergeFiles.Serialize_ErrorStatus", status = Status(DB_ERROR, ""));
    } catch (std::exception& ex) {
        std::string msg = "Serialize merged index encounter exception: " + std::string(ex.what());
        LOG_ENGINE_ERROR_ << msg;
        status = Status(DB_ERROR, msg);
    }

    if (!status.ok()) {
        LOG_ENGINE_ERROR_ << "Failed to persist merged segment: " << new_segment_dir << ". Error: " << status.message();

        // if failed to serialize merge file to disk
        // typical error: out of disk space, out of memory or permission denied
        table_file.file_type_ = meta::SegmentSchema::TO_DELETE;
        status = meta_ptr_->UpdateCollectionFile(table_file);
        LOG_ENGINE_DEBUG_ << "Failed to update file to index, mark file: " << table_file.file_id_ << " to to_delete";

        return status;
    }

    // step 4: update table files state
    // if index type isn't IDMAP, set file type to TO_INDEX if file size exceed index_file_size
    // else set file type to RAW, no need to build index
    if (!utils::IsRawIndexType(table_file.engine_type_)) {
        table_file.file_type_ = (segment_writer_ptr->Size() >= table_file.index_file_size_)
                                    ? meta::SegmentSchema::TO_INDEX
                                    : meta::SegmentSchema::RAW;
    } else {
        table_file.file_type_ = meta::SegmentSchema::RAW;
    }
    table_file.file_size_ = segment_writer_ptr->Size();
    table_file.row_count_ = segment_writer_ptr->VectorCount();
    updated.push_back(table_file);
    status = meta_ptr_->UpdateCollectionFiles(updated);
    LOG_ENGINE_DEBUG_ << "New merged segment " << table_file.segment_id_ << " of size " << segment_writer_ptr->Size()
                      << " bytes";

    if (options_.insert_cache_immediately_) {
        segment_writer_ptr->Cache();
    }

    return status;
}

S
starlord 已提交
2023
Status
J
Jin Hai 已提交
2024
DBImpl::BackgroundMergeFiles(const std::string& collection_id) {
Z
Zhiru Zhu 已提交
2025
    const std::lock_guard<std::mutex> lock(flush_merge_compact_mutex_);
2026

J
Jin Hai 已提交
2027 2028
    meta::SegmentsSchema raw_files;
    auto status = meta_ptr_->FilesToMerge(collection_id, raw_files);
X
Xu Peng 已提交
2029
    if (!status.ok()) {
2030
        LOG_ENGINE_ERROR_ << "Failed to get merge files for collection: " << collection_id;
X
Xu Peng 已提交
2031 2032
        return status;
    }
2033

2034
    if (raw_files.size() < options_.merge_trigger_number_) {
2035
        LOG_ENGINE_TRACE_ << "Files number not greater equal than merge trigger number, skip merge action";
2036 2037
        return Status::OK();
    }
2038

2039
    status = OngoingFileChecker::GetInstance().MarkOngoingFiles(raw_files);
J
Jin Hai 已提交
2040
    MergeFiles(collection_id, raw_files);
2041
    status = OngoingFileChecker::GetInstance().UnmarkOngoingFiles(raw_files);
G
groot 已提交
2042

2043
    if (!initialized_.load(std::memory_order_acquire)) {
2044
        LOG_ENGINE_DEBUG_ << "Server will shutdown, skip merge action for collection: " << collection_id;
2045
    }
X
Xu Peng 已提交
2046

G
groot 已提交
2047 2048
    return Status::OK();
}
2049

S
starlord 已提交
2050
void
2051
DBImpl::BackgroundMerge(std::set<std::string> collection_ids) {
2052
    // LOG_ENGINE_TRACE_ << " Background merge thread start";
S
starlord 已提交
2053

G
groot 已提交
2054
    Status status;
2055
    for (auto& collection_id : collection_ids) {
J
Jin Hai 已提交
2056
        status = BackgroundMergeFiles(collection_id);
G
groot 已提交
2057
        if (!status.ok()) {
2058
            LOG_ENGINE_ERROR_ << "Merge files for collection " << collection_id << " failed: " << status.ToString();
G
groot 已提交
2059
        }
S
starlord 已提交
2060

2061
        if (!initialized_.load(std::memory_order_acquire)) {
2062
            LOG_ENGINE_DEBUG_ << "Server will shutdown, skip merge action";
S
starlord 已提交
2063 2064
            break;
        }
G
groot 已提交
2065
    }
X
Xu Peng 已提交
2066

G
groot 已提交
2067
    meta_ptr_->Archive();
Z
update  
zhiru 已提交
2068

2069
    {
G
groot 已提交
2070
        uint64_t ttl = 10 * meta::SECOND;  // default: file will be hard-deleted few seconds after soft-deleted
2071
        if (options_.mode_ == DBOptions::MODE::CLUSTER_WRITABLE) {
2072
            ttl = meta::HOUR;
2073
        }
G
groot 已提交
2074

2075
        meta_ptr_->CleanUpFilesWithTTL(ttl);
Z
update  
zhiru 已提交
2076
    }
S
starlord 已提交
2077

2078
    // LOG_ENGINE_TRACE_ << " Background merge thread exit";
G
groot 已提交
2079
}
X
Xu Peng 已提交
2080

S
starlord 已提交
2081
void
G
groot 已提交
2082
DBImpl::StartBuildIndexTask() {
S
starlord 已提交
2083
    // build index has been finished?
2084 2085 2086 2087 2088 2089 2090
    {
        std::lock_guard<std::mutex> lck(index_result_mutex_);
        if (!index_thread_results_.empty()) {
            std::chrono::milliseconds span(10);
            if (index_thread_results_.back().wait_for(span) == std::future_status::ready) {
                index_thread_results_.pop_back();
            }
G
groot 已提交
2091 2092 2093
        }
    }

S
starlord 已提交
2094
    // add new build index task
2095 2096 2097
    {
        std::lock_guard<std::mutex> lck(index_result_mutex_);
        if (index_thread_results_.empty()) {
S
starlord 已提交
2098
            index_thread_results_.push_back(index_thread_pool_.enqueue(&DBImpl::BackgroundBuildIndex, this));
2099
        }
G
groot 已提交
2100
    }
X
Xu Peng 已提交
2101 2102
}

S
starlord 已提交
2103 2104
void
DBImpl::BackgroundBuildIndex() {
P
peng.xu 已提交
2105
    std::unique_lock<std::mutex> lock(build_index_mutex_);
J
Jin Hai 已提交
2106
    meta::SegmentsSchema to_index_files;
G
groot 已提交
2107
    meta_ptr_->FilesToIndex(to_index_files);
2108
    Status status = index_failed_checker_.IgnoreFailedIndexFiles(to_index_files);
2109

2110
    if (!to_index_files.empty()) {
2111
        LOG_ENGINE_DEBUG_ << "Background build index thread begin";
2112
        status = OngoingFileChecker::GetInstance().MarkOngoingFiles(to_index_files);
2113

2114
        // step 2: put build index task to scheduler
J
Jin Hai 已提交
2115
        std::vector<std::pair<scheduler::BuildIndexJobPtr, scheduler::SegmentSchemaPtr>> job2file_map;
2116
        for (auto& file : to_index_files) {
G
groot 已提交
2117
            scheduler::BuildIndexJobPtr job = std::make_shared<scheduler::BuildIndexJob>(meta_ptr_, options_);
J
Jin Hai 已提交
2118
            scheduler::SegmentSchemaPtr file_ptr = std::make_shared<meta::SegmentSchema>(file);
2119
            job->AddToIndexFiles(file_ptr);
G
groot 已提交
2120
            scheduler::JobMgrInst::GetInstance()->Put(job);
G
groot 已提交
2121
            job2file_map.push_back(std::make_pair(job, file_ptr));
2122
        }
G
groot 已提交
2123

G
groot 已提交
2124
        // step 3: wait build index finished and mark failed files
G
groot 已提交
2125 2126
        for (auto iter = job2file_map.begin(); iter != job2file_map.end(); ++iter) {
            scheduler::BuildIndexJobPtr job = iter->first;
J
Jin Hai 已提交
2127
            meta::SegmentSchema& file_schema = *(iter->second.get());
G
groot 已提交
2128 2129 2130
            job->WaitBuildIndexFinish();
            if (!job->GetStatus().ok()) {
                Status status = job->GetStatus();
2131
                LOG_ENGINE_ERROR_ << "Building index job " << job->id() << " failed: " << status.ToString();
G
groot 已提交
2132

2133
                index_failed_checker_.MarkFailedIndexFile(file_schema, status.message());
G
groot 已提交
2134
            } else {
2135
                LOG_ENGINE_DEBUG_ << "Building index job " << job->id() << " succeed.";
G
groot 已提交
2136 2137

                index_failed_checker_.MarkSucceedIndexFile(file_schema);
G
groot 已提交
2138
            }
2139
            status = OngoingFileChecker::GetInstance().UnmarkOngoingFile(file_schema);
2140
        }
G
groot 已提交
2141

2142
        LOG_ENGINE_DEBUG_ << "Background build index thread finished";
G
groot 已提交
2143
        index_req_swn_.Notify();  // notify CreateIndex check circle
Y
Yu Kun 已提交
2144
    }
X
Xu Peng 已提交
2145 2146
}

G
groot 已提交
2147
Status
J
Jin Hai 已提交
2148 2149
DBImpl::GetFilesToBuildIndex(const std::string& collection_id, const std::vector<int>& file_types,
                             meta::SegmentsSchema& files) {
G
groot 已提交
2150
    files.clear();
J
Jin Hai 已提交
2151
    auto status = meta_ptr_->FilesByType(collection_id, file_types, files);
G
groot 已提交
2152 2153 2154

    // only build index for files that row count greater than certain threshold
    for (auto it = files.begin(); it != files.end();) {
J
Jin Hai 已提交
2155
        if ((*it).file_type_ == static_cast<int>(meta::SegmentSchema::RAW) &&
G
groot 已提交
2156 2157 2158
            (*it).row_count_ < meta::BUILD_INDEX_THRESHOLD) {
            it = files.erase(it);
        } else {
2159
            ++it;
G
groot 已提交
2160 2161 2162 2163 2164 2165
        }
    }

    return Status::OK();
}

G
groot 已提交
2166
Status
J
Jin Hai 已提交
2167
DBImpl::GetFilesToSearch(const std::string& collection_id, meta::SegmentsSchema& files) {
2168
    LOG_ENGINE_DEBUG_ << "Collect files from collection: " << collection_id;
2169

J
Jin Hai 已提交
2170 2171
    meta::SegmentsSchema search_files;
    auto status = meta_ptr_->FilesToSearch(collection_id, search_files);
G
groot 已提交
2172 2173 2174 2175
    if (!status.ok()) {
        return status;
    }

2176 2177 2178
    for (auto& file : search_files) {
        files.push_back(file);
    }
G
groot 已提交
2179 2180 2181
    return Status::OK();
}

2182
Status
J
Jin Hai 已提交
2183 2184
DBImpl::GetPartitionByTag(const std::string& collection_id, const std::string& partition_tag,
                          std::string& partition_name) {
2185 2186 2187
    Status status;

    if (partition_tag.empty()) {
J
Jin Hai 已提交
2188
        partition_name = collection_id;
2189 2190 2191 2192 2193 2194 2195 2196

    } else {
        // trim side-blank of tag, only compare valid characters
        // for example: " ab cd " is treated as "ab cd"
        std::string valid_tag = partition_tag;
        server::StringHelpFunctions::TrimStringBlank(valid_tag);

        if (valid_tag == milvus::engine::DEFAULT_PARTITON_TAG) {
J
Jin Hai 已提交
2197
            partition_name = collection_id;
2198 2199 2200
            return status;
        }

J
Jin Hai 已提交
2201
        status = meta_ptr_->GetPartitionName(collection_id, partition_tag, partition_name);
2202
        if (!status.ok()) {
2203
            LOG_ENGINE_ERROR_ << status.message();
2204 2205 2206 2207 2208 2209
        }
    }

    return status;
}

G
groot 已提交
2210
Status
J
Jin Hai 已提交
2211
DBImpl::GetPartitionsByTags(const std::string& collection_id, const std::vector<std::string>& partition_tags,
G
groot 已提交
2212
                            std::set<std::string>& partition_name_array) {
J
Jin Hai 已提交
2213 2214
    std::vector<meta::CollectionSchema> partition_array;
    auto status = meta_ptr_->ShowPartitions(collection_id, partition_array);
G
groot 已提交
2215 2216

    for (auto& tag : partition_tags) {
2217 2218 2219 2220
        // trim side-blank of tag, only compare valid characters
        // for example: " ab cd " is treated as "ab cd"
        std::string valid_tag = tag;
        server::StringHelpFunctions::TrimStringBlank(valid_tag);
2221 2222

        if (valid_tag == milvus::engine::DEFAULT_PARTITON_TAG) {
J
Jin Hai 已提交
2223
            partition_name_array.insert(collection_id);
2224 2225 2226
            return status;
        }

G
groot 已提交
2227
        for (auto& schema : partition_array) {
2228
            if (server::StringHelpFunctions::IsRegexMatch(schema.partition_tag_, valid_tag)) {
J
Jin Hai 已提交
2229
                partition_name_array.insert(schema.collection_id_);
G
groot 已提交
2230 2231 2232 2233
            }
        }
    }

T
Tinkerrr 已提交
2234 2235 2236 2237
    if (partition_name_array.empty()) {
        return Status(PARTITION_NOT_FOUND, "Cannot find the specified partitions");
    }

G
groot 已提交
2238 2239 2240 2241
    return Status::OK();
}

Status
2242
DBImpl::DropCollectionRecursively(const std::string& collection_id) {
J
Jin Hai 已提交
2243
    // dates partly delete files of the collection but currently we don't support
2244
    LOG_ENGINE_DEBUG_ << "Prepare to delete collection " << collection_id;
G
groot 已提交
2245 2246

    Status status;
2247
    if (options_.wal_enable_) {
2248
        wal_mgr_->DropCollection(collection_id);
G
groot 已提交
2249 2250
    }

2251 2252 2253
    status = mem_mgr_->EraseMemVector(collection_id);   // not allow insert
    status = meta_ptr_->DropCollection(collection_id);  // soft delete collection
    index_failed_checker_.CleanFailedIndexFileOfCollection(collection_id);
2254

J
Jin Hai 已提交
2255
    // scheduler will determine when to delete collection files
2256
    auto nres = scheduler::ResMgrInst::GetInstance()->GetNumOfComputeResource();
J
Jin Hai 已提交
2257
    scheduler::DeleteJobPtr job = std::make_shared<scheduler::DeleteJob>(collection_id, meta_ptr_, nres);
2258 2259 2260
    scheduler::JobMgrInst::GetInstance()->Put(job);
    job->WaitAndDelete();

J
Jin Hai 已提交
2261 2262
    std::vector<meta::CollectionSchema> partition_array;
    status = meta_ptr_->ShowPartitions(collection_id, partition_array);
G
groot 已提交
2263
    for (auto& schema : partition_array) {
2264 2265
        status = DropCollectionRecursively(schema.collection_id_);
        fiu_do_on("DBImpl.DropCollectionRecursively.failed", status = Status(DB_ERROR, ""));
G
groot 已提交
2266 2267 2268 2269 2270 2271 2272 2273 2274
        if (!status.ok()) {
            return status;
        }
    }

    return Status::OK();
}

Status
2275
DBImpl::UpdateCollectionIndexRecursively(const std::string& collection_id, const CollectionIndex& index) {
J
Jin Hai 已提交
2276
    DropIndex(collection_id);
G
groot 已提交
2277

2278 2279
    auto status = meta_ptr_->UpdateCollectionIndex(collection_id, index);
    fiu_do_on("DBImpl.UpdateCollectionIndexRecursively.fail_update_collection_index",
S
shengjh 已提交
2280
              status = Status(DB_META_TRANSACTION_FAILED, ""));
G
groot 已提交
2281
    if (!status.ok()) {
2282
        LOG_ENGINE_ERROR_ << "Failed to update collection index info for collection: " << collection_id;
G
groot 已提交
2283 2284 2285
        return status;
    }

J
Jin Hai 已提交
2286 2287
    std::vector<meta::CollectionSchema> partition_array;
    status = meta_ptr_->ShowPartitions(collection_id, partition_array);
G
groot 已提交
2288
    for (auto& schema : partition_array) {
2289
        status = UpdateCollectionIndexRecursively(schema.collection_id_, index);
G
groot 已提交
2290 2291 2292 2293 2294 2295 2296 2297 2298
        if (!status.ok()) {
            return status;
        }
    }

    return Status::OK();
}

Status
2299
DBImpl::WaitCollectionIndexRecursively(const std::string& collection_id, const CollectionIndex& index) {
G
groot 已提交
2300 2301 2302
    // for IDMAP type, only wait all NEW file converted to RAW file
    // for other type, wait NEW/RAW/NEW_MERGE/NEW_INDEX/TO_INDEX files converted to INDEX files
    std::vector<int> file_types;
2303
    if (utils::IsRawIndexType(index.engine_type_)) {
G
groot 已提交
2304
        file_types = {
J
Jin Hai 已提交
2305 2306
            static_cast<int32_t>(meta::SegmentSchema::NEW),
            static_cast<int32_t>(meta::SegmentSchema::NEW_MERGE),
G
groot 已提交
2307 2308 2309
        };
    } else {
        file_types = {
J
Jin Hai 已提交
2310 2311 2312
            static_cast<int32_t>(meta::SegmentSchema::RAW),       static_cast<int32_t>(meta::SegmentSchema::NEW),
            static_cast<int32_t>(meta::SegmentSchema::NEW_MERGE), static_cast<int32_t>(meta::SegmentSchema::NEW_INDEX),
            static_cast<int32_t>(meta::SegmentSchema::TO_INDEX),
G
groot 已提交
2313 2314 2315 2316
        };
    }

    // get files to build index
2317 2318
    meta::SegmentsSchema collection_files;
    auto status = GetFilesToBuildIndex(collection_id, file_types, collection_files);
G
groot 已提交
2319 2320
    int times = 1;

2321
    while (!collection_files.empty()) {
2322
        LOG_ENGINE_DEBUG_ << "Non index files detected! Will build index " << times;
2323
        if (!utils::IsRawIndexType(index.engine_type_)) {
2324
            status = meta_ptr_->UpdateCollectionFilesToIndex(collection_id);
G
groot 已提交
2325 2326
        }

G
groot 已提交
2327
        index_req_swn_.Wait_For(std::chrono::seconds(WAIT_BUILD_INDEX_INTERVAL));
2328
        GetFilesToBuildIndex(collection_id, file_types, collection_files);
2329
        ++times;
G
groot 已提交
2330

2331
        index_failed_checker_.IgnoreFailedIndexFiles(collection_files);
G
groot 已提交
2332 2333 2334
    }

    // build index for partition
J
Jin Hai 已提交
2335 2336
    std::vector<meta::CollectionSchema> partition_array;
    status = meta_ptr_->ShowPartitions(collection_id, partition_array);
G
groot 已提交
2337
    for (auto& schema : partition_array) {
2338 2339
        status = WaitCollectionIndexRecursively(schema.collection_id_, index);
        fiu_do_on("DBImpl.WaitCollectionIndexRecursively.fail_build_collection_Index_for_partition",
S
shengjh 已提交
2340
                  status = Status(DB_ERROR, ""));
G
groot 已提交
2341 2342 2343 2344 2345
        if (!status.ok()) {
            return status;
        }
    }

G
groot 已提交
2346
    // failed to build index for some files, return error
2347
    std::string err_msg;
2348 2349
    index_failed_checker_.GetErrMsgForCollection(collection_id, err_msg);
    fiu_do_on("DBImpl.WaitCollectionIndexRecursively.not_empty_err_msg", err_msg.append("fiu"));
2350 2351
    if (!err_msg.empty()) {
        return Status(DB_ERROR, err_msg);
G
groot 已提交
2352 2353
    }

G
groot 已提交
2354 2355 2356 2357
    return Status::OK();
}

Status
2358
DBImpl::DropCollectionIndexRecursively(const std::string& collection_id) {
2359
    LOG_ENGINE_DEBUG_ << "Drop index for collection: " << collection_id;
2360 2361
    index_failed_checker_.CleanFailedIndexFileOfCollection(collection_id);
    auto status = meta_ptr_->DropCollectionIndex(collection_id);
G
groot 已提交
2362 2363 2364 2365 2366
    if (!status.ok()) {
        return status;
    }

    // drop partition index
J
Jin Hai 已提交
2367 2368
    std::vector<meta::CollectionSchema> partition_array;
    status = meta_ptr_->ShowPartitions(collection_id, partition_array);
G
groot 已提交
2369
    for (auto& schema : partition_array) {
2370 2371
        status = DropCollectionIndexRecursively(schema.collection_id_);
        fiu_do_on("DBImpl.DropCollectionIndexRecursively.fail_drop_collection_Index_for_partition",
S
shengjh 已提交
2372
                  status = Status(DB_ERROR, ""));
G
groot 已提交
2373 2374 2375 2376 2377 2378 2379 2380 2381
        if (!status.ok()) {
            return status;
        }
    }

    return Status::OK();
}

Status
2382
DBImpl::GetCollectionRowCountRecursively(const std::string& collection_id, uint64_t& row_count) {
G
groot 已提交
2383
    row_count = 0;
J
Jin Hai 已提交
2384
    auto status = meta_ptr_->Count(collection_id, row_count);
G
groot 已提交
2385 2386 2387 2388 2389
    if (!status.ok()) {
        return status;
    }

    // get partition row count
J
Jin Hai 已提交
2390 2391
    std::vector<meta::CollectionSchema> partition_array;
    status = meta_ptr_->ShowPartitions(collection_id, partition_array);
G
groot 已提交
2392
    for (auto& schema : partition_array) {
G
groot 已提交
2393
        uint64_t partition_row_count = 0;
2394 2395
        status = GetCollectionRowCountRecursively(schema.collection_id_, partition_row_count);
        fiu_do_on("DBImpl.GetCollectionRowCountRecursively.fail_get_collection_rowcount_for_partition",
S
shengjh 已提交
2396
                  status = Status(DB_ERROR, ""));
G
groot 已提交
2397 2398 2399 2400 2401 2402 2403 2404 2405 2406
        if (!status.ok()) {
            return status;
        }

        row_count += partition_row_count;
    }

    return Status::OK();
}

2407 2408 2409 2410
Status
DBImpl::ExecWalRecord(const wal::MXLogRecord& record) {
    fiu_return_on("DBImpl.ExexWalRecord.return", Status(););

2411 2412
    auto collections_flushed = [&](const std::set<std::string>& collection_ids) -> uint64_t {
        if (collection_ids.empty()) {
2413 2414 2415 2416 2417
            return 0;
        }

        uint64_t max_lsn = 0;
        if (options_.wal_enable_) {
2418
            for (auto& collection : collection_ids) {
2419
                uint64_t lsn = 0;
2420 2421
                meta_ptr_->GetCollectionFlushLSN(collection, lsn);
                wal_mgr_->CollectionFlushed(collection, lsn);
2422 2423 2424 2425 2426 2427 2428
                if (lsn > max_lsn) {
                    max_lsn = lsn;
                }
            }
        }

        std::lock_guard<std::mutex> lck(merge_result_mutex_);
2429 2430
        for (auto& collection : collection_ids) {
            merge_collection_ids_.insert(collection);
2431 2432 2433 2434 2435 2436 2437
        }
        return max_lsn;
    };

    Status status;

    switch (record.type) {
2438 2439 2440 2441
        case wal::MXLogType::Entity: {
            std::string target_collection_name;
            status = GetPartitionByTag(record.collection_id, record.partition_tag, target_collection_name);
            if (!status.ok()) {
2442
                LOG_WAL_ERROR_ << LogOut("[%s][%ld] ", "insert", 0) << "Get partition fail: " << status.message();
2443 2444 2445
                return status;
            }

2446
            std::set<std::string> flushed_collections;
2447 2448 2449
            status = mem_mgr_->InsertEntities(target_collection_name, record.length, record.ids,
                                              (record.data_size / record.length / sizeof(float)),
                                              (const float*)record.data, record.attr_nbytes, record.attr_data_size,
2450 2451
                                              record.attr_data, record.lsn, flushed_collections);
            collections_flushed(flushed_collections);
2452 2453 2454 2455

            milvus::server::CollectInsertMetrics metrics(record.length, status);
            break;
        }
2456
        case wal::MXLogType::InsertBinary: {
2457 2458
            std::string target_collection_name;
            status = GetPartitionByTag(record.collection_id, record.partition_tag, target_collection_name);
2459
            if (!status.ok()) {
2460
                LOG_WAL_ERROR_ << LogOut("[%s][%ld] ", "insert", 0) << "Get partition fail: " << status.message();
2461 2462 2463
                return status;
            }

2464 2465
            std::set<std::string> flushed_collections;
            status = mem_mgr_->InsertVectors(target_collection_name, record.length, record.ids,
2466
                                             (record.data_size / record.length / sizeof(uint8_t)),
2467
                                             (const u_int8_t*)record.data, record.lsn, flushed_collections);
2468
            // even though !status.ok, run
2469
            collections_flushed(flushed_collections);
2470 2471 2472 2473 2474 2475 2476

            // metrics
            milvus::server::CollectInsertMetrics metrics(record.length, status);
            break;
        }

        case wal::MXLogType::InsertVector: {
2477 2478
            std::string target_collection_name;
            status = GetPartitionByTag(record.collection_id, record.partition_tag, target_collection_name);
2479
            if (!status.ok()) {
2480
                LOG_WAL_ERROR_ << LogOut("[%s][%ld] ", "insert", 0) << "Get partition fail: " << status.message();
2481 2482 2483
                return status;
            }

2484 2485
            std::set<std::string> flushed_collections;
            status = mem_mgr_->InsertVectors(target_collection_name, record.length, record.ids,
2486
                                             (record.data_size / record.length / sizeof(float)),
2487
                                             (const float*)record.data, record.lsn, flushed_collections);
2488
            // even though !status.ok, run
2489
            collections_flushed(flushed_collections);
2490 2491 2492 2493 2494 2495 2496

            // metrics
            milvus::server::CollectInsertMetrics metrics(record.length, status);
            break;
        }

        case wal::MXLogType::Delete: {
J
Jin Hai 已提交
2497 2498
            std::vector<meta::CollectionSchema> partition_array;
            status = meta_ptr_->ShowPartitions(record.collection_id, partition_array);
2499 2500 2501 2502
            if (!status.ok()) {
                return status;
            }

2503
            std::vector<std::string> collection_ids{record.collection_id};
2504
            for (auto& partition : partition_array) {
2505 2506
                auto& partition_collection_id = partition.collection_id_;
                collection_ids.emplace_back(partition_collection_id);
2507 2508 2509
            }

            if (record.length == 1) {
2510
                for (auto& collection_id : collection_ids) {
J
Jin Hai 已提交
2511
                    status = mem_mgr_->DeleteVector(collection_id, *record.ids, record.lsn);
2512 2513 2514 2515 2516
                    if (!status.ok()) {
                        return status;
                    }
                }
            } else {
2517
                for (auto& collection_id : collection_ids) {
J
Jin Hai 已提交
2518
                    status = mem_mgr_->DeleteVectors(collection_id, record.length, record.ids, record.lsn);
2519 2520 2521 2522 2523 2524 2525 2526 2527
                    if (!status.ok()) {
                        return status;
                    }
                }
            }
            break;
        }

        case wal::MXLogType::Flush: {
J
Jin Hai 已提交
2528 2529 2530 2531
            if (!record.collection_id.empty()) {
                // flush one collection
                std::vector<meta::CollectionSchema> partition_array;
                status = meta_ptr_->ShowPartitions(record.collection_id, partition_array);
2532 2533 2534 2535
                if (!status.ok()) {
                    return status;
                }

2536
                std::vector<std::string> collection_ids{record.collection_id};
2537
                for (auto& partition : partition_array) {
2538 2539
                    auto& partition_collection_id = partition.collection_id_;
                    collection_ids.emplace_back(partition_collection_id);
2540 2541
                }

2542 2543
                std::set<std::string> flushed_collections;
                for (auto& collection_id : collection_ids) {
2544
                    const std::lock_guard<std::mutex> lock(flush_merge_compact_mutex_);
J
Jin Hai 已提交
2545
                    status = mem_mgr_->Flush(collection_id);
2546 2547 2548
                    if (!status.ok()) {
                        break;
                    }
2549
                    flushed_collections.insert(collection_id);
2550 2551
                }

2552
                collections_flushed(flushed_collections);
2553 2554

            } else {
2555 2556
                // flush all collections
                std::set<std::string> collection_ids;
2557 2558
                {
                    const std::lock_guard<std::mutex> lock(flush_merge_compact_mutex_);
2559
                    status = mem_mgr_->Flush(collection_ids);
2560 2561
                }

2562
                uint64_t lsn = collections_flushed(collection_ids);
2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574
                if (options_.wal_enable_) {
                    wal_mgr_->RemoveOldFiles(lsn);
                }
            }
            break;
        }
    }

    return status;
}

void
G
groot 已提交
2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585
DBImpl::InternalFlush(const std::string& collection_id) {
    wal::MXLogRecord record;
    record.type = wal::MXLogType::Flush;
    record.collection_id = collection_id;
    ExecWalRecord(record);

    StartMergeTask();
}

void
DBImpl::BackgroundWalThread() {
2586
    SetThreadName("wal_thread");
2587 2588
    server::SystemInfo::GetInstance().Init();

2589
    std::chrono::system_clock::time_point next_auto_flush_time;
2590
    auto get_next_auto_flush_time = [&]() {
2591
        return std::chrono::system_clock::now() + std::chrono::seconds(options_.auto_flush_interval_);
2592
    };
2593 2594 2595
    if (options_.auto_flush_interval_ > 0) {
        next_auto_flush_time = get_next_auto_flush_time();
    }
2596 2597

    while (true) {
2598 2599
        if (options_.auto_flush_interval_ > 0) {
            if (std::chrono::system_clock::now() >= next_auto_flush_time) {
G
groot 已提交
2600
                InternalFlush();
2601 2602
                next_auto_flush_time = get_next_auto_flush_time();
            }
2603 2604
        }

G
groot 已提交
2605
        wal::MXLogRecord record;
2606 2607
        auto error_code = wal_mgr_->GetNextRecord(record);
        if (error_code != WAL_SUCCESS) {
2608
            LOG_ENGINE_ERROR_ << "WAL background GetNextRecord error";
2609 2610 2611 2612 2613 2614
            break;
        }

        if (record.type != wal::MXLogType::None) {
            ExecWalRecord(record);
            if (record.type == wal::MXLogType::Flush) {
G
groot 已提交
2615 2616
                // notify flush request to return
                flush_req_swn_.Notify();
2617 2618

                // if user flush all manually, update auto flush also
J
Jin Hai 已提交
2619
                if (record.collection_id.empty() && options_.auto_flush_interval_ > 0) {
2620 2621 2622 2623 2624 2625
                    next_auto_flush_time = get_next_auto_flush_time();
                }
            }

        } else {
            if (!initialized_.load(std::memory_order_acquire)) {
G
groot 已提交
2626 2627
                InternalFlush();
                flush_req_swn_.Notify();
2628 2629
                WaitMergeFileFinish();
                WaitBuildIndexFinish();
2630
                LOG_ENGINE_DEBUG_ << "WAL background thread exit";
2631 2632 2633
                break;
            }

2634
            if (options_.auto_flush_interval_ > 0) {
G
groot 已提交
2635
                swn_wal_.Wait_Until(next_auto_flush_time);
2636
            } else {
G
groot 已提交
2637
                swn_wal_.Wait();
2638
            }
2639 2640 2641 2642
        }
    }
}

G
groot 已提交
2643 2644
void
DBImpl::BackgroundFlushThread() {
2645
    SetThreadName("flush_thread");
G
groot 已提交
2646 2647 2648
    server::SystemInfo::GetInstance().Init();
    while (true) {
        if (!initialized_.load(std::memory_order_acquire)) {
2649
            LOG_ENGINE_DEBUG_ << "DB background flush thread exit";
G
groot 已提交
2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666
            break;
        }

        InternalFlush();
        if (options_.auto_flush_interval_ > 0) {
            swn_flush_.Wait_For(std::chrono::seconds(options_.auto_flush_interval_));
        } else {
            swn_flush_.Wait();
        }
    }
}

void
DBImpl::BackgroundMetricThread() {
    server::SystemInfo::GetInstance().Init();
    while (true) {
        if (!initialized_.load(std::memory_order_acquire)) {
2667
            LOG_ENGINE_DEBUG_ << "DB background metric thread exit";
G
groot 已提交
2668 2669 2670 2671 2672 2673 2674 2675
            break;
        }

        swn_metric_.Wait_For(std::chrono::seconds(BACKGROUND_METRIC_INTERVAL));
        StartMetricTask();
    }
}

2676 2677 2678 2679 2680
void
DBImpl::OnCacheInsertDataChanged(bool value) {
    options_.insert_cache_immediately_ = value;
}

2681 2682 2683 2684 2685
void
DBImpl::OnUseBlasThresholdChanged(int64_t threshold) {
    faiss::distance_compute_blas_threshold = threshold;
}

S
starlord 已提交
2686 2687
}  // namespace engine
}  // namespace milvus