MySqlEngine.cpp 16.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Copyright (C) 2019-2020 Zilliz. All rights reserved.
//
// 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
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License
// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
// or implied. See the License for the specific language governing permissions and limitations under the License.

#include "db/meta/backend/MySqlEngine.h"

#include <memory>
B
BossZou 已提交
15
#include <sstream>
16
#include <string>
B
BossZou 已提交
17
#include <thread>
18 19 20
#include <utility>
#include <vector>

21
#include <fiu/fiu-local.h>
B
BossZou 已提交
22
#include <mysql++/mysql++.h>
23 24

#include "db/Utils.h"
B
BossZou 已提交
25
#include "db/meta/MetaNames.h"
26
#include "db/meta/backend/MetaHelper.h"
B
BossZou 已提交
27
#include "db/meta/backend/MetaSchema.h"
B
BossZou 已提交
28
#include "utils//Log.h"
29 30 31 32 33 34 35
#include "utils/Exception.h"
#include "utils/StringHelpFunctions.h"

namespace milvus::engine::meta {

////////// private namespace //////////
namespace {
B
BossZou 已提交
36
static const auto MetaIdField = MetaField(F_ID, "BIGINT", "PRIMARY KEY AUTO_INCREMENT");
37 38 39 40 41 42 43 44 45 46 47
static const MetaField MetaCollectionIdField = MetaField(F_COLLECTON_ID, "BIGINT", "NOT NULL");
static const MetaField MetaPartitionIdField = MetaField(F_PARTITION_ID, "BIGINT", "NOT NULL");
static const MetaField MetaSchemaIdField = MetaField(F_SCHEMA_ID, "BIGINT", "NOT NULL");
static const MetaField MetaSegmentIdField = MetaField(F_SEGMENT_ID, "BIGINT", "NOT NULL");
static const MetaField MetaFieldElementIdField = MetaField(F_FIELD_ELEMENT_ID, "BIGINT", "NOT NULL");
static const MetaField MetaFieldIdField = MetaField(F_FIELD_ID, "BIGINT", "NOT NULL");
static const MetaField MetaNameField = MetaField(F_NAME, "VARCHAR(255)", "NOT NULL");
static const MetaField MetaMappingsField = MetaField(F_MAPPINGS, "JSON", "NOT NULL");
static const MetaField MetaNumField = MetaField(F_NUM, "BIGINT", "NOT NULL");
static const MetaField MetaLSNField = MetaField(F_LSN, "BIGINT", "NOT NULL");
static const MetaField MetaFtypeField = MetaField(F_FTYPE, "BIGINT", "NOT NULL");
48
static const MetaField MetaFEtypeField = MetaField(F_FETYPE, "BIGINT", "NOT NULL");
49 50 51 52 53 54
static const MetaField MetaStateField = MetaField(F_STATE, "TINYINT", "NOT NULL");
static const MetaField MetaCreatedOnField = MetaField(F_CREATED_ON, "BIGINT", "NOT NULL");
static const MetaField MetaUpdatedOnField = MetaField(F_UPDATED_ON, "BIGINT", "NOT NULL");
static const MetaField MetaParamsField = MetaField(F_PARAMS, "JSON", "NOT NULL");
static const MetaField MetaSizeField = MetaField(F_SIZE, "BIGINT", "NOT NULL");
static const MetaField MetaRowCountField = MetaField(F_ROW_COUNT, "BIGINT", "NOT NULL");
55
static const MetaField MetaTypeNameField = MetaField(F_TYPE_NAME, "VARCHAR(255)", "NOT NULL");
56 57

// Environment schema
B
BossZou 已提交
58 59
static const MetaSchema COLLECTION_SCHEMA(TABLE_COLLECTION, {MetaIdField, MetaNameField, MetaLSNField, MetaParamsField,
                                                             MetaStateField, MetaCreatedOnField, MetaUpdatedOnField});
60 61

// Tables schema
B
BossZou 已提交
62
static const MetaSchema COLLECTIONCOMMIT_SCHEMA(TABLE_COLLECTION_COMMIT,
63 64 65 66 67
                                                {MetaIdField, MetaCollectionIdField, MetaSchemaIdField,
                                                 MetaMappingsField, MetaRowCountField, MetaSizeField, MetaLSNField,
                                                 MetaStateField, MetaCreatedOnField, MetaUpdatedOnField});

// TableFiles schema
B
BossZou 已提交
68
static const MetaSchema PARTITION_SCHEMA(TABLE_PARTITION,
69 70 71 72
                                         {MetaIdField, MetaNameField, MetaCollectionIdField, MetaLSNField,
                                          MetaStateField, MetaCreatedOnField, MetaUpdatedOnField});

// Fields schema
B
BossZou 已提交
73
static const MetaSchema PARTITIONCOMMIT_SCHEMA(TABLE_PARTITION_COMMIT,
74 75 76 77
                                               {MetaIdField, MetaCollectionIdField, MetaPartitionIdField,
                                                MetaMappingsField, MetaRowCountField, MetaSizeField, MetaStateField,
                                                MetaLSNField, MetaCreatedOnField, MetaUpdatedOnField});

B
BossZou 已提交
78 79 80 81 82 83 84 85
static const MetaSchema SEGMENT_SCHEMA(TABLE_SEGMENT,
                                       {MetaIdField, MetaCollectionIdField, MetaPartitionIdField, MetaNumField,
                                        MetaLSNField, MetaStateField, MetaCreatedOnField, MetaUpdatedOnField});

static const MetaSchema SEGMENTCOMMIT_SCHEMA(TABLE_SEGMENT_COMMIT,
                                             {MetaIdField, MetaSchemaIdField, MetaPartitionIdField, MetaSegmentIdField,
                                              MetaMappingsField, MetaRowCountField, MetaSizeField, MetaLSNField,
                                              MetaStateField, MetaCreatedOnField, MetaUpdatedOnField});
B
BossZou 已提交
86 87

static const MetaSchema SEGMENTFILE_SCHEMA(TABLE_SEGMENT_FILE,
88
                                           {MetaIdField, MetaCollectionIdField, MetaPartitionIdField,
89
                                            MetaSegmentIdField, MetaFieldElementIdField, MetaFEtypeField,
90 91
                                            MetaRowCountField, MetaSizeField, MetaLSNField, MetaStateField,
                                            MetaCreatedOnField, MetaUpdatedOnField});
92

B
BossZou 已提交
93 94 95
static const MetaSchema SCHEMACOMMIT_SCHEMA(TABLE_SCHEMA_COMMIT,
                                            {MetaIdField, MetaCollectionIdField, MetaMappingsField, MetaLSNField,
                                             MetaStateField, MetaCreatedOnField, MetaUpdatedOnField});
B
BossZou 已提交
96 97

static const MetaSchema FIELD_SCHEMA(TABLE_FIELD,
98 99 100
                                     {MetaIdField, MetaNameField, MetaNumField, MetaFtypeField, MetaParamsField,
                                      MetaLSNField, MetaStateField, MetaCreatedOnField, MetaUpdatedOnField});

B
BossZou 已提交
101
static const MetaSchema FIELDCOMMIT_SCHEMA(TABLE_FIELD_COMMIT,
102 103 104
                                           {MetaIdField, MetaCollectionIdField, MetaFieldIdField, MetaMappingsField,
                                            MetaLSNField, MetaStateField, MetaCreatedOnField, MetaUpdatedOnField});

B
BossZou 已提交
105
static const MetaSchema FIELDELEMENT_SCHEMA(TABLE_FIELD_ELEMENT,
106
                                            {MetaIdField, MetaCollectionIdField, MetaFieldIdField, MetaNameField,
107
                                             MetaFEtypeField, MetaTypeNameField, MetaParamsField, MetaLSNField,
108
                                             MetaStateField, MetaCreatedOnField, MetaUpdatedOnField});
109 110 111 112 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 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212

}  // namespace

/////////////// MySqlEngine ///////////////
Status
MySqlEngine::Initialize() {
    // step 1: create db root path
    //    if (!boost::filesystem::is_directory(options_.path_)) {
    //        auto ret = boost::filesystem::create_directory(options_.path_);
    //        fiu_do_on("MySQLMetaImpl.Initialize.fail_create_directory", ret = false);
    //        if (!ret) {
    //            std::string msg = "Failed to create db directory " + options_.path_;
    //            LOG_ENGINE_ERROR_ << msg;
    //            throw Exception(DB_META_TRANSACTION_FAILED, msg);
    //        }
    //    }
    std::string uri = options_.backend_uri_;

    // step 2: parse and check meta uri
    utils::MetaUriInfo uri_info;
    auto status = utils::ParseMetaUri(uri, uri_info);
    if (!status.ok()) {
        std::string msg = "Wrong URI format: " + uri;
        LOG_ENGINE_ERROR_ << msg;
        throw Exception(DB_INVALID_META_URI, msg);
    }

    if (strcasecmp(uri_info.dialect_.c_str(), "mysql") != 0) {
        std::string msg = "URI's dialect is not MySQL";
        LOG_ENGINE_ERROR_ << msg;
        throw Exception(DB_INVALID_META_URI, msg);
    }

    // step 3: connect mysql
    unsigned int thread_hint = std::thread::hardware_concurrency();
    int max_pool_size = (thread_hint > 8) ? static_cast<int>(thread_hint) : 8;
    int port = 0;
    if (!uri_info.port_.empty()) {
        port = std::stoi(uri_info.port_);
    }

    mysql_connection_pool_ = std::make_shared<meta::MySQLConnectionPool>(
        uri_info.db_name_, uri_info.username_, uri_info.password_, uri_info.host_, port, max_pool_size);
    LOG_ENGINE_DEBUG_ << "MySQL connection pool: maximum pool size = " << std::to_string(max_pool_size);

    // step 4: validate to avoid open old version schema
    //    ValidateMetaSchema();

    // step 5: clean shadow files
    //    if (mode_ != DBOptions::MODE::CLUSTER_READONLY) {
    //        CleanUpShadowFiles();
    //    }

    // step 6: try connect mysql server
    mysqlpp::ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab_);

    if (connectionPtr == nullptr) {
        std::string msg = "Failed to connect MySQL meta server: " + uri;
        LOG_ENGINE_ERROR_ << msg;
        throw Exception(DB_INVALID_META_URI, msg);
    }

    bool is_thread_aware = connectionPtr->thread_aware();
    fiu_do_on("MySQLMetaImpl.Initialize.is_thread_aware", is_thread_aware = false);
    if (!is_thread_aware) {
        std::string msg =
            "Failed to initialize MySQL meta backend: MySQL client component wasn't built with thread awareness";
        LOG_ENGINE_ERROR_ << msg;
        throw Exception(DB_INVALID_META_URI, msg);
    }

    mysqlpp::Query InitializeQuery = connectionPtr->query();

    auto create_schema = [&](const MetaSchema& schema) {
        std::string create_table_str = "CREATE TABLE IF NOT EXISTS " + schema.name() + "(" + schema.ToString() + ");";
        InitializeQuery << create_table_str;
        //        LOG_ENGINE_DEBUG_ << "Initialize: " << InitializeQuery.str();

        bool initialize_query_exec = InitializeQuery.exec();
        //        fiu_do_on("MySQLMetaImpl.Initialize.fail_create_collection_files", initialize_query_exec = false);
        if (!initialize_query_exec) {
            std::string msg = "Failed to create meta collection '" + schema.name() + "' in MySQL";
            LOG_ENGINE_ERROR_ << msg;
            throw Exception(DB_META_TRANSACTION_FAILED, msg);
        }
    };

    create_schema(COLLECTION_SCHEMA);
    create_schema(COLLECTIONCOMMIT_SCHEMA);
    create_schema(PARTITION_SCHEMA);
    create_schema(PARTITIONCOMMIT_SCHEMA);
    create_schema(SEGMENT_SCHEMA);
    create_schema(SEGMENTCOMMIT_SCHEMA);
    create_schema(SEGMENTFILE_SCHEMA);
    create_schema(SCHEMACOMMIT_SCHEMA);
    create_schema(FIELD_SCHEMA);
    create_schema(FIELDCOMMIT_SCHEMA);
    create_schema(FIELDELEMENT_SCHEMA);

    return Status::OK();
}

Status
MySqlEngine::Query(const MetaQueryContext& context, AttrsMapList& attrs) {
B
BossZou 已提交
213 214 215
    auto status = Status::OK();
    mysqlpp::Connection::thread_start();

216 217
    try {
        mysqlpp::ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab_);
B
BossZou 已提交
218
        if (connectionPtr == nullptr || !connectionPtr->connected()) {
B
BossZou 已提交
219
            mysqlpp::Connection::thread_end();
B
BossZou 已提交
220 221
            return Status(SS_TIMEOUT, "Mysql server is not accessed");
        }
222 223

        std::string sql;
B
BossZou 已提交
224
        status = MetaHelper::MetaQueryContextToSql(context, sql);
225
        if (!status.ok()) {
B
BossZou 已提交
226
            mysqlpp::Connection::thread_end();
227 228 229
            return status;
        }

B
BossZou 已提交
230
        // std::lock_guard<std::mutex> lock(meta_mutex_);
231 232 233
        mysqlpp::Query query = connectionPtr->query(sql);
        auto res = query.store();
        if (!res) {
B
BossZou 已提交
234 235 236 237 238 239
            mysqlpp::Connection::thread_end();
            std::stringstream ss;
            ss << "Mysql query fail: (" << query.errnum() << ": " << query.error() << ")";
            std::string err_msg = ss.str();
            LOG_ENGINE_ERROR_ << err_msg;
            return Status(DB_ERROR, err_msg);
240 241 242 243 244 245
        }

        auto names = res.field_names();
        for (auto& row : res) {
            AttrsMap attrs_map;
            for (auto& name : *names) {
246
                attrs_map.insert(std::make_pair(name, row[name.c_str()]));
247 248 249
            }
            attrs.push_back(attrs_map);
        }
B
BossZou 已提交
250
    } catch (const mysqlpp::ConnectionFailed& er) {
B
BossZou 已提交
251
        status = Status(SS_TIMEOUT, er.what());
252
    } catch (const mysqlpp::BadQuery& er) {
B
BossZou 已提交
253 254
        LOG_ENGINE_ERROR_ << "Query error: " << er.what();
        if (er.errnum() == 2006) {
B
BossZou 已提交
255 256 257
            status = Status(SS_TIMEOUT, er.what());
        } else {
            status = Status(DB_ERROR, er.what());
B
BossZou 已提交
258
        }
259 260 261 262 263
    } catch (const mysqlpp::BadConversion& er) {
        // Handle bad conversions
        //        cerr << "Conversion error: " << er.what() << endl <<
        //             "\tretrieved data size: " << er.retrieved <<
        //             ", actual size: " << er.actual_size << endl;
B
BossZou 已提交
264
        status = Status(DB_ERROR, er.what());
265 266 267
    } catch (const mysqlpp::Exception& er) {
        // Catch-all for any other MySQL++ exceptions
        //        cerr << "Error: " << er.what() << endl;
B
BossZou 已提交
268
        status = Status(DB_ERROR, er.what());
269 270
    }

B
BossZou 已提交
271 272
    mysqlpp::Connection::thread_end();
    return status;
273 274 275 276
}

Status
MySqlEngine::ExecuteTransaction(const std::vector<MetaApplyContext>& sql_contexts, std::vector<int64_t>& result_ids) {
B
BossZou 已提交
277 278 279
    Status status;
    mysqlpp::Connection::thread_start();

280 281
    try {
        mysqlpp::ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab_);
B
BossZou 已提交
282
        if (connectionPtr == nullptr || !connectionPtr->connected()) {
B
BossZou 已提交
283
            mysqlpp::Connection::thread_end();
B
BossZou 已提交
284 285 286
            return Status(SS_TIMEOUT, "Mysql server is not accessed");
        }

287 288
        mysqlpp::Transaction trans(*connectionPtr, mysqlpp::Transaction::serializable, mysqlpp::Transaction::session);

B
BossZou 已提交
289
        // std::lock_guard<std::mutex> lock(meta_mutex_);
290 291
        for (auto& context : sql_contexts) {
            std::string sql;
B
BossZou 已提交
292
            status = MetaHelper::MetaApplyContextToSql(context, sql);
293
            if (!status.ok()) {
B
BossZou 已提交
294
                break;
295 296 297 298
            }

            auto query = connectionPtr->query(sql);
            auto res = query.execute();
B
BossZou 已提交
299 300 301 302 303 304 305
            if (!res) {
                std::stringstream ss;
                ss << "Mysql execute fail: (" << query.errnum() << ": " << query.error() << ")";
                status = Status(DB_ERROR, ss.str());
                break;
            }

306 307 308 309 310 311 312 313
            if (context.op_ == oAdd) {
                auto id = res.insert_id();
                result_ids.push_back(id);
            } else {
                result_ids.push_back(context.id_);
            }
        }

B
BossZou 已提交
314 315 316 317 318
        if (status.ok()) {
            trans.commit();
        } else {
            trans.rollback();
        }
B
BossZou 已提交
319
    } catch (const mysqlpp::ConnectionFailed& er) {
B
BossZou 已提交
320
        status = Status(SS_TIMEOUT, er.what());
321
    } catch (const mysqlpp::BadQuery& er) {
B
BossZou 已提交
322 323
        LOG_ENGINE_ERROR_ << "MySql Error Code: " << er.errnum() << ": " << er.what();
        if (er.errnum() == 2006) {
B
BossZou 已提交
324 325 326
            status = Status(SS_TIMEOUT, er.what());
        } else {
            status = Status(DB_ERROR, er.what());
B
BossZou 已提交
327
        }
328 329 330 331 332 333 334
    } catch (const mysqlpp::BadConversion& er) {
        // Handle bad conversions
        //        cerr << "Conversion error: " << er.what() << endl <<
        //             "\tretrieved data size: " << er.retrieved <<
        //             ", actual size: " << er.actual_size << endl;
        //        return -1;
        //        std::cout << "[DB] Error: " << er.what() << std::endl;
B
BossZou 已提交
335
        status = Status(DB_ERROR, er.what());
336 337 338 339 340
    } catch (const mysqlpp::Exception& er) {
        // Catch-all for any other MySQL++ exceptions
        //        cerr << "Error: " << er.what() << endl;
        //        return -1;
        //        std::cout << "[DB] Error: " << er.what() << std::endl;
B
BossZou 已提交
341
        status = Status(DB_ERROR, er.what());
342 343
    }

B
BossZou 已提交
344 345
    mysqlpp::Connection::thread_end();
    return status;
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
}

Status
MySqlEngine::TruncateAll() {
    static std::vector<std::string> collecton_names = {
        COLLECTION_SCHEMA.name(),      COLLECTIONCOMMIT_SCHEMA.name(), PARTITION_SCHEMA.name(),
        PARTITIONCOMMIT_SCHEMA.name(), SEGMENT_SCHEMA.name(),          SEGMENTCOMMIT_SCHEMA.name(),
        SEGMENTFILE_SCHEMA.name(),     SCHEMACOMMIT_SCHEMA.name(),     FIELD_SCHEMA.name(),
        FIELDCOMMIT_SCHEMA.name(),     FIELDELEMENT_SCHEMA.name(),
    };

    std::vector<MetaApplyContext> contexts;
    for (auto& name : collecton_names) {
        MetaApplyContext context;
        context.sql_ = "TRUNCATE " + name + ";";
        context.id_ = 0;

        contexts.push_back(context);
    }

    std::vector<snapshot::ID_TYPE> ids;
    return ExecuteTransaction(contexts, ids);
}

}  // namespace milvus::engine::meta