diff options
author | Andrew Morrow <acm@mongodb.com> | 2018-05-26 11:11:57 -0400 |
---|---|---|
committer | Andrew Morrow <acm@mongodb.com> | 2018-05-30 15:20:12 -0400 |
commit | 3cb4c2b9abbce0d39ac4d1841fbf9417c32a96a7 (patch) | |
tree | a9936d96d060dea0db2bd65111e198b9e4459009 /src/mongo/client | |
parent | 5e9d5527bdcb71ffcc9ced17741076b71c813c5d (diff) | |
download | mongo-3cb4c2b9abbce0d39ac4d1841fbf9417c32a96a7.tar.gz |
SERVER-33907 Cleanup naming of embedded SDK in preparation for ABI
(cherry picked from commit aea0c0f19b6b61e1d600cda7e69683ad6a9ffed2)
Diffstat (limited to 'src/mongo/client')
32 files changed, 0 insertions, 6102 deletions
diff --git a/src/mongo/client/SConscript b/src/mongo/client/SConscript index 06e3f13236f..a1a4f111bbc 100644 --- a/src/mongo/client/SConscript +++ b/src/mongo/client/SConscript @@ -4,16 +4,6 @@ Import('env') env = env.Clone() - -env.SConscript( - dirs=[ - 'embedded', - ], - exports=[ - 'env', - ], -) - # Contains only the core ConnectionString functionality, *not* the ability to call connect() # and return a DBClientBase* back. For that you need to link against the 'clientdriver' library. env.Library( diff --git a/src/mongo/client/embedded/SConscript b/src/mongo/client/embedded/SConscript deleted file mode 100644 index e9c14e1e716..00000000000 --- a/src/mongo/client/embedded/SConscript +++ /dev/null @@ -1,272 +0,0 @@ -# -*- mode: python; -*- - -Import("env") -Import("get_option") - -env = env.Clone() - -env.Library( - target="service_entry_point_embedded", - source=[ - "service_entry_point_embedded.cpp", - ], - LIBDEPS=[ - '$BUILD_DIR/mongo/base', - '$BUILD_DIR/mongo/transport/service_entry_point', - ], - LIBDEPS_PRIVATE=[ - '$BUILD_DIR/mongo/db/auth/auth', - '$BUILD_DIR/mongo/db/command_can_run_here', - '$BUILD_DIR/mongo/db/rw_concern_d', - '$BUILD_DIR/mongo/db/service_entry_point_common', - '$BUILD_DIR/mongo/db/s/sharding', - '$BUILD_DIR/mongo/db/storage/storage_engine_lock_file', - '$BUILD_DIR/mongo/db/storage/storage_engine_metadata', - ], -) - -env.Library( - target="service_context_embedded", - source=[ - "service_context_embedded.cpp", - ], - LIBDEPS=[ - '$BUILD_DIR/mongo/base', - '$BUILD_DIR/mongo/db/service_context', - '$BUILD_DIR/mongo/transport/service_entry_point', - ], - LIBDEPS_PRIVATE=[ - '$BUILD_DIR/mongo/db/concurrency/lock_manager', - '$BUILD_DIR/mongo/db/storage/storage_engine_lock_file', - '$BUILD_DIR/mongo/db/storage/storage_engine_metadata', - '$BUILD_DIR/mongo/db/storage/storage_options', - 'service_entry_point_embedded', - ], -) - -env.Library( - target='repl_coordinator_embedded', - source=[ - 'replication_coordinator_embedded.cpp', - ], - LIBDEPS=[ - '$BUILD_DIR/mongo/db/repl/repl_coordinator_interface', - '$BUILD_DIR/mongo/db/repl/replica_set_messages', - ], -) - -env.Library( - target="embedded_options", - source=[ - 'embedded_options.cpp', - 'embedded_options_init.cpp', - 'embedded_options_parser_init.cpp', - ], - LIBDEPS=[ - '$BUILD_DIR/mongo/db/server_options', - '$BUILD_DIR/mongo/db/storage/storage_options', - '$BUILD_DIR/mongo/util/options_parser/options_parser', - ], -) - -env.Library( - target="embedded_auth", - source=[ - 'embedded_auth_manager.cpp', - 'embedded_auth_session.cpp', - ], - LIBDEPS=[ - '$BUILD_DIR/mongo/db/auth/auth', - ], -) - -env.Library( - target="embedded_commands", - source=[ - 'embedded_commands.cpp', - 'embedded_ismaster.cpp', - ], - LIBDEPS_PRIVATE=[ - '$BUILD_DIR/mongo/db/commands', - '$BUILD_DIR/mongo/db/commands/standalone', - '$BUILD_DIR/mongo/db/storage/storage_options', - '$BUILD_DIR/mongo/db/wire_version', - '$BUILD_DIR/mongo/rpc/client_metadata', - ], -) - -env.Library( - target='index_create_impl_embedded', - source=[ - 'index_create_impl_embedded.cpp', - ], - LIBDEPS_PRIVATE=[ - '$BUILD_DIR/mongo/db/catalog/catalog_impl', - ], -) - -env.Library( - target='embedded', - source=[ - 'embedded.cpp', - ], - LIBDEPS=[ - '$BUILD_DIR/mongo/base', - ], - LIBDEPS_PRIVATE=[ - '$BUILD_DIR/mongo/db/catalog/catalog_impl', - '$BUILD_DIR/mongo/db/commands/fsync_locked', - '$BUILD_DIR/mongo/db/commands/mongod_fcv', - '$BUILD_DIR/mongo/db/op_observer_d', - '$BUILD_DIR/mongo/db/repair_database_and_check_version', - '$BUILD_DIR/mongo/db/repl/repl_set_status_commands', - '$BUILD_DIR/mongo/db/repl/storage_interface_impl', - '$BUILD_DIR/mongo/db/storage/mobile/storage_mobile', - '$BUILD_DIR/mongo/db/storage/storage_engine_common', - '$BUILD_DIR/mongo/db/storage/storage_init_d', - '$BUILD_DIR/mongo/util/version_impl', - 'embedded_auth', - 'embedded_commands', - 'embedded_options', - 'index_create_impl_embedded', - 'repl_coordinator_embedded', - 'service_context_embedded', - 'service_entry_point_embedded', - ] -) - -capi = env.Library( - target='mongo_embedded_capi', - source=[ - 'libmongodbcapi.cpp', - ], - LIBDEPS_PRIVATE=[ - '$BUILD_DIR/mongo/db/service_context', - '$BUILD_DIR/mongo/rpc/protocol', - '$BUILD_DIR/mongo/transport/transport_layer_mock', - 'embedded', - ], - INSTALL_ALIAS=[ - 'mobile-dev', - ], -) - -env.Alias('embedded_capi', capi) - -if get_option('install-mode') == 'hygienic': - env.AutoInstall( - 'include', - source=['libmongodbcapi.h'], - INSTALL_ALIAS=[ - 'mobile-dev', - ], - ) - -capiTestEnv = env.Clone() -capiTestEnv.InjectThirdPartyIncludePaths(libraries=['yaml']) -capiTest = capiTestEnv.Program( - target='mongo_embedded_capi_test', - source=[ - 'libmongodbcapi_test.cpp', - ], - LIBDEPS=[ - '$BUILD_DIR/mongo/base', - '$BUILD_DIR/mongo/db/commands/test_commands_enabled', - '$BUILD_DIR/mongo/db/server_options_core', - '$BUILD_DIR/mongo/rpc/protocol', - '$BUILD_DIR/mongo/unittest/unittest', - '$BUILD_DIR/mongo/util/net/network', - '$BUILD_DIR/mongo/util/options_parser/options_parser', - 'mongo_embedded_capi', - ], - INSTALL_ALIAS=[ - 'mobile-test', - ], -) - -env.RegisterUnitTest(capiTest[0]) -env.Alias('embedded_capi', capiTest) - -mongoe_env = env.Clone() -mongoe_env.InjectThirdPartyIncludePaths(libraries=['yaml']) -mongoe = mongoe_env.Program( - target='mongoe', - source=[ - 'mongoe_main.cpp', - ], - LIBDEPS=[ - '$BUILD_DIR/mongo/db/commands/shell_protocol', - '$BUILD_DIR/mongo/db/mongod_options', - '$BUILD_DIR/mongo/db/server_options', - '$BUILD_DIR/mongo/transport/transport_layer_manager', - '$BUILD_DIR/mongo/util/signal_handlers', - 'embedded', - ], - INSTALL_ALIAS=[ - 'mobile-test', - ], -) - -hygienic = get_option('install-mode') == 'hygienic' - -if not hygienic: - env.Install('#/', mongoe) - - -if not env['MONGO_HAVE_LIBMONGOC']: - Return() - -embeddedTransport = env.Library( - target='mongo_embedded_transport', - source=[ - 'embedded_transport_layer.cpp', - ], - LIBDEPS=[ - '$BUILD_DIR/mongo/base', - 'mongo_embedded_capi', - ], - LIBDEPS_PRIVATE=[ - '$BUILD_DIR/third_party/shim_zlib', - ], - SYSLIBDEPS=[ - 'mongoc-1.0', - 'bson-1.0', - ], - INSTALL_ALIAS=[ - 'mobile-dev', - ], -) - -env.Alias('embedded_capi', embeddedTransport) - -if get_option('install-mode') == 'hygienic': - env.AutoInstall( - 'include', - source=['embedded_transport_layer.h'], - INSTALL_ALIAS=[ - 'mobile-dev', - ], - ) - -embeddedTransportTestEnv = env.Clone() -embeddedTransportTestEnv.InjectThirdPartyIncludePaths(libraries=['yaml']) -embeddedTransportTest = embeddedTransportTestEnv.Program( - target='mongo_embedded_transport_test', - source=[ - 'embedded_transport_layer_test.cpp', - 'functions_for_test.cpp', - ], - LIBDEPS=[ - '$BUILD_DIR/mongo/base', - '$BUILD_DIR/mongo/db/server_options_core', - '$BUILD_DIR/mongo/unittest/unittest', - '$BUILD_DIR/mongo/util/options_parser/options_parser', - 'mongo_embedded_transport', - ], - INSTALL_ALIAS=[ - 'mobile-test', - ], -) - -env.Alias('embedded_capi', embeddedTransportTest) -env.RegisterUnitTest(embeddedTransportTest[0]); diff --git a/src/mongo/client/embedded/common-operations.cpp b/src/mongo/client/embedded/common-operations.cpp deleted file mode 100644 index 493c334de62..00000000000 --- a/src/mongo/client/embedded/common-operations.cpp +++ /dev/null @@ -1,247 +0,0 @@ -/** - * Copyright (C) 2017 MongoDB Inc. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * - * As a special exception, the copyright holders give permission to link the - * code of portions of this program with the OpenSSL library under certain - * conditions as described in each individual source file and distribute - * linked combinations including the program with the OpenSSL library. You - * must comply with the GNU Affero General Public License in all respects - * for all of the code used other than as permitted herein. If you modify - * file(s) with this exception, you may extend this exception to your - * version of the file(s), but you are not obligated to do so. If you do not - * wish to do so, delete this exception statement from your version. If you - * delete this exception statement from all source files in the program, - * then also delete it in the license file. - */ - -#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kStorage - -#include "mongo/client/embedded/common-operations.h" - -#include <mongoc.h> -#include <stdio.h> - -#include "mongo/client/embedded/embedded_transport_layer.h" -#include "mongo/util/log.h" - -/** - * WARNING: This function is an example lifted directly from the C driver - * for use testing the connection to the c driver. It is written in C, - * and should not be used for anything besides basic testing. - */ -bool mongo::embeddedTest::insert_data(mongoc_collection_t* collection) { - mongoc_bulk_operation_t* bulk; - enum N { ndocs = 4 }; - bson_t* docs[ndocs]; - bson_error_t error; - int i = 0; - bool ret; - - bulk = mongoc_collection_create_bulk_operation(collection, true, NULL); - - docs[0] = BCON_NEW("x", BCON_DOUBLE(1.0), "tags", "[", "dog", "cat", "]"); - docs[1] = BCON_NEW("x", BCON_DOUBLE(2.0), "tags", "[", "cat", "]"); - docs[2] = BCON_NEW("x", BCON_DOUBLE(2.0), "tags", "[", "mouse", "cat", "dog", "]"); - docs[3] = BCON_NEW("x", BCON_DOUBLE(3.0), "tags", "[", "]"); - - for (i = 0; i < ndocs; i++) { - mongoc_bulk_operation_insert(bulk, docs[i]); - bson_destroy(docs[i]); - docs[i] = NULL; - } - - ret = mongoc_bulk_operation_execute(bulk, NULL, &error); - - if (!ret) { - log() << "Error inserting data: " << error.message; - } - - mongoc_bulk_operation_destroy(bulk); - return ret; -} - -/** - * WARNING: This function is an example lifted directly from the C driver - * for use testing the connection to the c driver. It is written in C, - * and should not be used for anything besides basic testing. - */ -bool copydb(mongoc_client_t* client, const char* other_host_and_port) { - mongoc_database_t* admindb; - bson_t* command; - bson_t reply; - bson_error_t error; - bool res; - - BSON_ASSERT(other_host_and_port); - /* Must do this from the admin db */ - admindb = mongoc_client_get_database(client, "admin"); - - command = BCON_NEW("copydb", - BCON_INT32(1), - "fromdb", - BCON_UTF8("test"), - "todb", - BCON_UTF8("test2"), - - /* If you want from a different host */ - "fromhost", - BCON_UTF8(other_host_and_port)); - res = mongoc_database_command_simple(admindb, command, NULL, &reply, &error); - if (!res) { - mongo::log() << "Error with copydb: " << error.message; - goto copy_cleanup; - } - - -copy_cleanup: - bson_destroy(&reply); - bson_destroy(command); - mongoc_database_destroy(admindb); - - return res; -} -/** - * WARNING: This function is an example lifted directly from the C driver - * for use testing the connection to the c driver. It is written in C, - * and should not be used for anything besides basic testing. - */ -bool clone_collection(mongoc_database_t* database, const char* other_host_and_port) { - bson_t* command; - bson_t reply; - bson_error_t error; - bool res; - - BSON_ASSERT(other_host_and_port); - command = BCON_NEW("cloneCollection", - BCON_UTF8("test.remoteThings"), - "from", - BCON_UTF8(other_host_and_port), - "query", - "{", - "x", - BCON_INT32(1), - "}"); - res = mongoc_database_command_simple(database, command, NULL, &reply, &error); - if (!res) { - mongo::log() << "Error with clone: " << error.message; - goto clone_cleanup; - } - - -clone_cleanup: - bson_destroy(&reply); - bson_destroy(command); - - return res; -} -/** - * WARNING: This function is an example lifted directly from the C driver - * for use testing the connection to the c driver. It is written in C, - * and should not be used for anything besides basic testing. - */ -bool mongo::embeddedTest::explain(mongoc_collection_t* collection) { - - bson_t* command; - bson_t reply; - bson_error_t error; - bool res; - - command = BCON_NEW("explain", - "{", - "find", - BCON_UTF8((const char*)"things"), - "filter", - "{", - "x", - BCON_INT32(1), - "}", - "}"); - res = mongoc_collection_command_simple(collection, command, NULL, &reply, &error); - if (!res) { - log() << "Error with explain: " << error.message; - goto explain_cleanup; - } - - -explain_cleanup: - bson_destroy(&reply); - bson_destroy(command); - return res; -} -/** - * WARNING: This function is an example lifted directly from the C driver - * for use testing the connection to the c driver. It is written in C, - * and should not be used for anything besides basic testing. - */ -int mongo::embeddedTest::run_c_driver_all() { - mongoc_database_t* database = NULL; - mongoc_client_t* client = NULL; - mongoc_collection_t* collection = NULL; - char* host_and_port = NULL; - int res = 0; - char* other_host_and_port = NULL; - - - client = mongoc_client_new(NULL); - - if (!client) { - log() << " Invalid client "; - res = 2; - goto cleanup; - } - - mongoc_client_set_error_api(client, 2); - database = mongoc_client_get_database(client, "test"); - collection = mongoc_database_get_collection(database, (const char*)"things"); - - if (!mongo::embeddedTest::insert_data(collection)) { - res = 3; - goto cleanup; - } - - if (!mongo::embeddedTest::explain(collection)) { - res = 4; - goto cleanup; - } - - if (other_host_and_port) { - if (!copydb(client, other_host_and_port)) { - res = 5; - goto cleanup; - } - - if (!clone_collection(database, other_host_and_port)) { - res = 6; - goto cleanup; - } - } - -cleanup: - if (collection) { - mongoc_collection_destroy(collection); - } - - if (database) { - mongoc_database_destroy(database); - } - - if (client) { - mongoc_client_destroy(client); - } - - bson_free(host_and_port); - mongoc_cleanup(); - return res; -} diff --git a/src/mongo/client/embedded/common-operations.h b/src/mongo/client/embedded/common-operations.h deleted file mode 100644 index b5f91eb1d23..00000000000 --- a/src/mongo/client/embedded/common-operations.h +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Copyright (C) 2017 MongoDB Inc. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * - * As a special exception, the copyright holders give permission to link the - * code of portions of this program with the OpenSSL library under certain - * conditions as described in each individual source file and distribute - * linked combinations including the program with the OpenSSL library. You - * must comply with the GNU Affero General Public License in all respects - * for all of the code used other than as permitted herein. If you modify - * file(s) with this exception, you may extend this exception to your - * version of the file(s), but you are not obligated to do so. If you do not - * wish to do so, delete this exception statement from your version. If you - * delete this exception statement from all source files in the program, - * then also delete it in the license file. - */ - -#pragma once - -#include <mongoc.h> - -namespace mongo { - -namespace embeddedTest { - -bool explain(mongoc_collection_t* collection); - -bool insert_data(mongoc_collection_t* collection); - -int run_c_driver_all(); - -} // namespace embeddedTest - -} // namespace mongo diff --git a/src/mongo/client/embedded/embedded.cpp b/src/mongo/client/embedded/embedded.cpp deleted file mode 100644 index afe4efdfa57..00000000000 --- a/src/mongo/client/embedded/embedded.cpp +++ /dev/null @@ -1,323 +0,0 @@ -/** -* Copyright (C) 2018 MongoDB Inc. -* -* This program is free software: you can redistribute it and/or modify -* it under the terms of the GNU Affero General Public License, version 3, -* as published by the Free Software Foundation. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU Affero General Public License for more details. -* -* You should have received a copy of the GNU Affero General Public License -* along with this program. If not, see <http://www.gnu.org/licenses/>. -* -* As a special exception, the copyright holders give permission to link the -* code of portions of this program with the OpenSSL library under certain -* conditions as described in each individual source file and distribute -* linked combinations including the program with the OpenSSL library. You -* must comply with the GNU Affero General Public License in all respects -* for all of the code used other than as permitted herein. If you modify -* file(s) with this exception, you may extend this exception to your -* version of the file(s), but you are not obligated to do so. If you do not -* wish to do so, delete this exception statement from your version. If you -* delete this exception statement from all source files in the program, -* then also delete it in the license file. -*/ - -#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kStorage - -#include "mongo/platform/basic.h" - -#include "mongo/client/embedded/embedded.h" - -#include "mongo/base/initializer.h" -#include "mongo/client/embedded/replication_coordinator_embedded.h" -#include "mongo/client/embedded/service_context_embedded.h" -#include "mongo/client/embedded/service_entry_point_embedded.h" -#include "mongo/config.h" -#include "mongo/db/catalog/database_holder.h" -#include "mongo/db/catalog/health_log.h" -#include "mongo/db/catalog/uuid_catalog.h" -#include "mongo/db/client.h" -#include "mongo/db/commands/feature_compatibility_version.h" -#include "mongo/db/commands/fsync_locked.h" -#include "mongo/db/concurrency/lock_state.h" -#include "mongo/db/dbdirectclient.h" -#include "mongo/db/global_settings.h" -#include "mongo/db/index_rebuilder.h" -#include "mongo/db/kill_sessions_local.h" -#include "mongo/db/logical_clock.h" -#include "mongo/db/op_observer_impl.h" -#include "mongo/db/op_observer_registry.h" -#include "mongo/db/repair_database_and_check_version.h" -#include "mongo/db/repl/storage_interface_impl.h" -#include "mongo/db/service_context_registrar.h" -#include "mongo/db/session_catalog.h" -#include "mongo/db/session_killer.h" -#include "mongo/db/storage/encryption_hooks.h" -#include "mongo/db/storage/storage_engine_init.h" -#include "mongo/db/ttl.h" -#include "mongo/logger/log_component.h" -#include "mongo/scripting/dbdirectclient_factory.h" -#include "mongo/util/background.h" -#include "mongo/util/exit.h" -#include "mongo/util/log.h" -#include "mongo/util/periodic_runner_factory.h" -#include "mongo/util/quick_exit.h" -#include "mongo/util/time_support.h" - -#include <boost/filesystem.hpp> - - -namespace mongo { -namespace embedded { -namespace { -void initWireSpec() { - WireSpec& spec = WireSpec::instance(); - - // The featureCompatibilityVersion behavior defaults to the downgrade behavior while the - // in-memory version is unset. - - spec.incomingInternalClient.minWireVersion = RELEASE_2_4_AND_BEFORE; - spec.incomingInternalClient.maxWireVersion = LATEST_WIRE_VERSION; - - spec.outgoing.minWireVersion = RELEASE_2_4_AND_BEFORE; - spec.outgoing.maxWireVersion = LATEST_WIRE_VERSION; - - spec.isInternalClient = true; -} - - -// Noop, to fulfull dependencies for other initializers -MONGO_INITIALIZER_GENERAL(ForkServer, ("EndStartupOptionHandling"), ("default")) -(InitializerContext* context) { - return Status::OK(); -} - -// Create a minimalistic replication coordinator to provide a limited interface for users. Not -// functional to provide any replication logic. -GlobalInitializerRegisterer replicationManagerInitializer( - "CreateReplicationManager", - {"SSLManager", "ServiceContext", "default"}, - [](InitializerContext* context) { - auto serviceContext = getGlobalServiceContext(); - repl::StorageInterface::set(serviceContext, std::make_unique<repl::StorageInterfaceImpl>()); - - auto logicalClock = stdx::make_unique<LogicalClock>(serviceContext); - LogicalClock::set(serviceContext, std::move(logicalClock)); - - auto replCoord = std::make_unique<ReplicationCoordinatorEmbedded>(serviceContext); - repl::ReplicationCoordinator::set(serviceContext, std::move(replCoord)); - repl::setOplogCollectionName(serviceContext); - return Status::OK(); - }, - [](DeinitializerContext* context) { - auto serviceContext = getGlobalServiceContext(); - - repl::ReplicationCoordinator::set(serviceContext, nullptr); - LogicalClock::set(serviceContext, nullptr); - repl::StorageInterface::set(serviceContext, nullptr); - - return Status::OK(); - }); - -MONGO_INITIALIZER(fsyncLockedForWriting)(InitializerContext* context) { - setLockedForWritingImpl([]() { return false; }); - return Status::OK(); -} -} // namespace - -using logger::LogComponent; -using std::endl; - -void shutdown(ServiceContext* srvContext) { - - Client::initThreadIfNotAlready(); - auto const client = Client::getCurrent(); - auto const serviceContext = client->getServiceContext(); - invariant(srvContext == serviceContext); - - serviceContext->setKillAllOperations(); - - // We should always be able to acquire the global lock at shutdown. - // Close all open databases, shutdown storage engine and run all deinitializers. - auto shutdownOpCtx = serviceContext->makeOperationContext(client); - { - UninterruptibleLockGuard noInterrupt(shutdownOpCtx->lockState()); - Lock::GlobalLock lk(shutdownOpCtx.get(), MODE_X); - DatabaseHolder::getDatabaseHolder().closeAll(shutdownOpCtx.get(), "shutdown"); - - // Shut down the background periodic task runner - if (auto runner = serviceContext->getPeriodicRunner()) { - runner->shutdown(); - } - - // Global storage engine may not be started in all cases before we exit - if (serviceContext->getStorageEngine()) { - shutdownGlobalStorageEngineCleanly(serviceContext); - } - - Status status = mongo::runGlobalDeinitializers(); - uassertStatusOKWithContext(status, "Global deinitilization failed"); - } - shutdownOpCtx.reset(); - - if (Client::getCurrent()) - Client::destroy(); - - setGlobalServiceContext(nullptr); - - log(LogComponent::kControl) << "now exiting"; -} - - -ServiceContext* initialize(const char* yaml_config) { - srand(static_cast<unsigned>(curTimeMicros64())); - - // yaml_config is passed to the options parser through the argc/argv interface that already - // existed. If it is nullptr then use 0 count which will be interpreted as empty string. - const char* argv[2] = {yaml_config, nullptr}; - - Status status = mongo::runGlobalInitializers(yaml_config ? 1 : 0, argv, nullptr); - uassertStatusOKWithContext(status, "Global initilization failed"); - - Client::initThread("initandlisten"); - - initWireSpec(); - - auto serviceContext = getGlobalServiceContext(); - - auto opObserverRegistry = std::make_unique<OpObserverRegistry>(); - opObserverRegistry->addObserver(std::make_unique<OpObserverImpl>()); - opObserverRegistry->addObserver(std::make_unique<UUIDCatalogObserver>()); - serviceContext->setOpObserver(std::move(opObserverRegistry)); - - DBDirectClientFactory::get(serviceContext).registerImplementation([](OperationContext* opCtx) { - return std::unique_ptr<DBClientBase>(new DBDirectClient(opCtx)); - }); - - { - ProcessId pid = ProcessId::getCurrent(); - LogstreamBuilder l = log(LogComponent::kControl); - l << "MongoDB starting : pid=" << pid << " port=" << serverGlobalParams.port - << " dbpath=" << storageGlobalParams.dbpath; - - const bool is32bit = sizeof(int*) == 4; - l << (is32bit ? " 32" : " 64") << "-bit" << endl; - } - - DEV log(LogComponent::kControl) << "DEBUG build (which is slower)" << endl; - - createLockFile(serviceContext); - - serviceContext->setServiceEntryPoint( - std::make_unique<ServiceEntryPointEmbedded>(serviceContext)); - - initializeStorageEngine(serviceContext); - - // Warn if we detect configurations for multiple registered storage engines in the same - // configuration file/environment. - if (serverGlobalParams.parsedOpts.hasField("storage")) { - BSONElement storageElement = serverGlobalParams.parsedOpts.getField("storage"); - invariant(storageElement.isABSONObj()); - for (auto&& e : storageElement.Obj()) { - // Ignore if field name under "storage" matches current storage engine. - if (storageGlobalParams.engine == e.fieldName()) { - continue; - } - - // Warn if field name matches non-active registered storage engine. - if (isRegisteredStorageEngine(serviceContext, e.fieldName())) { - warning() << "Detected configuration for non-active storage engine " - << e.fieldName() << " when current storage engine is " - << storageGlobalParams.engine; - } - } - } - - { - std::stringstream ss; - ss << endl; - ss << "*********************************************************************" << endl; - ss << " ERROR: dbpath (" << storageGlobalParams.dbpath << ") does not exist." << endl; - ss << " Create this directory or give existing directory in --dbpath." << endl; - ss << " See http://dochub.mongodb.org/core/startingandstoppingmongo" << endl; - ss << "*********************************************************************" << endl; - uassert(50677, ss.str().c_str(), boost::filesystem::exists(storageGlobalParams.dbpath)); - } - - { - std::stringstream ss; - ss << "repairpath (" << storageGlobalParams.repairpath << ") does not exist"; - uassert(50678, ss.str().c_str(), boost::filesystem::exists(storageGlobalParams.repairpath)); - } - - if (!storageGlobalParams.readOnly) { - boost::filesystem::remove_all(storageGlobalParams.dbpath + "/_tmp/"); - } - - auto startupOpCtx = serviceContext->makeOperationContext(&cc()); - - bool canCallFCVSetIfCleanStartup = - !storageGlobalParams.readOnly && !(storageGlobalParams.engine == "devnull"); - if (canCallFCVSetIfCleanStartup) { - Lock::GlobalWrite lk(startupOpCtx.get()); - FeatureCompatibilityVersion::setIfCleanStartup(startupOpCtx.get(), - repl::StorageInterface::get(serviceContext)); - } - - auto swNonLocalDatabases = repairDatabasesAndCheckVersion(startupOpCtx.get()); - if (!swNonLocalDatabases.isOK()) { - // SERVER-31611 introduced a return value to `repairDatabasesAndCheckVersion`. Previously, - // a failing condition would fassert. SERVER-31611 covers a case where the binary (3.6) is - // refusing to start up because it refuses acknowledgement of FCV 3.2 and requires the - // user to start up with an older binary. Thus shutting down the server must leave the - // datafiles in a state that the older binary can start up. This requires going through a - // clean shutdown. - // - // The invariant is *not* a statement that `repairDatabasesAndCheckVersion` must return - // `MustDowngrade`. Instead, it is meant as a guardrail to protect future developers from - // accidentally buying into this behavior. New errors that are returned from the method - // may or may not want to go through a clean shutdown, and they likely won't want the - // program to return an exit code of `EXIT_NEED_DOWNGRADE`. - severe(LogComponent::kControl) << "** IMPORTANT: " - << swNonLocalDatabases.getStatus().reason(); - invariant(swNonLocalDatabases == ErrorCodes::MustDowngrade); - quickExit(EXIT_NEED_DOWNGRADE); - } - - // Assert that the in-memory featureCompatibilityVersion parameter has been explicitly set. If - // we are part of a replica set and are started up with no data files, we do not set the - // featureCompatibilityVersion until a primary is chosen. For this case, we expect the in-memory - // featureCompatibilityVersion parameter to still be uninitialized until after startup. - if (canCallFCVSetIfCleanStartup) { - invariant(serverGlobalParams.featureCompatibility.isVersionInitialized()); - } - - if (storageGlobalParams.upgrade) { - log() << "finished checking dbs"; - exitCleanly(EXIT_CLEAN); - } - - // This is for security on certain platforms (nonce generation) - srand((unsigned)(curTimeMicros64()) ^ (unsigned(uintptr_t(&startupOpCtx)))); - - if (!storageGlobalParams.readOnly) { - restartInProgressIndexesFromLastShutdown(startupOpCtx.get()); - } - - // MessageServer::run will return when exit code closes its socket and we don't need the - // operation context anymore - startupOpCtx.reset(); - - // Make sure current thread have no client set in thread_local - Client::releaseCurrent(); - - serviceContext->notifyStartupComplete(); - - return serviceContext; -} -} // namespace embedded -} // namespace mongo diff --git a/src/mongo/client/embedded/embedded.h b/src/mongo/client/embedded/embedded.h deleted file mode 100644 index 8601b4e709a..00000000000 --- a/src/mongo/client/embedded/embedded.h +++ /dev/null @@ -1,40 +0,0 @@ -/** -* Copyright (C) 2018 MongoDB Inc. -* -* This program is free software: you can redistribute it and/or modify -* it under the terms of the GNU Affero General Public License, version 3, -* as published by the Free Software Foundation. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU Affero General Public License for more details. -* -* You should have received a copy of the GNU Affero General Public License -* along with this program. If not, see <http://www.gnu.org/licenses/>. -* -* As a special exception, the copyright holders give permission to link the -* code of portions of this program with the OpenSSL library under certain -* conditions as described in each individual source file and distribute -* linked combinations including the program with the OpenSSL library. You -* must comply with the GNU Affero General Public License in all respects -* for all of the code used other than as permitted herein. If you modify -* file(s) with this exception, you may extend this exception to your -* version of the file(s), but you are not obligated to do so. If you do not -* wish to do so, delete this exception statement from your version. If you -* delete this exception statement from all source files in the program, -* then also delete it in the license file. -*/ - -#pragma once - -#include "mongo/platform/basic.h" - -namespace mongo { -class ServiceContext; - -namespace embedded { -ServiceContext* initialize(const char* yaml_config); -void shutdown(ServiceContext* serviceContext); -} // namespace embedded -} // namespace mongo diff --git a/src/mongo/client/embedded/embedded_auth_manager.cpp b/src/mongo/client/embedded/embedded_auth_manager.cpp deleted file mode 100644 index 4680777e9fa..00000000000 --- a/src/mongo/client/embedded/embedded_auth_manager.cpp +++ /dev/null @@ -1,144 +0,0 @@ -/** - * Copyright (C) 2018 MongoDB Inc. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * - * As a special exception, the copyright holders give permission to link the - * code of portions of this program with the OpenSSL library under certain - * conditions as described in each individual source file and distribute - * linked combinations including the program with the OpenSSL library. You - * must comply with the GNU Affero General Public License in all respects - * for all of the code used other than as permitted herein. If you modify - * file(s) with this exception, you may extend this exception to your - * version of the file(s), but you are not obligated to do so. If you do not - * wish to do so, delete this exception statement from your version. If you - * delete this exception statement from all source files in the program, - * then also delete it in the license file. - */ - -#include "mongo/platform/basic.h" - -#include "mongo/client/embedded/not_implemented.h" -#include "mongo/db/auth/authorization_manager.h" -#include "mongo/db/auth/authorization_session.h" -#include "mongo/util/assert_util.h" - -namespace mongo { -namespace embedded { -namespace { -class AuthorizationManager : public mongo::AuthorizationManager { -public: - std::unique_ptr<AuthorizationSession> makeAuthorizationSession() override { - return AuthorizationSession::create(this); - } - - void setShouldValidateAuthSchemaOnStartup(const bool check) override { - _shouldValidate = check; - } - bool shouldValidateAuthSchemaOnStartup() override { - return _shouldValidate; - } - void setAuthEnabled(const bool state) override { - invariant(!state); - } - - bool isAuthEnabled() const override { - return false; - } - - Status getAuthorizationVersion(OperationContext*, int*) override { - UASSERT_NOT_IMPLEMENTED; - } - - OID getCacheGeneration() override { - UASSERT_NOT_IMPLEMENTED; - } - - bool hasAnyPrivilegeDocuments(OperationContext*) override { - UASSERT_NOT_IMPLEMENTED; - } - - Status getUserDescription(OperationContext*, const UserName&, BSONObj*) override { - UASSERT_NOT_IMPLEMENTED; - } - - Status getRoleDescription(OperationContext*, - const RoleName&, - PrivilegeFormat, - AuthenticationRestrictionsFormat, - BSONObj*) override { - UASSERT_NOT_IMPLEMENTED; - } - - Status getRolesDescription(OperationContext*, - const std::vector<RoleName>&, - PrivilegeFormat, - AuthenticationRestrictionsFormat, - BSONObj*) override { - UASSERT_NOT_IMPLEMENTED; - } - - Status getRoleDescriptionsForDB(OperationContext*, - std::string, - PrivilegeFormat, - AuthenticationRestrictionsFormat, - bool, - std::vector<BSONObj>*) override { - UASSERT_NOT_IMPLEMENTED; - } - - Status acquireUser(OperationContext*, const UserName&, User**) override { - UASSERT_NOT_IMPLEMENTED; - } - - void releaseUser(User* user) override { - UASSERT_NOT_IMPLEMENTED; - } - - void invalidateUserByName(const UserName& user) override { - UASSERT_NOT_IMPLEMENTED; - } - - void invalidateUsersFromDB(const std::string& dbname) override { - UASSERT_NOT_IMPLEMENTED; - } - - Status initialize(OperationContext* opCtx) override { - UASSERT_NOT_IMPLEMENTED; - } - - void invalidateUserCache() override { - UASSERT_NOT_IMPLEMENTED; - } - - Status _initializeUserFromPrivilegeDocument(User*, const BSONObj&) override { - UASSERT_NOT_IMPLEMENTED; - } - - void logOp(OperationContext*, - const char*, - const NamespaceString&, - const BSONObj&, - const BSONObj*) override { /* do nothing*/ - } - -private: - bool _shouldValidate = false; -}; -} // namespace -} // namespace embedded - -MONGO_REGISTER_SHIM(AuthorizationManager::create)()->std::unique_ptr<AuthorizationManager> { - return std::make_unique<embedded::AuthorizationManager>(); -} -} // namespace mongo diff --git a/src/mongo/client/embedded/embedded_auth_session.cpp b/src/mongo/client/embedded/embedded_auth_session.cpp deleted file mode 100644 index 7ec995360a0..00000000000 --- a/src/mongo/client/embedded/embedded_auth_session.cpp +++ /dev/null @@ -1,275 +0,0 @@ -/** - * Copyright (C) 2018 MongoDB Inc. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * - * As a special exception, the copyright holders give permission to link the - * code of portions of this program with the OpenSSL library under certain - * conditions as described in each individual source file and distribute - * linked combinations including the program with the OpenSSL library. You - * must comply with the GNU Affero General Public License in all respects - * for all of the code used other than as permitted herein. If you modify - * file(s) with this exception, you may extend this exception to your - * version of the file(s), but you are not obligated to do so. If you do not - * wish to do so, delete this exception statement from your version. If you - * delete this exception statement from all source files in the program, - * then also delete it in the license file. - */ - -#include "mongo/platform/basic.h" - -#include "mongo/client/embedded/not_implemented.h" -#include "mongo/db/auth/authorization_manager.h" -#include "mongo/db/auth/authorization_session.h" -#include "mongo/util/assert_util.h" - -namespace mongo { -namespace embedded { -namespace { -class Impl : public UserNameIterator::Impl { - bool more() const override { - return false; - } - const UserName& get() const override { - UASSERT_NOT_IMPLEMENTED; - } - - const UserName& next() override { - UASSERT_NOT_IMPLEMENTED; - } - - Impl* doClone() const override { - return new Impl(*this); - } -}; - - -class AuthorizationSession : public mongo::AuthorizationSession { -public: - explicit AuthorizationSession(AuthorizationManager* const authzManager) - : _authzManager(authzManager) {} - - AuthorizationManager& getAuthorizationManager() override { - return *_authzManager; - } - - void startRequest(OperationContext*) override { - // It is always okay to start a request in embedded. - } - - Status addAndAuthorizeUser(OperationContext*, const UserName&) override { - UASSERT_NOT_IMPLEMENTED; - } - - User* lookupUser(const UserName&) override { - UASSERT_NOT_IMPLEMENTED; - } - - User* getSingleUser() override { - UASSERT_NOT_IMPLEMENTED; - } - - bool isAuthenticated() override { - UASSERT_NOT_IMPLEMENTED; - } - - UserNameIterator getAuthenticatedUserNames() override { - return UserNameIterator(std::make_unique<Impl>()); - } - - RoleNameIterator getAuthenticatedRoleNames() override { - UASSERT_NOT_IMPLEMENTED; - } - - std::string getAuthenticatedUserNamesToken() override { - UASSERT_NOT_IMPLEMENTED; - } - - void grantInternalAuthorization() override { - // Always okay to do something, on embedded. - } - - void logoutDatabase(const std::string&) override { - UASSERT_NOT_IMPLEMENTED; - } - - PrivilegeVector getDefaultPrivileges() override { - UASSERT_NOT_IMPLEMENTED; - } - - Status checkAuthForFind(const NamespaceString&, bool) override { - return Status::OK(); - } - - Status checkAuthForGetMore(const NamespaceString&, long long, bool) override { - return Status::OK(); - } - - Status checkAuthForUpdate( - OperationContext*, const NamespaceString&, const BSONObj&, const BSONObj&, bool) override { - return Status::OK(); - } - - Status checkAuthForInsert(OperationContext*, const NamespaceString&, const BSONObj&) override { - return Status::OK(); - } - - Status checkAuthForDelete(OperationContext*, const NamespaceString&, const BSONObj&) override { - return Status::OK(); - } - - Status checkAuthForKillCursors(const NamespaceString&, UserNameIterator) override { - return Status::OK(); - } - - Status checkAuthForAggregate(const NamespaceString&, const BSONObj&, bool) override { - return Status::OK(); - } - - Status checkAuthForCreate(const NamespaceString&, const BSONObj&, bool) override { - return Status::OK(); - } - - Status checkAuthForCollMod(const NamespaceString&, const BSONObj&, bool) override { - return Status::OK(); - } - - Status checkAuthorizedToGrantPrivilege(const Privilege&) override { - return Status::OK(); - } - - Status checkAuthorizedToRevokePrivilege(const Privilege&) override { - return Status::OK(); - } - - bool isUsingLocalhostBypass() override { - return false; - } - - bool isAuthorizedToParseNamespaceElement(const BSONElement&) override { - return true; - } - - bool isAuthorizedToCreateRole(const auth::CreateOrUpdateRoleArgs&) override { - return true; - } - - bool isAuthorizedToGrantRole(const RoleName&) override { - return true; - } - - bool isAuthorizedToRevokeRole(const RoleName&) override { - return true; - } - - bool isAuthorizedToChangeAsUser(const UserName&, ActionType) override { - return true; - } - - bool isAuthorizedToChangeOwnPasswordAsUser(const UserName&) override { - return true; - } - - bool isAuthorizedToListCollections(StringData, const BSONObj&) override { - return true; - } - - bool isAuthorizedToChangeOwnCustomDataAsUser(const UserName&) override { - return true; - } - - bool isAuthenticatedAsUserWithRole(const RoleName&) override { - return true; - } - - bool isAuthorizedForPrivilege(const Privilege&) override { - return true; - } - - bool isAuthorizedForPrivileges(const std::vector<Privilege>&) override { - return true; - } - - bool isAuthorizedForActionsOnResource(const ResourcePattern&, ActionType) override { - return true; - } - - bool isAuthorizedForActionsOnResource(const ResourcePattern&, const ActionSet&) override { - return true; - } - - bool isAuthorizedForActionsOnNamespace(const NamespaceString&, ActionType) override { - return true; - } - - bool isAuthorizedForActionsOnNamespace(const NamespaceString&, const ActionSet&) override { - return true; - } - - void setImpersonatedUserData(std::vector<UserName>, std::vector<RoleName>) override { - UASSERT_NOT_IMPLEMENTED; - } - - UserNameIterator getImpersonatedUserNames() override { - UASSERT_NOT_IMPLEMENTED; - } - - RoleNameIterator getImpersonatedRoleNames() override { - UASSERT_NOT_IMPLEMENTED; - } - - void clearImpersonatedUserData() override { - UASSERT_NOT_IMPLEMENTED; - } - - bool isCoauthorizedWithClient(Client*) override { - return true; - } - - bool isCoauthorizedWith(UserNameIterator) override { - return true; - } - - bool isImpersonating() const override { - UASSERT_NOT_IMPLEMENTED; - } - - Status checkCursorSessionPrivilege(OperationContext*, - boost::optional<LogicalSessionId>) override { - return Status::OK(); - } - - bool isAuthorizedForAnyActionOnAnyResourceInDB(StringData) override { - return true; - } - - bool isAuthorizedForAnyActionOnResource(const ResourcePattern&) override { - return true; - } - -protected: - std::tuple<std::vector<UserName>*, std::vector<RoleName>*> _getImpersonations() override { - UASSERT_NOT_IMPLEMENTED; - } - -private: - AuthorizationManager* const _authzManager; -}; -} // namespace -} // namespace embedded - -MONGO_REGISTER_SHIM(AuthorizationSession::create) -(AuthorizationManager* const authzManager)->std::unique_ptr<AuthorizationSession> { - return std::make_unique<embedded::AuthorizationSession>(authzManager); -} -} // namespace mongo diff --git a/src/mongo/client/embedded/embedded_commands.cpp b/src/mongo/client/embedded/embedded_commands.cpp deleted file mode 100644 index ff288428e73..00000000000 --- a/src/mongo/client/embedded/embedded_commands.cpp +++ /dev/null @@ -1,130 +0,0 @@ -/** -* Copyright (C) 2018 MongoDB Inc. -* -* This program is free software: you can redistribute it and/or modify -* it under the terms of the GNU Affero General Public License, version 3, -* as published by the Free Software Foundation. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU Affero General Public License for more details. -* -* You should have received a copy of the GNU Affero General Public License -* along with this program. If not, see <http://www.gnu.org/licenses/>. -* -* As a special exception, the copyright holders give permission to link the -* code of portions of this program with the OpenSSL library under certain -* conditions as described in each individual source file and distribute -* linked combinations including the program with the OpenSSL library. You -* must comply with the GNU Affero General Public License in all respects -* for all of the code used other than as permitted herein. If you modify -* file(s) with this exception, you may extend this exception to your -* version of the file(s), but you are not obligated to do so. If you do not -* wish to do so, delete this exception statement from your version. If you -* delete this exception statement from all source files in the program, -* then also delete it in the license file. -*/ - -#include "mongo/platform/basic.h" - -#include "mongo/db/commands.h" - -namespace mongo { - -class CmdTrimMemory : public BasicCommand { -public: - CmdTrimMemory() : BasicCommand("trimMemory") {} - - AllowedOnSecondary secondaryAllowed(ServiceContext*) const override { - return AllowedOnSecondary::kNever; - } - - bool adminOnly() const override { - return false; - } - - bool supportsWriteConcern(const BSONObj& cmd) const override { - return false; - } - - void addRequiredPrivileges(const std::string& dbname, - const BSONObj& cmdObj, - std::vector<Privilege>* out) const override { - } // No auth in embedded - - std::string help() const override { - return "Gives the database an opportunity to trim memory usage. Valid parameters are " - "conservative|moderate|aggressive to describe trim method."; - } - - bool run(OperationContext* opCtx, - const std::string& dbname, - const BSONObj& jsobj, - BSONObjBuilder& result) override { - - // TODO: Implement trimMemory https://jira.mongodb.org/browse/SERVER-34131 - - std::string mode = jsobj[getName()].String(); - if (mode == "aggressive") { - - } else if (mode == "moderate") { - - } else if (mode == "conservative") { - - } else { - uasserted(ErrorCodes::InvalidOptions, - "Only conservative|moderate|aggressive are valid options."); - } - return true; - } - -} cmdTrimMemory; - -class CmdBatteryLevel : public BasicCommand { -public: - CmdBatteryLevel() : BasicCommand("setBatteryLevel") {} - - AllowedOnSecondary secondaryAllowed(ServiceContext*) const override { - return AllowedOnSecondary::kNever; - } - - bool adminOnly() const override { - return false; - } - - bool supportsWriteConcern(const BSONObj& cmd) const override { - return false; - } - - void addRequiredPrivileges(const std::string& dbname, - const BSONObj& cmdObj, - std::vector<Privilege>* out) const override { - } // No auth in embedded - - std::string help() const override { - return "Notifies the database of the battery level on host device. Valid parameters are " - "low|normal to describe the battery level."; - } - - bool run(OperationContext* opCtx, - const std::string& dbname, - const BSONObj& jsobj, - BSONObjBuilder& result) override { - - // TODO: Implement setBatteryLevel https://jira.mongodb.org/browse/SERVER-34132 - - std::string mode = jsobj[getName()].String(); - if (mode == "low") { - - } else if (mode == "normal") { - - } else { - uasserted(ErrorCodes::InvalidOptions, "Only low|normal are valid options."); - } - return true; - } - -} cmdBatteryLevel; - -} // namespace mongo diff --git a/src/mongo/client/embedded/embedded_ismaster.cpp b/src/mongo/client/embedded/embedded_ismaster.cpp deleted file mode 100644 index eb45ed178b4..00000000000 --- a/src/mongo/client/embedded/embedded_ismaster.cpp +++ /dev/null @@ -1,111 +0,0 @@ -/** -* Copyright (C) 2008-2014 MongoDB Inc. -* -* This program is free software: you can redistribute it and/or modify -* it under the terms of the GNU Affero General Public License, version 3, -* as published by the Free Software Foundation. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU Affero General Public License for more details. -* -* You should have received a copy of the GNU Affero General Public License -* along with this program. If not, see <http://www.gnu.org/licenses/>. -* -* As a special exception, the copyright holders give permission to link the -* code of portions of this program with the OpenSSL library under certain -* conditions as described in each individual source file and distribute -* linked combinations including the program with the OpenSSL library. You -* must comply with the GNU Affero General Public License in all respects for -* all of the code used other than as permitted herein. If you modify file(s) -* with this exception, you may extend this exception to your version of the -* file(s), but you are not obligated to do so. If you do not wish to do so, -* delete this exception statement from your version. If you delete this -* exception statement from all source files in the program, then also delete -* it in the license file. -*/ -#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kCommand - -#include "mongo/platform/basic.h" - -#include "mongo/db/commands.h" -#include "mongo/db/ops/write_ops.h" -#include "mongo/rpc/metadata/client_metadata.h" -#include "mongo/rpc/metadata/client_metadata_ismaster.h" - -namespace mongo { -namespace { - -class CmdIsMaster : public BasicCommand { -public: - bool requiresAuth() const override { - return false; - } - - AllowedOnSecondary secondaryAllowed(ServiceContext*) const override { - return AllowedOnSecondary::kAlways; - } - - std::string help() const override { - return "Check if this server is primary for a replica set\n" - "{ isMaster : 1 }"; - } - - virtual bool supportsWriteConcern(const BSONObj& cmd) const override { - return false; - } - - virtual void addRequiredPrivileges(const std::string& dbname, - const BSONObj& cmdObj, - std::vector<Privilege>* out) const {} // No auth required - - CmdIsMaster() : BasicCommand("isMaster", "ismaster") {} - - virtual bool run(OperationContext* opCtx, - const std::string&, - const BSONObj& cmdObj, - BSONObjBuilder& result) { - - auto& clientMetadataIsMasterState = ClientMetadataIsMasterState::get(opCtx->getClient()); - bool seenIsMaster = clientMetadataIsMasterState.hasSeenIsMaster(); - if (!seenIsMaster) { - clientMetadataIsMasterState.setSeenIsMaster(); - } - - BSONElement element = cmdObj[kMetadataDocumentName]; - if (!element.eoo()) { - if (seenIsMaster) { - uasserted(ErrorCodes::ClientMetadataCannotBeMutated, - "The client metadata document may only be sent in the first isMaster"); - } - - auto swParseClientMetadata = ClientMetadata::parse(element); - uassertStatusOK(swParseClientMetadata.getStatus()); - - invariant(swParseClientMetadata.getValue()); - - swParseClientMetadata.getValue().get().logClientMetadata(opCtx->getClient()); - - clientMetadataIsMasterState.setClientMetadata( - opCtx->getClient(), std::move(swParseClientMetadata.getValue())); - } - - result.appendBool("ismaster", true); - - result.appendNumber("maxBsonObjectSize", BSONObjMaxUserSize); - result.appendNumber("maxMessageSizeBytes", MaxMessageSizeBytes); - result.appendNumber("maxWriteBatchSize", write_ops::kMaxWriteBatchSize); - result.appendDate("localTime", jsTime()); - - result.append("minWireVersion", WireSpec::instance().incomingExternalClient.minWireVersion); - result.append("maxWireVersion", WireSpec::instance().incomingExternalClient.maxWireVersion); - - result.append("readOnly", storageGlobalParams.readOnly); - - return true; - } -} CmdIsMaster; - -} // namespace repl -} // namespace mongo diff --git a/src/mongo/client/embedded/embedded_log_appender.h b/src/mongo/client/embedded/embedded_log_appender.h deleted file mode 100644 index 4e327f23020..00000000000 --- a/src/mongo/client/embedded/embedded_log_appender.h +++ /dev/null @@ -1,77 +0,0 @@ -/* Copyright 2018 MongoDB Inc. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * - * As a special exception, the copyright holders give permission to link the - * code of portions of this program with the OpenSSL library under certain - * conditions as described in each individual source file and distribute - * linked combinations including the program with the OpenSSL library. You - * must comply with the GNU Affero General Public License in all respects - * for all of the code used other than as permitted herein. If you modify - * file(s) with this exception, you may extend this exception to your - * version of the file(s), but you are not obligated to do so. If you do not - * wish to do so, delete this exception statement from your version. If you - * delete this exception statement from all source files in the program, - * then also delete it in the license file. - */ - -#pragma once - -#include <functional> -#include <sstream> - -#include "mongo/base/status.h" -#include "mongo/logger/appender.h" -#include "mongo/logger/encoder.h" - -namespace mongo { -namespace embedded { - -/** - * Appender for writing to callbacks registered with the embedded C API. - */ -template <typename Event> -class EmbeddedLogAppender : public logger::Appender<Event> { - EmbeddedLogAppender(EmbeddedLogAppender const&) = delete; - EmbeddedLogAppender& operator=(EmbeddedLogAppender const&) = delete; - -public: - typedef logger::Encoder<Event> EventEncoder; - - explicit EmbeddedLogAppender( - std::function<void(void*, const char*, const char*, const char*, int)> callback, - void* callbackUserData, - std::unique_ptr<EventEncoder> encoder) - : _encoder(std::move(encoder)), - _callback(std::move(callback)), - _callbackUserData(callbackUserData) {} - - Status append(const Event& event) final { - std::stringstream output; - _encoder->encode(event, output); - _callback(_callbackUserData, - output.str().c_str(), - event.getComponent().getShortName().c_str(), - event.getContextName().toString().c_str(), - event.getSeverity().toInt()); - return Status::OK(); - } - -private: - std::unique_ptr<EventEncoder> _encoder; - std::function<void(void*, const char*, const char*, const char*, int)> _callback; - void* const _callbackUserData; -}; - -} // namespace embedded -} // namespace mongo diff --git a/src/mongo/client/embedded/embedded_options.cpp b/src/mongo/client/embedded/embedded_options.cpp deleted file mode 100644 index 8d1096a2300..00000000000 --- a/src/mongo/client/embedded/embedded_options.cpp +++ /dev/null @@ -1,177 +0,0 @@ -/* - * Copyright (C) 2018 MongoDB Inc. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * - * As a special exception, the copyright holders give permission to link the - * code of portions of this program with the OpenSSL library under certain - * conditions as described in each individual source file and distribute - * linked combinations including the program with the OpenSSL library. You - * must comply with the GNU Affero General Public License in all respects for - * all of the code used other than as permitted herein. If you modify file(s) - * with this exception, you may extend this exception to your version of the - * file(s), but you are not obligated to do so. If you do not wish to do so, - * delete this exception statement from your version. If you delete this - * exception statement from all source files in the program, then also delete - * it in the license file. - */ - -#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kControl - -#include "mongo/client/embedded/embedded_options.h" - -#include "mongo/db/server_options.h" -#include "mongo/db/server_options_helpers.h" -#include "mongo/db/storage/storage_options.h" - -#include <boost/filesystem.hpp> -#include <string> - -namespace mongo { -namespace embedded { - -using std::string; - -Status addOptions(optionenvironment::OptionSection* options) { - moe::OptionSection general_options("General options"); - - Status ret = addBaseServerOptions(&general_options); - if (!ret.isOK()) { - return ret; - } - - moe::OptionSection storage_options("Storage options"); - - storage_options - .addOptionChaining( - "storage.engine", "storageEngine", moe::String, "what storage engine to use") - .setDefault(optionenvironment::Value("mobile")); - -#ifdef _WIN32 - boost::filesystem::path currentPath = boost::filesystem::current_path(); - - std::string defaultPath = currentPath.root_name().string() + storageGlobalParams.kDefaultDbPath; - storage_options.addOptionChaining("storage.dbPath", - "dbpath", - optionenvironment::String, - std::string("directory for datafiles - defaults to ") + - storageGlobalParams.kDefaultDbPath + " which is " + - defaultPath + " based on the current working drive"); - -#else - storage_options.addOptionChaining("storage.dbPath", - "dbpath", - optionenvironment::String, - std::string("directory for datafiles - defaults to ") + - storageGlobalParams.kDefaultDbPath); - -#endif - - storage_options.addOptionChaining("storage.repairPath", - "repairpath", - optionenvironment::String, - "root directory for repair files - defaults to dbpath"); - - options->addSection(general_options).transitional_ignore(); - options->addSection(storage_options).transitional_ignore(); - - return Status::OK(); -} - -Status canonicalizeOptions(optionenvironment::Environment* params) { - - Status ret = canonicalizeServerOptions(params); - if (!ret.isOK()) { - return ret; - } - - return Status::OK(); -} - -Status storeOptions(const moe::Environment& params) { - if (params.count("storage.engine")) { - storageGlobalParams.engine = params["storage.engine"].as<std::string>(); - storageGlobalParams.engineSetByUser = true; - } - - if (params.count("storage.dbPath")) { - storageGlobalParams.dbpath = params["storage.dbPath"].as<string>(); - if (params.count("processManagement.fork") && storageGlobalParams.dbpath[0] != '/') { - // we need to change dbpath if we fork since we change - // cwd to "/" - // fork only exists on *nix - // so '/' is safe - storageGlobalParams.dbpath = serverGlobalParams.cwd + "/" + storageGlobalParams.dbpath; - } - } -#ifdef _WIN32 - if (storageGlobalParams.dbpath.size() > 1 && - storageGlobalParams.dbpath[storageGlobalParams.dbpath.size() - 1] == '/') { - // size() check is for the unlikely possibility of --dbpath "/" - storageGlobalParams.dbpath = - storageGlobalParams.dbpath.erase(storageGlobalParams.dbpath.size() - 1); - } -#endif - - if (!params.count("net.port")) { - if (params.count("sharding.clusterRole")) { - std::string clusterRole = params["sharding.clusterRole"].as<std::string>(); - if (clusterRole == "configsvr") { - serverGlobalParams.port = ServerGlobalParams::ConfigServerPort; - } else if (clusterRole == "shardsvr") { - serverGlobalParams.port = ServerGlobalParams::ShardServerPort; - } else { - StringBuilder sb; - sb << "Bad value for sharding.clusterRole: " << clusterRole - << ". Supported modes are: (configsvr|shardsvr)"; - return Status(ErrorCodes::BadValue, sb.str()); - } - } - } else { - if (serverGlobalParams.port < 0 || serverGlobalParams.port > 65535) { - return Status(ErrorCodes::BadValue, "bad --port number"); - } - } - -#ifdef _WIN32 - // If dbPath is a default value, prepend with drive name so log entries are explicit - // We must resolve the dbpath before it stored in repairPath in the default case. - if (storageGlobalParams.dbpath == storageGlobalParams.kDefaultDbPath || - storageGlobalParams.dbpath == storageGlobalParams.kDefaultConfigDbPath) { - boost::filesystem::path currentPath = boost::filesystem::current_path(); - storageGlobalParams.dbpath = currentPath.root_name().string() + storageGlobalParams.dbpath; - } -#endif - - // needs to be after things like --configsvr parsing, thus here. - if (params.count("storage.repairPath")) { - storageGlobalParams.repairpath = params["storage.repairPath"].as<string>(); - if (!storageGlobalParams.repairpath.size()) { - return Status(ErrorCodes::BadValue, "repairpath is empty"); - } - - if (storageGlobalParams.dur && - !str::startsWith(storageGlobalParams.repairpath, storageGlobalParams.dbpath)) { - return Status(ErrorCodes::BadValue, - "You must use a --repairpath that is a subdirectory of --dbpath when " - "using journaling"); - } - } else { - storageGlobalParams.repairpath = storageGlobalParams.dbpath; - } - - return Status::OK(); -} - -} // namespace embedded -} // namespace mongo diff --git a/src/mongo/client/embedded/embedded_options.h b/src/mongo/client/embedded/embedded_options.h deleted file mode 100644 index 126a4da6a25..00000000000 --- a/src/mongo/client/embedded/embedded_options.h +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (C) 2018 MongoDB Inc. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * - * As a special exception, the copyright holders give permission to link the - * code of portions of this program with the OpenSSL library under certain - * conditions as described in each individual source file and distribute - * linked combinations including the program with the OpenSSL library. You - * must comply with the GNU Affero General Public License in all respects for - * all of the code used other than as permitted herein. If you modify file(s) - * with this exception, you may extend this exception to your version of the - * file(s), but you are not obligated to do so. If you do not wish to do so, - * delete this exception statement from your version. If you delete this - * exception statement from all source files in the program, then also delete - * it in the license file. - */ - -#pragma once - -#include "mongo/base/status.h" -#include "mongo/util/options_parser/environment.h" -#include "mongo/util/options_parser/option_section.h" - -namespace mongo { -namespace embedded { - -Status addOptions(optionenvironment::OptionSection* options); - -/** - * Canonicalize options for the given environment. - * - * For example, the options "dur", "nodur", "journal", "nojournal", and - * "storage.journaling.enabled" should all be merged into "storage.journaling.enabled". - */ -Status canonicalizeOptions(optionenvironment::Environment* params); - -Status storeOptions(const optionenvironment::Environment& params); -} // namespace embedded -} // namespace mongo diff --git a/src/mongo/client/embedded/embedded_options_init.cpp b/src/mongo/client/embedded/embedded_options_init.cpp deleted file mode 100644 index 2e838ab4668..00000000000 --- a/src/mongo/client/embedded/embedded_options_init.cpp +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (C) 2018 MongoDB Inc. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * - * As a special exception, the copyright holders give permission to link the - * code of portions of this program with the OpenSSL library under certain - * conditions as described in each individual source file and distribute - * linked combinations including the program with the OpenSSL library. You - * must comply with the GNU Affero General Public License in all respects for - * all of the code used other than as permitted herein. If you modify file(s) - * with this exception, you may extend this exception to your version of the - * file(s), but you are not obligated to do so. If you do not wish to do so, - * delete this exception statement from your version. If you delete this - * exception statement from all source files in the program, then also delete - * it in the license file. - */ - -#include "mongo/client/embedded/embedded_options.h" - -#include "mongo/util/options_parser/startup_option_init.h" -#include "mongo/util/options_parser/startup_options.h" - -namespace mongo { -namespace embedded { - -MONGO_GENERAL_STARTUP_OPTIONS_REGISTER(EmbeddedOptions)(InitializerContext* context) { - return addOptions(&optionenvironment::startupOptions); -} - -MONGO_INITIALIZER_GENERAL(EmbeddedOptions, - ("BeginStartupOptionValidation", "AllFailPointsRegistered"), - ("EndStartupOptionValidation")) -(InitializerContext* context) { - // Run validation, but tell the Environment that we don't want it to be set as "valid", - // since we may be making it invalid in the canonicalization process. - Status ret = optionenvironment::startupOptionsParsed.validate(false); - if (!ret.isOK()) { - return ret; - } - ret = canonicalizeOptions(&optionenvironment::startupOptionsParsed); - if (!ret.isOK()) { - return ret; - } - ret = optionenvironment::startupOptionsParsed.validate(); - if (!ret.isOK()) { - return ret; - } - return Status::OK(); -} - -MONGO_INITIALIZER_GENERAL(EmbeddedOptions_Store, - ("BeginStartupOptionStorage"), - ("EndStartupOptionStorage")) -(InitializerContext* context) { - return storeOptions(optionenvironment::startupOptionsParsed); -} - -} // namespace embedded -} // namespace mongo diff --git a/src/mongo/client/embedded/embedded_options_parser_init.cpp b/src/mongo/client/embedded/embedded_options_parser_init.cpp deleted file mode 100644 index 1416556828a..00000000000 --- a/src/mongo/client/embedded/embedded_options_parser_init.cpp +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Copyright (C) 2018 MongoDB Inc. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * - * As a special exception, the copyright holders give permission to link the - * code of portions of this program with the OpenSSL library under certain - * conditions as described in each individual source file and distribute - * linked combinations including the program with the OpenSSL library. You - * must comply with the GNU Affero General Public License in all respects for - * all of the code used other than as permitted herein. If you modify file(s) - * with this exception, you may extend this exception to your version of the - * file(s), but you are not obligated to do so. If you do not wish to do so, - * delete this exception statement from your version. If you delete this - * exception statement from all source files in the program, then also delete - * it in the license file. - */ - -#include "mongo/util/options_parser/startup_options.h" - -#include <iostream> - -#include "mongo/util/exit_code.h" -#include "mongo/util/options_parser/option_description.h" -#include "mongo/util/options_parser/option_section.h" -#include "mongo/util/options_parser/options_parser.h" -#include "mongo/util/options_parser/startup_option_init.h" -#include "mongo/util/quick_exit.h" - -namespace mongo { -namespace optionenvironment { - -MONGO_STARTUP_OPTIONS_PARSE(StartupOptions)(InitializerContext* context) { - // Embedded uses a YAML config passed in argv to reuse the existing interface, extract it from - // the first element otherwise use empty string. - std::string config = !context->args().empty() ? context->args()[0] : ""; - - OptionsParser parser; - Status ret = - parser.runConfigFile(startupOptions, config, context->env(), &startupOptionsParsed); - uassertStatusOKWithContext(ret, "Options parsing failed."); - - return Status::OK(); -} - -} // namespace optionenvironment -} // namespace mongo diff --git a/src/mongo/client/embedded/embedded_transport_layer.cpp b/src/mongo/client/embedded/embedded_transport_layer.cpp deleted file mode 100644 index 3e662efb62b..00000000000 --- a/src/mongo/client/embedded/embedded_transport_layer.cpp +++ /dev/null @@ -1,274 +0,0 @@ -/** - * Copyright (C) 2017 MongoDB Inc. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * - * As a special exception, the copyright holders give permission to link the - * code of portions of this program with the OpenSSL library under certain - * conditions as described in each individual source file and distribute - * linked combinations including the program with the OpenSSL library. You - * must comply with the GNU Affero General Public License in all respects - * for all of the code used other than as permitted herein. If you modify - * file(s) with this exception, you may extend this exception to your - * version of the file(s), but you are not obligated to do so. If you do not - * wish to do so, delete this exception statement from your version. If you - * delete this exception statement from all source files in the program, - * then also delete it in the license file. - */ - -#include "mongo/client/embedded/embedded_transport_layer.h" - -#include <cstdlib> -#include <deque> -#include <iostream> -#include <iterator> -#include <memory> -#include <string> - -#include "mongo/base/data_range.h" -#include "mongo/base/data_range_cursor.h" -#include "mongo/client/embedded/libmongodbcapi.h" -#include "mongo/util/assert_util.h" -#include "mongo/util/shared_buffer.h" - -enum RPCState { WaitingForMessageLength, WaitingForMessageContent, HaveOutput }; - -struct FreeDeleter { - void operator()(void* x) { - free(x); - } -}; - -struct mongoc_stream_embedded_t : mongoc_stream_t { - libmongodbcapi_client* clientHandle; - mongo::DataRangeCursor inputBuf = mongo::DataRangeCursor(nullptr, nullptr); - std::unique_ptr<char, FreeDeleter> hiddenBuf; - mongo::ConstDataRangeCursor outputBuf = mongo::ConstDataRangeCursor(nullptr, nullptr); - - void* libmongo_output; - size_t libmongo_output_size; - // If this is 0, we have recieved a full message and expect another header - u_long input_length_to_go; - RPCState state; -}; - -namespace { - -struct FreeAndDestroy { - void operator()(mongoc_stream_t* x) { - auto stream = static_cast<mongoc_stream_embedded_t*>(x); - libmongodbcapi_client_destroy(stream->clientHandle, nullptr); - stream->~mongoc_stream_embedded_t(); - free(stream); - } -}; -extern "C" void mongoc_stream_embedded_destroy(mongoc_stream_t* s) try { - std::unique_ptr<mongoc_stream_t, FreeAndDestroy> stream(s); -} catch (...) { - errno = EBADMSG; -} - - -extern "C" ssize_t mongoc_stream_embedded_writev(mongoc_stream_t* s, - mongoc_iovec_t* iov, - size_t iovcnt, - int32_t timeout_msec) try { - auto stream = static_cast<mongoc_stream_embedded_t*>(s); - invariant(stream->state == RPCState::WaitingForMessageContent || - stream->state == RPCState::WaitingForMessageLength); - - u_long already_read = 0; - for (size_t i = 0; i < iovcnt; i++) { - char* current_loc = static_cast<char*>(iov[i].iov_base); - u_long remaining_iov = iov[i].iov_len; - - // do we need a new message? - if (stream->state == RPCState::WaitingForMessageLength) { - - invariant(remaining_iov >= 4); - - // message length is the first four bytes - // Should use dataview from mongo server - stream->input_length_to_go = - mongo::ConstDataView(current_loc).read<mongo::LittleEndian<int32_t>>(); - // stream->hiddenBuf = (char*)malloc(stream->input_length_to_go); - stream->hiddenBuf = - std::unique_ptr<char, FreeDeleter>((char*)malloc(stream->input_length_to_go)); - stream->inputBuf = mongo::DataRangeCursor( - stream->hiddenBuf.get(), stream->hiddenBuf.get() + stream->input_length_to_go); - auto writeOK = - stream->inputBuf.writeAndAdvance(mongo::DataRange(current_loc, current_loc + 4)); - invariant(writeOK.isOK()); - current_loc += 4; - remaining_iov -= 4; - stream->input_length_to_go -= 4; - already_read += 4; - stream->state = RPCState::WaitingForMessageContent; - } - - // if there is no more message after reading length, we're done - if (remaining_iov <= 0) - continue; - - // copy message length into buffer - // pipelining is not allowed, so remaining_iov must be less than input_length_to_go - invariant(stream->input_length_to_go >= remaining_iov); - auto writeOK = stream->inputBuf.writeAndAdvance( - mongo::DataRange(current_loc, current_loc + remaining_iov)); - invariant(writeOK.isOK()); - // cleanup number values to reflect the copy - stream->input_length_to_go -= remaining_iov; - already_read += remaining_iov; - remaining_iov = 0; - - // if we found a complete message, send it - if (stream->input_length_to_go == 0) { - auto input_len = (size_t)(stream->inputBuf.data() - stream->hiddenBuf.get()); - int retVal = libmongodbcapi_client_invoke(stream->clientHandle, - stream->hiddenBuf.get(), - input_len, - &(stream->libmongo_output), - &(stream->libmongo_output_size), - nullptr); - if (retVal != LIBMONGODB_CAPI_SUCCESS) { - return -1; - } - - // We will allocate a new one when we read in the next message length - stream->hiddenBuf.reset(); - // and then write the output to our output buffer - auto start = static_cast<char*>(stream->libmongo_output); - auto end = (static_cast<char*>(stream->libmongo_output)) + stream->libmongo_output_size; - stream->outputBuf = mongo::ConstDataRangeCursor(start, end); - stream->state = RPCState::HaveOutput; - } - } - - return already_read; -} catch (...) { - errno = EBADMSG; - return 0; // not guarenteeing anything was written -} -extern "C" ssize_t mongoc_stream_embedded_readv(mongoc_stream_t* s, - mongoc_iovec_t* iov, - size_t iovcnt, - size_t min_bytes, - int32_t timeout_msec) try { - size_t bytes_read = 0; - auto stream = static_cast<mongoc_stream_embedded_t*>(s); - invariant(stream->state == RPCState::HaveOutput); - for (size_t i = 0; i < iovcnt && stream->outputBuf.length() > 0; i++) { - - // for each vector, fill the vector if we are able - size_t bytes_to_copy = std::min(iov[i].iov_len, stream->outputBuf.length()); - memcpy(iov[i].iov_base, stream->outputBuf.data(), bytes_to_copy); - auto x = stream->outputBuf.advance(bytes_to_copy); - invariant(x.isOK()); - bytes_read += bytes_to_copy; - } - stream->state = - stream->outputBuf.length() == 0 ? RPCState::WaitingForMessageLength : RPCState::HaveOutput; - return bytes_read; -} catch (...) { - errno = EBADMSG; - return 0; // not guarenteeing anything was read -} - - -extern "C" int mongoc_stream_embedded_close(mongoc_stream_t* s) { - return 0; -} - -extern "C" ssize_t mongoc_stream_embedded_poll(mongoc_stream_poll_t* s, - size_t array_length, - int32_t timeout_msec) try { - for (size_t i = 0; i < array_length; i++) { - s[i].revents = s[i].events & (POLLIN | POLLOUT); - } - return array_length; -} catch (...) { - errno = EBADMSG; - return -1; -} - -extern "C" bool mongoc_stream_embedded_check_closed(mongoc_stream_t* s) noexcept { - return false; -} - -extern "C" mongoc_stream_t* embedded_stream_initiator(const mongoc_uri_t* uri, - const mongoc_host_list_t* host, - void* user_data, - bson_error_t* error) try { - std::unique_ptr<unsigned char, FreeDeleter> stream_buf( - static_cast<unsigned char*>(bson_malloc0(sizeof(mongoc_stream_embedded_t)))); - if (!stream_buf) { - errno = ENOMEM; - return nullptr; - } - // Create the stream - std::unique_ptr<mongoc_stream_embedded_t, FreeAndDestroy> stream( - new (stream_buf.get()) mongoc_stream_embedded_t()); - stream_buf.release(); // This must be here so we don't have double ownership - stream->state = RPCState::WaitingForMessageLength; - // Set up connections to database - stream->clientHandle = - libmongodbcapi_client_create(static_cast<libmongodbcapi_instance*>(user_data), nullptr); - - // Connect the functions to the stream - // type is not relevant for us. Has to be set for the C Driver, but it has to do with picking - // how to communicate over the networ - stream->type = 1000; - stream->poll = mongoc_stream_embedded_poll; - stream->close = mongoc_stream_embedded_close; - stream->readv = mongoc_stream_embedded_readv; - stream->writev = mongoc_stream_embedded_writev; - stream->destroy = mongoc_stream_embedded_destroy; - stream->check_closed = mongoc_stream_embedded_check_closed; - return stream.release(); -} catch (...) { - errno = EBADMSG; - return nullptr; -} - -} // namespace - -struct ClientDeleter { - void operator()(mongoc_client_t* x) { - mongoc_client_destroy(x); - } -}; - -extern "C" mongoc_client_t* embedded_mongoc_client_new(libmongodbcapi_instance* db) try { - if (!db) { - errno = EINVAL; - return nullptr; - } - std::unique_ptr<mongoc_client_t, ClientDeleter> client(mongoc_client_new(NULL)); - mongoc_client_set_stream_initiator(client.get(), embedded_stream_initiator, db); - return client.release(); -} catch (const std::out_of_range& c) { - errno = EACCES; - return nullptr; -} catch (const std::overflow_error& c) { - errno = EOVERFLOW; - return nullptr; -} catch (const std::underflow_error& c) { - errno = ERANGE; - return nullptr; -} catch (const std::invalid_argument& c) { - errno = EINVAL; - return nullptr; -} catch (...) { - errno = EBADMSG; - return nullptr; -} diff --git a/src/mongo/client/embedded/embedded_transport_layer.h b/src/mongo/client/embedded/embedded_transport_layer.h deleted file mode 100644 index 96c60fe1937..00000000000 --- a/src/mongo/client/embedded/embedded_transport_layer.h +++ /dev/null @@ -1,47 +0,0 @@ -/** - * Copyright (C) 2017 MongoDB Inc. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * - * As a special exception, the copyright holders give permission to link the - * code of portions of this program with the OpenSSL library under certain - * conditions as described in each individual source file and distribute - * linked combinations including the program with the OpenSSL library. You - * must comply with the GNU Affero General Public License in all respects - * for all of the code used other than as permitted herein. If you modify - * file(s) with this exception, you may extend this exception to your - * version of the file(s), but you are not obligated to do so. If you do not - * wish to do so, delete this exception statement from your version. If you - * delete this exception statement from all source files in the program, - * then also delete it in the license file. - */ - -#include <bson.h> -#include <mongoc.h> - -#ifdef __cplusplus -extern "C" { -#endif - -struct libmongodbcapi_instance; - -/** - * Creates a client with the correct stream intiator set - * @param db must be a valid db handle created by libmongodbcapi - * @returns a mongoc client or `NULL` on error - */ -mongoc_client_t* embedded_mongoc_client_new(libmongodbcapi_instance* db); - -#ifdef __cplusplus -} // extern "C" -#endif diff --git a/src/mongo/client/embedded/embedded_transport_layer_test.cpp b/src/mongo/client/embedded/embedded_transport_layer_test.cpp deleted file mode 100644 index a256cb75f32..00000000000 --- a/src/mongo/client/embedded/embedded_transport_layer_test.cpp +++ /dev/null @@ -1,226 +0,0 @@ -/** - * Copyright (C) 2017 MongoDB Inc. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * - * As a special exception, the copyright holders give permission to link the - * code of portions of this program with the OpenSSL library under certain - * conditions as described in each individual source file and distribute - * linked combinations including the program with the OpenSSL library. You - * must comply with the GNU Affero General Public License in all respects for - * all of the code used other than as permitted herein. If you modify file(s) - * with this exception, you may extend this exception to your version of the - * file(s), but you are not obligated to do so. If you do not wish to do so, - * delete this exception statement from your version. If you delete this - * exception statement from all source files in the program, then also delete - * it in the license file. - */ - -#include "mongo/client/embedded/embedded_transport_layer.h" - -#include <mongoc.h> -#include <set> -#include <yaml-cpp/yaml.h> - -#include "mongo/client/embedded/functions_for_test.h" -#include "mongo/client/embedded/libmongodbcapi.h" -#include "mongo/db/server_options.h" -#include "mongo/stdx/memory.h" -#include "mongo/unittest/temp_dir.h" -#include "mongo/unittest/unittest.h" -#include "mongo/util/options_parser/environment.h" -#include "mongo/util/options_parser/option_section.h" -#include "mongo/util/options_parser/options_parser.h" -#include "mongo/util/quick_exit.h" -#include "mongo/util/signal_handlers_synchronous.h" - -namespace moe = mongo::optionenvironment; - -libmongodbcapi_lib* global_lib_handle; - -namespace { - -std::unique_ptr<mongo::unittest::TempDir> globalTempDir; - -class MongodbEmbeddedTransportLayerTest : public mongo::unittest::Test { -protected: - void setUp() { - if (!globalTempDir) { - globalTempDir = std::make_unique<mongo::unittest::TempDir>("embedded_mongo"); - } - - YAML::Emitter yaml; - yaml << YAML::BeginMap; - - yaml << YAML::Key << "storage"; - yaml << YAML::Value << YAML::BeginMap; - yaml << YAML::Key << "dbPath"; - yaml << YAML::Value << globalTempDir->path(); - yaml << YAML::EndMap; // storage - - yaml << YAML::EndMap; - - db_handle = libmongodbcapi_instance_create(global_lib_handle, yaml.c_str(), nullptr); - - cd_client = embedded_mongoc_client_new(db_handle); - mongoc_client_set_error_api(cd_client, 2); - cd_db = mongoc_client_get_database(cd_client, "test"); - cd_collection = mongoc_database_get_collection(cd_db, (const char*)"things"); - } - - void tearDown() { - mongoc_collection_drop(cd_collection, nullptr); - if (cd_collection) { - mongoc_collection_destroy(cd_collection); - } - - if (cd_db) { - mongoc_database_destroy(cd_db); - } - - if (cd_client) { - mongoc_client_destroy(cd_client); - } - - libmongodbcapi_instance_destroy(db_handle, nullptr); - } - - libmongodbcapi_instance* getDBHandle() { - return db_handle; - } - - mongoc_database_t* getDB() { - return cd_db; - } - mongoc_client_t* getClient() { - return cd_client; - } - mongoc_collection_t* getCollection() { - return cd_collection; - } - - -private: - libmongodbcapi_instance* db_handle; - mongoc_database_t* cd_db; - mongoc_client_t* cd_client; - mongoc_collection_t* cd_collection; -}; - -TEST_F(MongodbEmbeddedTransportLayerTest, CreateAndDestroyDB) { - // Test the setUp() and tearDown() test fixtures -} -TEST_F(MongodbEmbeddedTransportLayerTest, InsertAndExplain) { - auto client = getClient(); - auto collection = getCollection(); - ASSERT(client); - - - ASSERT(mongo::embeddedTest::insert_data(collection)); - - ASSERT(mongo::embeddedTest::explain(collection)); -} -TEST_F(MongodbEmbeddedTransportLayerTest, InsertAndCount) { - auto client = getClient(); - auto collection = getCollection(); - ASSERT(client); - ASSERT(collection); - bson_error_t err; - int64_t count; - ASSERT(mongo::embeddedTest::insert_data(collection)); - count = mongoc_collection_count(collection, MONGOC_QUERY_NONE, nullptr, 0, 0, NULL, &err); - ASSERT(count == 4); -} -TEST_F(MongodbEmbeddedTransportLayerTest, InsertAndDelete) { - auto client = getClient(); - auto collection = getCollection(); - ASSERT(client); - ASSERT(collection); - bson_error_t err; - bson_oid_t oid; - int64_t count; - // done with setup - - auto doc = bson_new(); - bson_oid_init(&oid, NULL); - BSON_APPEND_OID(doc, "_id", &oid); - BSON_APPEND_UTF8(doc, "hello", "world"); - ASSERT(mongoc_collection_insert(collection, MONGOC_INSERT_NONE, doc, NULL, &err)); - count = mongoc_collection_count(collection, MONGOC_QUERY_NONE, nullptr, 0, 0, NULL, &err); - ASSERT(1 == count); - bson_destroy(doc); - doc = bson_new(); - BSON_APPEND_OID(doc, "_id", &oid); - ASSERT(mongoc_collection_remove(collection, MONGOC_REMOVE_SINGLE_REMOVE, doc, NULL, &err)); - ASSERT(0 == mongoc_collection_count(collection, MONGOC_QUERY_NONE, nullptr, 0, 0, NULL, &err)); - bson_destroy(doc); -} - -struct StatusDestroy { - void operator()(libmongodbcapi_status* const ptr) { - if (!ptr) { - libmongodbcapi_status_destroy(ptr); - } - } -}; -using StatusPtr = std::unique_ptr<libmongodbcapi_status, StatusDestroy>; -} // namespace - -// Define main function as an entry to these tests. -// These test functions cannot use the main() defined for unittests because they -// call runGlobalInitializers(). The embedded C API calls mongoDbMain() which -// calls runGlobalInitializers(). -int main(int argc, char** argv, char** envp) { - - moe::OptionsParser parser; - moe::Environment environment; - moe::OptionSection options; - std::map<std::string, std::string> env; - - options.addOptionChaining( - "tempPath", "tempPath", moe::String, "directory to place mongo::TempDir subdirectories"); - std::vector<std::string> argVector(argv, argv + argc); - mongo::Status ret = parser.run(options, argVector, env, &environment); - if (!ret.isOK()) { - std::cerr << options.helpString(); - return EXIT_FAILURE; - } - if (environment.count("tempPath")) { - ::mongo::unittest::TempDir::setTempPath(environment["tempPath"].as<std::string>()); - } - - ::mongo::clearSignalMask(); - ::mongo::setupSynchronousSignalHandlers(); - ::mongo::serverGlobalParams.noUnixSocket = true; - ::mongo::unittest::setupTestLogger(); - - StatusPtr status(libmongodbcapi_status_create()); - mongoc_init(); - - global_lib_handle = libmongodbcapi_lib_init(nullptr, status.get()); - if (global_lib_handle == nullptr) { - std::cerr << "Error: " << libmongodbcapi_status_get_explanation(status.get()); - return EXIT_FAILURE; - } - - auto result = ::mongo::unittest::Suite::run(std::vector<std::string>(), "", 1); - - if (libmongodbcapi_lib_fini(global_lib_handle, status.get()) != LIBMONGODB_CAPI_SUCCESS) { - std::cerr << "Error: " << libmongodbcapi_status_get_explanation(status.get()); - return EXIT_FAILURE; - } - - mongoc_cleanup(); - globalTempDir.reset(); - mongo::quickExit(result); -} diff --git a/src/mongo/client/embedded/functions_for_test.cpp b/src/mongo/client/embedded/functions_for_test.cpp deleted file mode 100644 index c0c14b2e241..00000000000 --- a/src/mongo/client/embedded/functions_for_test.cpp +++ /dev/null @@ -1,245 +0,0 @@ -/** - * Copyright (C) 2017 MongoDB Inc. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * - * As a special exception, the copyright holders give permission to link the - * code of portions of this program with the OpenSSL library under certain - * conditions as described in each individual source file and distribute - * linked combinations including the program with the OpenSSL library. You - * must comply with the GNU Affero General Public License in all respects - * for all of the code used other than as permitted herein. If you modify - * file(s) with this exception, you may extend this exception to your - * version of the file(s), but you are not obligated to do so. If you do not - * wish to do so, delete this exception statement from your version. If you - * delete this exception statement from all source files in the program, - * then also delete it in the license file. - */ - -#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kStorage - -#include "mongo/client/embedded/functions_for_test.h" - -#include <mongoc.h> -#include <stdio.h> - -#include "mongo/client/embedded/embedded_transport_layer.h" -#include "mongo/util/log.h" - -/** - * WARNING: This function is an example lifted directly from the C driver - * for use testing the connection to the c driver. It is written in C, - * and should not be used for anything besides basic testing. - */ -bool mongo::embeddedTest::insert_data(mongoc_collection_t* collection) { - mongoc_bulk_operation_t* bulk; - const int ndocs = 4; - bson_t* docs[ndocs]; - - bulk = mongoc_collection_create_bulk_operation(collection, true, NULL); - - docs[0] = BCON_NEW("x", BCON_DOUBLE(1.0), "tags", "[", "dog", "cat", "]"); - docs[1] = BCON_NEW("x", BCON_DOUBLE(2.0), "tags", "[", "cat", "]"); - docs[2] = BCON_NEW("x", BCON_DOUBLE(2.0), "tags", "[", "mouse", "cat", "dog", "]"); - docs[3] = BCON_NEW("x", BCON_DOUBLE(3.0), "tags", "[", "]"); - - for (int i = 0; i < ndocs; i++) { - mongoc_bulk_operation_insert(bulk, docs[i]); - bson_destroy(docs[i]); - docs[i] = NULL; - } - - bson_error_t error; - bool ret = mongoc_bulk_operation_execute(bulk, NULL, &error); - - if (!ret) { - log() << "Error inserting data: " << error.message; - } - - mongoc_bulk_operation_destroy(bulk); - return ret; -} - -/** - * WARNING: This function is an example lifted directly from the C driver - * for use testing the connection to the c driver. It is written in C, - * and should not be used for anything besides basic testing. - */ -bool copydb(mongoc_client_t* client, const char* other_host_and_port) { - mongoc_database_t* admindb; - bson_t* command; - bson_t reply; - bson_error_t error; - bool res; - - BSON_ASSERT(other_host_and_port); - /* Must do this from the admin db */ - admindb = mongoc_client_get_database(client, "admin"); - - command = BCON_NEW("copydb", - BCON_INT32(1), - "fromdb", - BCON_UTF8("test"), - "todb", - BCON_UTF8("test2"), - - /* If you want from a different host */ - "fromhost", - BCON_UTF8(other_host_and_port)); - res = mongoc_database_command_simple(admindb, command, NULL, &reply, &error); - if (!res) { - mongo::log() << "Error with copydb: " << error.message; - goto copy_cleanup; - } - - -copy_cleanup: - bson_destroy(&reply); - bson_destroy(command); - mongoc_database_destroy(admindb); - - return res; -} -/** - * WARNING: This function is an example lifted directly from the C driver - * for use testing the connection to the c driver. It is written in C, - * and should not be used for anything besides basic testing. - */ -bool clone_collection(mongoc_database_t* database, const char* other_host_and_port) { - bson_t* command; - bson_t reply; - bson_error_t error; - bool res; - - BSON_ASSERT(other_host_and_port); - command = BCON_NEW("cloneCollection", - BCON_UTF8("test.remoteThings"), - "from", - BCON_UTF8(other_host_and_port), - "query", - "{", - "x", - BCON_INT32(1), - "}"); - res = mongoc_database_command_simple(database, command, NULL, &reply, &error); - if (!res) { - mongo::log() << "Error with clone: " << error.message; - goto clone_cleanup; - } - - -clone_cleanup: - bson_destroy(&reply); - bson_destroy(command); - - return res; -} -/** - * WARNING: This function is an example lifted directly from the C driver - * for use testing the connection to the c driver. It is written in C, - * and should not be used for anything besides basic testing. - */ -bool mongo::embeddedTest::explain(mongoc_collection_t* collection) { - - bson_t* command; - bson_t reply; - bson_error_t error; - bool res; - - command = BCON_NEW("explain", - "{", - "find", - BCON_UTF8((const char*)"things"), - "filter", - "{", - "x", - BCON_INT32(1), - "}", - "}"); - res = mongoc_collection_command_simple(collection, command, NULL, &reply, &error); - if (!res) { - log() << "Error with explain: " << error.message; - goto explain_cleanup; - } - - -explain_cleanup: - bson_destroy(&reply); - bson_destroy(command); - return res; -} -/** - * WARNING: This function is an example lifted directly from the C driver - * for use testing the connection to the c driver. It is written in C, - * and should not be used for anything besides basic testing. - */ -int mongo::embeddedTest::run_c_driver_all() { - mongoc_database_t* database = NULL; - mongoc_client_t* client = NULL; - mongoc_collection_t* collection = NULL; - char* host_and_port = NULL; - int res = 0; - char* other_host_and_port = NULL; - - - client = mongoc_client_new(NULL); - - if (!client) { - log() << " Invalid client "; - res = 2; - goto cleanup; - } - - mongoc_client_set_error_api(client, 2); - database = mongoc_client_get_database(client, "test"); - collection = mongoc_database_get_collection(database, (const char*)"things"); - - if (!mongo::embeddedTest::insert_data(collection)) { - res = 3; - goto cleanup; - } - - if (!mongo::embeddedTest::explain(collection)) { - res = 4; - goto cleanup; - } - - if (other_host_and_port) { - if (!copydb(client, other_host_and_port)) { - res = 5; - goto cleanup; - } - - if (!clone_collection(database, other_host_and_port)) { - res = 6; - goto cleanup; - } - } - -cleanup: - if (collection) { - mongoc_collection_destroy(collection); - } - - if (database) { - mongoc_database_destroy(database); - } - - if (client) { - mongoc_client_destroy(client); - } - - bson_free(host_and_port); - mongoc_cleanup(); - return res; -} diff --git a/src/mongo/client/embedded/functions_for_test.h b/src/mongo/client/embedded/functions_for_test.h deleted file mode 100644 index b5f91eb1d23..00000000000 --- a/src/mongo/client/embedded/functions_for_test.h +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Copyright (C) 2017 MongoDB Inc. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * - * As a special exception, the copyright holders give permission to link the - * code of portions of this program with the OpenSSL library under certain - * conditions as described in each individual source file and distribute - * linked combinations including the program with the OpenSSL library. You - * must comply with the GNU Affero General Public License in all respects - * for all of the code used other than as permitted herein. If you modify - * file(s) with this exception, you may extend this exception to your - * version of the file(s), but you are not obligated to do so. If you do not - * wish to do so, delete this exception statement from your version. If you - * delete this exception statement from all source files in the program, - * then also delete it in the license file. - */ - -#pragma once - -#include <mongoc.h> - -namespace mongo { - -namespace embeddedTest { - -bool explain(mongoc_collection_t* collection); - -bool insert_data(mongoc_collection_t* collection); - -int run_c_driver_all(); - -} // namespace embeddedTest - -} // namespace mongo diff --git a/src/mongo/client/embedded/index_create_impl_embedded.cpp b/src/mongo/client/embedded/index_create_impl_embedded.cpp deleted file mode 100644 index a58560f3945..00000000000 --- a/src/mongo/client/embedded/index_create_impl_embedded.cpp +++ /dev/null @@ -1,55 +0,0 @@ -/** - * Copyright (C) 2018 MongoDB Inc. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * - * As a special exception, the copyright holders give permission to link the - * code of portions of this program with the OpenSSL library under certain - * conditions as described in each individual source file and distribute - * linked combinations including the program with the OpenSSL library. You - * must comply with the GNU Affero General Public License in all respects for - * all of the code used other than as permitted herein. If you modify file(s) - * with this exception, you may extend this exception to your version of the - * file(s), but you are not obligated to do so. If you do not wish to do so, - * delete this exception statement from your version. If you delete this - * exception statement from all source files in the program, then also delete - * it in the license file. - */ - -#include "mongo/platform/basic.h" - -#include "mongo/base/init.h" -#include "mongo/db/catalog/index_create_impl.h" - -namespace mongo { -namespace { - -class MultiIndexBlockImplEmbedded : public MultiIndexBlockImpl { - using MultiIndexBlockImpl::MultiIndexBlockImpl; - - bool initBackgroundIndexFromSpec(const BSONObj& spec) const override { - uassert(ErrorCodes::IllegalOperation, - "Background index building not supported on embedded"_sd, - !spec["background"].trueValue()); - return false; - } -}; -} // namespace - -MONGO_REGISTER_SHIM(MultiIndexBlock::makeImpl) -(OperationContext* const opCtx, Collection* const collection, PrivateTo<MultiIndexBlock>) - ->std::unique_ptr<MultiIndexBlock::Impl> { - return std::make_unique<MultiIndexBlockImplEmbedded>(opCtx, collection); -} - -} // namespace mongo diff --git a/src/mongo/client/embedded/libmongodbcapi.cpp b/src/mongo/client/embedded/libmongodbcapi.cpp deleted file mode 100644 index 3153aa88b65..00000000000 --- a/src/mongo/client/embedded/libmongodbcapi.cpp +++ /dev/null @@ -1,638 +0,0 @@ -/** - * Copyright (C) 2017 MongoDB Inc. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * - * As a special exception, the copyright holders give permission to link the - * code of portions of this program with the OpenSSL library under certain - * conditions as described in each individual source file and distribute - * linked combinations including the program with the OpenSSL library. You - * must comply with the GNU Affero General Public License in all respects - * for all of the code used other than as permitted herein. If you modify - * file(s) with this exception, you may extend this exception to your - * version of the file(s), but you are not obligated to do so. If you do not - * wish to do so, delete this exception statement from your version. If you - * delete this exception statement from all source files in the program, - * then also delete it in the license file. - */ - -#include "mongo/client/embedded/libmongodbcapi.h" - -#include <cstring> -#include <exception> -#include <thread> -#include <unordered_map> -#include <vector> - -#include "mongo/client/embedded/embedded.h" -#include "mongo/client/embedded/embedded_log_appender.h" -#include "mongo/db/client.h" -#include "mongo/db/dbmain.h" -#include "mongo/db/service_context.h" -#include "mongo/logger/logger.h" -#include "mongo/logger/message_event_utf8_encoder.h" -#include "mongo/rpc/message.h" -#include "mongo/stdx/unordered_map.h" -#include "mongo/transport/service_entry_point.h" -#include "mongo/transport/transport_layer_mock.h" -#include "mongo/util/assert_util.h" -#include "mongo/util/scopeguard.h" -#include "mongo/util/shared_buffer.h" - -struct libmongodbcapi_status { - libmongodbcapi_status() noexcept = default; - libmongodbcapi_status(const libmongodbcapi_error e, const int ec, std::string w) - : error(e), exception_code(ec), what(std::move(w)) {} - - void clean() noexcept { - error = LIBMONGODB_CAPI_SUCCESS; - } - - libmongodbcapi_error error = LIBMONGODB_CAPI_SUCCESS; - int exception_code = 0; - std::string what; -}; - -namespace mongo { -namespace { -class MobileException : public std::exception { -public: - explicit MobileException(const libmongodbcapi_error code, std::string m) - : _mesg(std::move(m)), _code(code) {} - - libmongodbcapi_error mobileCode() const noexcept { - return this->_code; - } - - const char* what() const noexcept final { - return this->_mesg.c_str(); - } - -private: - std::string _mesg; - libmongodbcapi_error _code; -}; - -libmongodbcapi_status translateException() try { throw; } catch (const MobileException& ex) { - return {ex.mobileCode(), mongo::ErrorCodes::InternalError, ex.what()}; -} catch (const ExceptionFor<ErrorCodes::ReentrancyNotAllowed>& ex) { - return {LIBMONGODB_CAPI_ERROR_REENTRANCY_NOT_ALLOWED, ex.code(), ex.what()}; -} catch (const DBException& ex) { - return {LIBMONGODB_CAPI_ERROR_EXCEPTION, ex.code(), ex.what()}; -} catch (const std::bad_alloc& ex) { - return {LIBMONGODB_CAPI_ERROR_ENOMEM, mongo::ErrorCodes::InternalError, ex.what()}; -} catch (const std::exception& ex) { - return {LIBMONGODB_CAPI_ERROR_UNKNOWN, mongo::ErrorCodes::InternalError, ex.what()}; -} catch (...) { - return {LIBMONGODB_CAPI_ERROR_UNKNOWN, - mongo::ErrorCodes::InternalError, - "Unknown error encountered in performing requested libmongodbcapi operation"}; -} - -std::nullptr_t handleException(libmongodbcapi_status& status) noexcept { - try { - status = translateException(); - } catch (...) { - status.error = LIBMONGODB_CAPI_ERROR_IN_REPORTING_ERROR; - - try { - status.exception_code = -1; - - status.what.clear(); - - // Expected to be small enough to fit in the capacity that string always has. - const char severeErrorMessage[] = "Severe Error"; - - if (status.what.capacity() > sizeof(severeErrorMessage)) { - status.what = severeErrorMessage; - } - } catch (...) /* Ignore any errors at this point. */ - { - } - } - return nullptr; -} - -} // namespace -} // namespace mongo - -struct libmongodbcapi_lib { - ~libmongodbcapi_lib() { - invariant(this->databaseCount.load() == 0); - - if (this->logCallbackHandle) { - using mongo::logger::globalLogDomain; - globalLogDomain()->detachAppender(this->logCallbackHandle); - this->logCallbackHandle.reset(); - } - } - - libmongodbcapi_lib(const libmongodbcapi_lib&) = delete; - void operator=(const libmongodbcapi_lib) = delete; - - libmongodbcapi_lib() = default; - - mongo::AtomicWord<int> databaseCount; - - mongo::logger::ComponentMessageLogDomain::AppenderHandle logCallbackHandle; - - std::unique_ptr<libmongodbcapi_instance> onlyDB; -}; - -namespace mongo { -namespace { -struct ServiceContextDestructor { - void operator()(mongo::ServiceContext* const serviceContext) const noexcept { - ::mongo::embedded::shutdown(serviceContext); - } -}; - -using EmbeddedServiceContextPtr = std::unique_ptr<mongo::ServiceContext, ServiceContextDestructor>; -} // namespace -} // namespace mongo - -struct libmongodbcapi_instance { - ~libmongodbcapi_instance() { - invariant(this->clientCount.load() == 0); - this->parentLib->databaseCount.subtractAndFetch(1); - } - - libmongodbcapi_instance(const libmongodbcapi_instance&) = delete; - libmongodbcapi_instance& operator=(const libmongodbcapi_instance&) = delete; - - explicit libmongodbcapi_instance(libmongodbcapi_lib* const p, const char* const yaml_config) - : parentLib(p), - serviceContext(::mongo::embedded::initialize(yaml_config)), - // creating mock transport layer to be able to create sessions - transportLayer(std::make_unique<mongo::transport::TransportLayerMock>()) { - if (!this->serviceContext) { - throw ::mongo::MobileException{ - LIBMONGODB_CAPI_ERROR_DB_INITIALIZATION_FAILED, - "The MongoDB Embedded Library Failed to initialize the Service Context"}; - } - - this->parentLib->databaseCount.addAndFetch(1); - } - - libmongodbcapi_lib* parentLib; - mongo::AtomicWord<int> clientCount; - - mongo::EmbeddedServiceContextPtr serviceContext; - std::unique_ptr<mongo::transport::TransportLayerMock> transportLayer; -}; - -struct libmongodbcapi_client { - ~libmongodbcapi_client() { - this->parent_db->clientCount.subtractAndFetch(1); - } - - explicit libmongodbcapi_client(libmongodbcapi_instance* const db) - : parent_db(db), - client(db->serviceContext->makeClient("embedded", db->transportLayer->createSession())) { - this->parent_db->clientCount.addAndFetch(1); - } - - libmongodbcapi_client(const libmongodbcapi_client&) = delete; - libmongodbcapi_client& operator=(const libmongodbcapi_client&) = delete; - - libmongodbcapi_instance* const parent_db; - mongo::ServiceContext::UniqueClient client; - - std::vector<unsigned char> output; - mongo::DbResponse response; -}; - -namespace mongo { -namespace { - -std::unique_ptr<libmongodbcapi_lib> library; - -class ReentrancyGuard { -private: - thread_local static bool inLibrary; - -public: - explicit ReentrancyGuard() { - uassert(ErrorCodes::ReentrancyNotAllowed, - str::stream() << "Reentry into libmongodbcapi is not allowed", - !inLibrary); - inLibrary = true; - } - - ~ReentrancyGuard() { - inLibrary = false; - } - - ReentrancyGuard(ReentrancyGuard const&) = delete; - ReentrancyGuard& operator=(ReentrancyGuard const&) = delete; -}; - -thread_local bool ReentrancyGuard::inLibrary = false; - -void registerLogCallback(libmongodbcapi_lib* const lib, - const libmongodbcapi_log_callback logCallback, - void* const logUserData) { - using logger::globalLogDomain; - using logger::MessageEventEphemeral; - using logger::MessageEventUnadornedEncoder; - - lib->logCallbackHandle = globalLogDomain()->attachAppender( - std::make_unique<embedded::EmbeddedLogAppender<MessageEventEphemeral>>( - logCallback, logUserData, std::make_unique<MessageEventUnadornedEncoder>())); -} - -libmongodbcapi_lib* capi_lib_init(libmongodbcapi_init_params const* params, - libmongodbcapi_status& status) try { - if (library) { - throw MobileException{ - LIBMONGODB_CAPI_ERROR_LIBRARY_ALREADY_INITIALIZED, - "Cannot initialize the MongoDB Embedded Library when it is already initialized."}; - } - - auto lib = std::make_unique<libmongodbcapi_lib>(); - - // TODO(adam.martin): Fold all of this log initialization into the ctor of lib. - if (params) { - using logger::globalLogManager; - // The standard console log appender may or may not be installed here, depending if this is - // the first time we initialize the library or not. Make sure we handle both cases. - if (params->log_flags & LIBMONGODB_CAPI_LOG_STDOUT) { - if (!globalLogManager()->isDefaultConsoleAppenderAttached()) - globalLogManager()->reattachDefaultConsoleAppender(); - } else { - if (globalLogManager()->isDefaultConsoleAppenderAttached()) - globalLogManager()->detachDefaultConsoleAppender(); - } - - if ((params->log_flags & LIBMONGODB_CAPI_LOG_CALLBACK) && params->log_callback) { - registerLogCallback(lib.get(), params->log_callback, params->log_user_data); - } - } - - library = std::move(lib); - - return library.get(); -} catch (...) { - // Make sure that no actual logger is attached if library cannot be initialized. Also prevent - // exception leaking failures here. - []() noexcept { - using logger::globalLogManager; - if (globalLogManager()->isDefaultConsoleAppenderAttached()) - globalLogManager()->detachDefaultConsoleAppender(); - } - (); - throw; -} - -void capi_lib_fini(libmongodbcapi_lib* const lib, libmongodbcapi_status& status) { - if (!lib) { - throw MobileException{ - LIBMONGODB_CAPI_ERROR_INVALID_LIB_HANDLE, - "Cannot close a `NULL` pointer referencing a MongoDB Embedded Library Instance"}; - } - - if (!library) { - throw MobileException{ - LIBMONGODB_CAPI_ERROR_LIBRARY_NOT_INITIALIZED, - "Cannot close the MongoDB Embedded Library when it is not initialized"}; - } - - if (library.get() != lib) { - throw MobileException{LIBMONGODB_CAPI_ERROR_INVALID_LIB_HANDLE, - "Invalid MongoDB Embedded Library handle."}; - } - - // This check is not possible to 100% guarantee. It is a best effort. The documentation of - // this API says that the behavior of closing a `lib` with open handles is undefined, but may - // provide diagnostic errors in some circumstances. - if (lib->databaseCount.load() > 0) { - throw MobileException{ - LIBMONGODB_CAPI_ERROR_HAS_DB_HANDLES_OPEN, - "Cannot close the MongoDB Embedded Library when it has database handles still open."}; - } - - library = nullptr; -} - -libmongodbcapi_instance* instance_new(libmongodbcapi_lib* const lib, - const char* const yaml_config, - libmongodbcapi_status& status) { - if (!library) { - throw MobileException{LIBMONGODB_CAPI_ERROR_LIBRARY_NOT_INITIALIZED, - "Cannot create a new database handle when the MongoDB Embedded " - "Library is not yet initialized."}; - } - - if (library.get() != lib) { - throw MobileException{LIBMONGODB_CAPI_ERROR_INVALID_LIB_HANDLE, - "Cannot create a new database handle when the MongoDB Embedded " - "Library is not yet initialized."}; - } - - if (lib->onlyDB) { - throw MobileException{LIBMONGODB_CAPI_ERROR_DB_MAX_OPEN, - "The maximum number of permitted database handles for the MongoDB " - "Embedded Library have been opened."}; - } - - lib->onlyDB = std::make_unique<libmongodbcapi_instance>(lib, yaml_config); - - return lib->onlyDB.get(); -} - -void instance_destroy(libmongodbcapi_instance* const db, libmongodbcapi_status& status) { - if (!library) { - throw MobileException{LIBMONGODB_CAPI_ERROR_LIBRARY_NOT_INITIALIZED, - "Cannot destroy a database handle when the MongoDB Embedded Library " - "is not yet initialized."}; - } - - if (!db) { - throw MobileException{ - LIBMONGODB_CAPI_ERROR_INVALID_DB_HANDLE, - "Cannot close a `NULL` pointer referencing a MongoDB Embedded Database"}; - } - - if (db != library->onlyDB.get()) { - throw MobileException{ - LIBMONGODB_CAPI_ERROR_INVALID_DB_HANDLE, - "Cannot close the specified MongoDB Embedded Database, as it is not a valid instance."}; - } - - if (db->clientCount.load() > 0) { - throw MobileException{ - LIBMONGODB_CAPI_ERROR_DB_CLIENTS_OPEN, - "Cannot close a MongoDB Embedded Database instance while it has open clients"}; - } - - library->onlyDB = nullptr; -} - -libmongodbcapi_client* client_new(libmongodbcapi_instance* const db, - libmongodbcapi_status& status) { - if (!library) { - throw MobileException{LIBMONGODB_CAPI_ERROR_LIBRARY_NOT_INITIALIZED, - "Cannot create a new client handle when the MongoDB Embedded Library " - "is not yet initialized."}; - } - - if (!db) { - throw MobileException{LIBMONGODB_CAPI_ERROR_INVALID_DB_HANDLE, - "Cannot use a `NULL` pointer referencing a MongoDB Embedded Database " - "when creating a new client"}; - } - - if (db != library->onlyDB.get()) { - throw MobileException{LIBMONGODB_CAPI_ERROR_INVALID_DB_HANDLE, - "The specified MongoDB Embedded Database instance cannot be used to " - "create a new client because it is invalid."}; - } - - return new libmongodbcapi_client(db); -} - -void client_destroy(libmongodbcapi_client* const client, libmongodbcapi_status& status) { - if (!library) { - throw MobileException(LIBMONGODB_CAPI_ERROR_LIBRARY_NOT_INITIALIZED, - "Cannot destroy a database handle when the MongoDB Embedded Library " - "is not yet initialized."); - } - - if (!client) { - throw MobileException{ - LIBMONGODB_CAPI_ERROR_INVALID_CLIENT_HANDLE, - "Cannot destroy a `NULL` pointer referencing a MongoDB Embedded Database Client"}; - } - - delete client; -} - -class ClientGuard { - ClientGuard(const ClientGuard&) = delete; - void operator=(const ClientGuard&) = delete; - -public: - explicit ClientGuard(libmongodbcapi_client* const client) : _client(client) { - mongo::Client::setCurrent(std::move(client->client)); - } - - ~ClientGuard() { - _client->client = mongo::Client::releaseCurrent(); - } - -private: - libmongodbcapi_client* const _client; -}; - -void client_wire_protocol_rpc(libmongodbcapi_client* const client, - const void* input, - const size_t input_size, - void** const output, - size_t* const output_size, - libmongodbcapi_status& status) { - ClientGuard clientGuard(client); - - auto opCtx = cc().makeOperationContext(); - auto sep = client->parent_db->serviceContext->getServiceEntryPoint(); - - auto sb = SharedBuffer::allocate(input_size); - memcpy(sb.get(), input, input_size); - - Message msg(std::move(sb)); - - client->response = sep->handleRequest(opCtx.get(), msg); - - MsgData::View outMessage(client->response.response.buf()); - outMessage.setId(nextMessageId()); - outMessage.setResponseToMsgId(msg.header().getId()); - - // The results of the computations used to fill out-parameters need to be captured and processed - // before setting the output parameters themselves, in order to maintain the strong-guarantee - // part of the contract of this function. - auto outParams = - std::make_tuple(client->response.response.size(), client->response.response.buf()); - - // We force the output parameters to be set in a `noexcept` enabled way. If the operation - // itself - // is safely noexcept, we just run it, otherwise we force a `noexcept` over it to catch errors. - if (noexcept(std::tie(*output_size, *output) = std::move(outParams))) { - std::tie(*output_size, *output) = std::move(outParams); - } else { - // Assigning primitives in a tied tuple should be noexcept, so we force it to be so, for - // our purposes. This facilitates a runtime check should something WEIRD happen. - [ output, output_size, &outParams ]() noexcept { - std::tie(*output_size, *output) = std::move(outParams); - } - (); - } -} - -int capi_status_get_error(const libmongodbcapi_status* const status) noexcept { - invariant(status); - return status->error; -} - -const char* capi_status_get_what(const libmongodbcapi_status* const status) noexcept { - invariant(status); - return status->what.c_str(); -} - -int capi_status_get_code(const libmongodbcapi_status* const status) noexcept { - invariant(status); - return status->exception_code; -} - -template <typename Function, - typename ReturnType = - decltype(std::declval<Function>()(*std::declval<libmongodbcapi_status*>()))> -struct enterCXXImpl; - -template <typename Function> -struct enterCXXImpl<Function, void> { - template <typename Callable> - static int call(Callable&& function, libmongodbcapi_status& status) noexcept { - try { - ReentrancyGuard singleEntrant; - function(status); - } catch (...) { - handleException(status); - } - return status.error; - } -}; - - -template <typename Function, typename Pointer> -struct enterCXXImpl<Function, Pointer*> { - template <typename Callable> - static Pointer* call(Callable&& function, libmongodbcapi_status& status) noexcept try { - ReentrancyGuard singleEntrant; - return function(status); - } catch (...) { - return handleException(status); - } -}; -} // namespace -} // namespace mongo - -namespace { -struct StatusGuard { -private: - libmongodbcapi_status* status; - libmongodbcapi_status fallback; - -public: - explicit StatusGuard(libmongodbcapi_status* const statusPtr) noexcept : status(statusPtr) { - if (status) - status->clean(); - } - - libmongodbcapi_status& get() noexcept { - return status ? *status : fallback; - } - - const libmongodbcapi_status& get() const noexcept { - return status ? *status : fallback; - } - - operator libmongodbcapi_status&() & noexcept { - return this->get(); - } - operator libmongodbcapi_status&() && noexcept { - return this->get(); - } -}; - -template <typename Callable> -auto enterCXX(libmongodbcapi_status* const statusPtr, Callable&& c) noexcept - -> decltype(mongo::enterCXXImpl<Callable>::call(std::forward<Callable>(c), *statusPtr)) { - StatusGuard status(statusPtr); - return mongo::enterCXXImpl<Callable>::call(std::forward<Callable>(c), status); -} -} // namespace - -extern "C" { -libmongodbcapi_lib* libmongodbcapi_lib_init(const libmongodbcapi_init_params* const params, - libmongodbcapi_status* const statusPtr) { - return enterCXX(statusPtr, [&](libmongodbcapi_status& status) { - return mongo::capi_lib_init(params, status); - }); -} - -int libmongodbcapi_lib_fini(libmongodbcapi_lib* const lib, libmongodbcapi_status* const statusPtr) { - return enterCXX(statusPtr, [&](libmongodbcapi_status& status) { - return mongo::capi_lib_fini(lib, status); - }); -} - -libmongodbcapi_instance* libmongodbcapi_instance_create(libmongodbcapi_lib* lib, - const char* const yaml_config, - libmongodbcapi_status* const statusPtr) { - return enterCXX(statusPtr, [&](libmongodbcapi_status& status) { - return mongo::instance_new(lib, yaml_config, status); - }); -} - -int libmongodbcapi_instance_destroy(libmongodbcapi_instance* const db, - libmongodbcapi_status* const statusPtr) { - return enterCXX(statusPtr, [&](libmongodbcapi_status& status) { - return mongo::instance_destroy(db, status); - }); -} - -libmongodbcapi_client* libmongodbcapi_client_create(libmongodbcapi_instance* const db, - libmongodbcapi_status* const statusPtr) { - return enterCXX(statusPtr, - [&](libmongodbcapi_status& status) { return mongo::client_new(db, status); }); -} - -int libmongodbcapi_client_destroy(libmongodbcapi_client* const client, - libmongodbcapi_status* const statusPtr) { - return enterCXX(statusPtr, [&](libmongodbcapi_status& status) { - return mongo::client_destroy(client, status); - }); -} - -int libmongodbcapi_client_invoke(libmongodbcapi_client* const client, - const void* input, - const size_t input_size, - void** const output, - size_t* const output_size, - libmongodbcapi_status* const statusPtr) { - return enterCXX(statusPtr, [&](libmongodbcapi_status& status) { - return mongo::client_wire_protocol_rpc( - client, input, input_size, output, output_size, status); - }); -} - -int libmongodbcapi_status_get_error(const libmongodbcapi_status* const status) { - return mongo::capi_status_get_error(status); -} - -const char* libmongodbcapi_status_get_explanation(const libmongodbcapi_status* const status) { - return mongo::capi_status_get_what(status); -} - -int libmongodbcapi_status_get_code(const libmongodbcapi_status* const status) { - return mongo::capi_status_get_code(status); -} - -libmongodbcapi_status* libmongodbcapi_status_create(void) { - return new libmongodbcapi_status; -} - -void libmongodbcapi_status_destroy(libmongodbcapi_status* const status) { - delete status; -} - -} // extern "C" diff --git a/src/mongo/client/embedded/libmongodbcapi.h b/src/mongo/client/embedded/libmongodbcapi.h deleted file mode 100644 index 266013f2d09..00000000000 --- a/src/mongo/client/embedded/libmongodbcapi.h +++ /dev/null @@ -1,672 +0,0 @@ -/*- - * Copyright (C) 2017 MongoDB Inc. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * - * As a special exception, the copyright holders give permission to link the - * code of portions of this program with the OpenSSL library under certain - * conditions as described in each individual source file and distribute - * linked combinations including the program with the OpenSSL library. You - * must comply with the GNU Affero General Public License in all respects - * for all of the code used other than as permitted herein. If you modify - * file(s) with this exception, you may extend this exception to your - * version of the file(s), but you are not obligated to do so. If you do not - * wish to do so, delete this exception statement from your version. If you - * delete this exception statement from all source files in the program, - * then also delete it in the license file. - */ -#ifndef LIBMONGODBCAPI_H -#define LIBMONGODBCAPI_H - -#include <stddef.h> -#include <stdint.h> - -#ifdef _DOXYGEN -/** - * Embeddable MongoDB Library. - * - * @invariant All functions in this library (those `extern "C"` functions starting with - * `libmongodbcapi_` in their names) have undefined behavior unless their thread safety requirements - * are met. - * - * We define "Thread Safety" to mean that a program will not exhibit undefined behavior in multiple - * concurrent execution contexts over this library. Please note, however, that values returned from - * a function may be stale, if the parameter objects passed to that function are subsequently passed - * to any function in another thread. Although the library will not exhibit undefined behavior, the - * program may not function as desired. - * - * @note The definition of "undefined behavior" with respect to this library includes any - * undocumented result up to and including undefined behavior of the entire program under the C and - * C++ language standards. - * @note The specification of post-conditions in this library only holds if undefined behavior does - * not occur. - * @note Some functions provide runtime diagnostics for some violations of their preconditions -- - * this behavior is not guaranteed and is provided as a convenience for both debugging and - * protection of data integrity. Some of these diagnostics are documented in the return-value - * specifications for these functions; however, if such a return value would be returned as the - * result of a violation of a precondition, then this return value is not guaranteed in this or any - * future release. - */ -namespace LibMongoDBCAPI { -// Doxygen requires a namespace when processing global scope functions, in order to generate -// documentation. We also use it as a hook to provide library-wide documentation. -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * An object which describes the details of the failure of an operation. - * - * The Embedded MongoDB Library (most `libmongodbcapi_` prefixed functions) uses allocated objects - * of this type to report the details of any failure, when an operation cannot be completed. - * Several `libmongodbcapi_status` functions are provided which permit observing the details of - * these failures. Further a construction function and a destruction function for these objects are - * also provided. - * - * @invariant The use of `libmongodbcapi_status` objects from multiple threads is not threadsafe - * unless all of the threads accessing a single `libmongodbcapi_status` object are passing that - * object as a const-qualified (`const libmongodbcapi_status *`) pointer. If a single thread is - * passing a `libmongodbcapi_status` object a function taking it by non-const-qualified - * (`libmongodbcapi_status *`) pointer, then no other thread may access the `libmongodbcapi_status` - * object. - * - * @note All `libmongodbcapi_` functions which take a `status` object may be passed a `NULL` - * pointer. In that case the function will not be able to report detailed status information; - * however, that function may still be called. - * - * @note All `libmongodbcapi_status` functions can be used before the `libmongodbcapi` library is - * initialized. This facilitates detailed error reporting from all library functions. - */ -typedef struct libmongodbcapi_status libmongodbcapi_status; - -/** - * Allocate and construct an API-return-status buffer object of type `libmongodbcapi_status`. - * - * All `libmongodbcapi_` functions outside of the `libmongodbcapi_status` family accept pointers to - * these objects (specifically a parameter of type `libmongodbcapi_status *`). These functions use - * that output-parameter as a mechanism for detailed error reporting. If a `NULL` pointer is - * passed, then these functions will not be able to report the details of their error. - * - * @pre None. - * - * @returns A pointer to a newly allocated `libmongodbcapi_status` object which will hold details of - * any failures of operations to which it was passed. - * @returns `NULL` when construction of a `libmongodbcapi_status` object fails. - * - * @invariant This function is completely threadsafe. - * - * @note It is possible to use the rest of the `libmongodbcapi` functions without status objects if - * detailed error reporting is unnecessary; however, if allocation of status objects fails it is - * likely that all other `libmongodbcapi` operations will fail as well. - * @note Allocation of an Embedded MongoDB Status buffer should rarely fail, except for - * out-of-memory reasons. - * - * @note This function may be called before `libmongodbcapi_lib_init`. - */ -libmongodbcapi_status* libmongodbcapi_status_create(void); - -/** - * Destroys a valid `libmongodbcapi_status` object. - * - * Frees the storage associated with a valid `libmongodbcapi_status` object including all shared - * observable storage, such as strings. The only way that a `libmongodbcapi_status` can be validly - * created is via `libmongodbcapi_status_create`, therefore the object being destroyed must have - * been created using that function. - * - * @pre The specified `status` object must not be `NULL`. - * @pre The specified `status` object must be a valid `libmongodbcapi_status` object. - * - * @param status The `libmongodbcapi_status` object to release. - * - * @invariant This function is not threadsafe unless the specified `status` object is not passed - * concurrently to any other function. It is safe to destroy distinct `libmongodbcapi_status` - * objects on distinct threads. - * - * @note This function does not report failures. - * @note This behavior of this function is undefined unless its preconditions are met. - * - * @note This function may be called before `libmongodbcapi_lib_init`. - * - * @note This function causes all storage associated with the specified `status` to be released, - * including the storage referenced by functions that returned observable storage buffers from this - * status, such as strings. - */ -void libmongodbcapi_status_destroy(libmongodbcapi_status* status); - -/** - * The error codes reported by `libmongodbcapi` functions will be given the symbolic names as mapped - * by this enum. - * - * When a `libmongdbcapi` function fails (and it has been documented report errors) it will report - * that error in the form of an `int` status code. That status code will always be returned as the - * type `int`; however, the values in this enum can be used to classify the failure. - */ -typedef enum { - LIBMONGODB_CAPI_ERROR_IN_REPORTING_ERROR = -2, - LIBMONGODB_CAPI_ERROR_UNKNOWN = -1, - LIBMONGODB_CAPI_SUCCESS = 0, - - LIBMONGODB_CAPI_ERROR_ENOMEM = 1, - LIBMONGODB_CAPI_ERROR_EXCEPTION = 2, - LIBMONGODB_CAPI_ERROR_LIBRARY_ALREADY_INITIALIZED = 3, - LIBMONGODB_CAPI_ERROR_LIBRARY_NOT_INITIALIZED = 4, - LIBMONGODB_CAPI_ERROR_INVALID_LIB_HANDLE = 5, - LIBMONGODB_CAPI_ERROR_DB_INITIALIZATION_FAILED = 6, - LIBMONGODB_CAPI_ERROR_INVALID_DB_HANDLE = 7, - LIBMONGODB_CAPI_ERROR_HAS_DB_HANDLES_OPEN = 8, - LIBMONGODB_CAPI_ERROR_DB_MAX_OPEN = 9, - LIBMONGODB_CAPI_ERROR_DB_CLIENTS_OPEN = 10, - LIBMONGODB_CAPI_ERROR_INVALID_CLIENT_HANDLE = 11, - LIBMONGODB_CAPI_ERROR_REENTRANCY_NOT_ALLOWED = 12, -} libmongodbcapi_error; - -/** - * Gets an error code from a `libmongodbcapi_status` object. - * - * When a `libmongodbcapi` function fails (and it has been documented to report errors) it will - * report its error in the form of an `int` status code which is stored into a supplied - * `libmongodbcapi_status` object, if provided. Some of these functions may also report extra - * information, which will be reported by other observer functions. Every `libmongodbcapi` function - * which reports errors will always update the `Error` code stored in a `libmongodbcapi_status` - * object, even upon success. - * - * @pre The specified `status` object must not be `NULL`. - * @pre The specified `status` object must be a valid `libmongodbcapi_status` object. - * @pre The specified `status` object must have been passed to a `libmongodbcapi` function. - * - * @param status The `libmongodbcapi_status` object from which to get an associated error code. - * - * @returns `LIBMONGODB_CAPI_SUCCESS` if the last function to which `status` was passed succeeded. - * @returns The `libmongodbcapi_error` code associated with the `status` parameter. - * - * @invariant This function is thread-safe, if the thread safety requirements specified by - * `libmongodbcapi_status`'s invariants are met. - * - * @note This function will report the `libmongodbcapi_error` value for the failure associated with - * `status`, therefore if the failing function returned a `libmongodbcapi_error` value itself, then - * calling this function is superfluous. - * - * @note This function does not report its own failures. - * @note This behavior of this function is undefined unless its preconditions are met. - */ -int libmongodbcapi_status_get_error(const libmongodbcapi_status* status); - -/** - * Gets a descriptive error message from a `libmongodbcapi_status` object. - * - * Any `libmongodbcapi` function which reports failure must, when it fails, update the specified - * `libmongodbcapi_status` object, if it exists, to contain a string indicating a user-readable - * description of the failure. This error message string is dependent upon the kind of error - * encountered and may contain dynamically generated information describing the specifics of the - * failure. - * - * @pre The specified `status` must not be `NULL`. - * @pre The specified `status` must be a valid `libmongodbcapi_status` object. - * @pre The specified `status` must have been passed to a `libmongodbcapi` function. - * @pre The function to which the specified `status` was passed must not have returned - * `LIBMONGODB_CAPI_SUCCESS` as its error code. - * - * @param status The `libmongodbcapi_status` object from which to get an associated error message. - * - * @returns A null-terminated string containing an error message. This string will be valid until - * the next time that the specified `status` is passed to any other `libmongodbcapi` function - * (including those in the `libmongodbcapi_status` family). - * - * @invariant This function is thread-safe, if the thread safety requirements specified by - * `libmongodbcapi_status`'s invariants are met; however, the pointer returned by this function is - * considered to be part of the specified `status` object for the purposes of thread safety. If the - * `libmongodbcapi_status` is changed, by any thread, it will invalidate the string returned by this - * function. - * - * @note For failures where the `libmongodbcapi_status_cet_error( status ) == - * LIBMONGODB_CAPI_ERROR_EXCEPTION`, this returns a string representation of the internal C++ - * exception. - * - * @note The storage for the returned string is associated with the specified `status` object, and - * therefore it will be deallocated when the `status` is destroyed using - * `libmongodbcapi_destroy_status`. - * - * @note This function does not report its own failures. - * @note This behavior of this function is undefined unless its preconditions are met. - */ -const char* libmongodbcapi_status_get_explanation(const libmongodbcapi_status* status); - -/** - * Gets a status code from a `libmongodbcapi_status` object. - * - * Any `libmongodbcapi` function which reports failure must, when it fails, update the specified - * `libmongodbcapi_status` object, if it exists, to contain a numeric code indicating a sub-category - * of failure. This error code is one specified by the normal MongoDB Driver interface, if - * `libmongodbcapi_error == LIBMONGODB_CAPI_ERROR_EXCEPTION`. - * - * @pre The specified `status` must not be `NULL`. - * @pre The specified `status` must be a valid `libmongodbcapi_status` object. - * @pre The specified `status` must have been passed to a `libmongodbcapi` function. - * @pre The function to which the specified `status` was passed must not have returned - * `LIBMONGODB_CAPI_SUCCESS` as its error code. - * - * @param status The `libmongodbcapi_status` object from which to get an associated status code. - * - * @returns A numeric status code associated with the `status` parameter which indicates a - * sub-category of failure. - * - * @invariant This function is thread-safe, if the thread safety requirements specified by - * `libmongodbcapi_status`'s invariants are met. - * - * @note For failures where the `libmongodbcapi_error == LIBMONGODB_CAPI_ERROR_EXCEPTION` and the - * exception was of type `mongo::DBException`, this returns the numeric code indicating which - * specific `mongo::DBException` was thrown. - * - * @note For failures where the `libmongodbcapi_error != LIBMONGODB_CAPI_ERROR_EXCEPTION` the value - * of this code is unspecified. - * - * @note This function does not report its own failures. - * @note This behavior of this function is undefined unless its preconditions are met. - */ -int libmongodbcapi_status_get_code(const libmongodbcapi_status* status); - - -/** - * An object which describes the runtime state of the Embedded MongoDB Library. - * - * The `libmongodbcapi` library uses allocated objects of this type to indicate the present state of - * the library. Some operations which the library provides need access to this object. Further a - * construction function and a destruction function for these objects are also provided. No more - * than a single object instance of this type may exist at any given time. - * - * @invariant The use of `libmongodbcapi_lib` objects from multiple threads is not threadsafe unless - * all of the threads accessing a single `libmongodbcapi_lib` object are not destroying this object. - * If a single thread is passing a `libmongodbcapi_lib` to its destruction function, then no other - * thread may access the `libmongodbcapi_status` object. - */ -typedef struct libmongodbcapi_lib libmongodbcapi_lib; - -/** - * An object which describes the runtime state of the Embedded MongoDB Library. - * - * The `libmongodbcapi` library uses structures of this type to indicate the desired configuration - * of the library. - * - * @invariant Because the library is only initialized once, in a single-threaded fashion, there are - * no thread-safety requirements on this type. - */ -typedef struct libmongodbcapi_init_params libmongodbcapi_init_params; - -/** - * Log callback. For details on what the parameters mean, see the documentation at - * https://docs.mongodb.com/manual/reference/log-messages/ - * - * Severity values, lower means more severe. - * Severe/Fatal = -4 - * Error = -3 - * Warning = -2 - * Info = -1 - * Log = 0 - * Debug = 1 to 5 - */ -typedef void (*libmongodbcapi_log_callback)( - void* user_data, const char* message, const char* component, const char* context, int severity); - -/** - * Valid bits for the log_flags bitfield in libmongodbcapi_init_params. - */ -typedef enum { - /** Placeholder for no logging */ - LIBMONGODB_CAPI_LOG_NONE = 0, - - /** Logs to stdout */ - LIBMONGODB_CAPI_LOG_STDOUT = 1, - - /** Logs to stderr (not supported yet) */ - // LIBMONGODB_CAPI_LOG_STDERR = 2, - - /** Logs via log callback that must be provided when this bit is set. */ - LIBMONGODB_CAPI_LOG_CALLBACK = 4 -} libmongodbcapi_log_flags; - -// See the documentation of this object on the comments above its forward declaration -struct libmongodbcapi_init_params { - /** - * Optional null-terminated YAML formatted MongoDB configuration string. - * See documentation for valid options. - */ - const char* yaml_config; - - /** - * Bitfield of log destinations, accepts values from libmongodbcapi_log_flags. - * Default is stdout. - */ - uint64_t log_flags; - - /** - * Optional log callback to the mongodbcapi library, it is not allowed to reentry the - * mongodbcapi library from the callback. - */ - libmongodbcapi_log_callback log_callback; - - /** - * Optional user data to be returned in the log callback. - */ - void* log_user_data; -}; - -/** - * Initializes the mongodbcapi library, required before any other call. - * - * The Embedded MongoDB Library must be initialized before it can be used. However, it is - * permissible to create and destroy `libmongodbcapi_status` objects without the library having been - * initialized. Initializing the library sets up internal state for all Embedded MongoDB Library - * operations, including creating embedded "server-like" instances and creating clients. - * - * @pre The specified `params` object must either be a valid `libmongodbcapi_lib_params` object (in - * a valid state) or `NULL`. - * @pre The specified `status` object must either be a valid `libmongodbcapi_status` object or - * `NULL`. - * @pre Either `libmongodbcapi_fini` must have never been called in this process, or it was called - * and returned success and `libmongodbcapi_lib_init` was not called after this. - * @pre Either `libmongodbcapi_init` must have never been called in this process, or it was called - * and then the embedded library was terminated by a successful call to `libmongodbcapi_lib_fini`. - * @pre No valid `libmongodbcapi_lib` must exist. - * - * @param params A pointer to libmongodbcapi_init_params containing library initialization - * parameters. A default configuration will be used if `params == NULL`. - * - * @param status A pointer to a `libmongodbcapi_status` object which will not be modified unless - * this function reports a failure. - * - * @post Either the Embedded MongoDB Library will be initialized, or an error will be reported. - * - * @returns A pointer to a `libmongodbcapi_lib` object on success. - * @returns `NULL` and modifies `status` on failure. - * - * @invariant This function is not thread safe. It must be called and have completed before any - * other non-`libmongodbcapi_status` operations can be called on any thread. - * - * @note This function exhibits undefined behavior unless its preconditions are met. - * @note This function may return diagnosic errors for violations of its preconditions, but this - * behavior is not guaranteed. - */ -libmongodbcapi_lib* libmongodbcapi_lib_init(const libmongodbcapi_init_params* params, - libmongodbcapi_status* status); - -/** - * Tears down the state of the library, all databases must be closed before calling this. - * - * The Embedded MongoDB Library must be quiesced before the containg process can be safely - * terminated. Dataloss is not a risk; however, some database repair routines may be executed at - * next initialization if the library is not properly quiesced. It is permissible to create and - * destroy `libmongodbcapi_status` objects after the library has been quiesced. The library may be - * re-initialized with a potentially different configuration after it has been queisced. - * - * @pre All `libmongodbcapi_instance` objects associated with this library handle must be destroyed. - * @pre The specified `lib` object must not be `NULL`. - * @pre The specified `lib` object must be a valid `libmongodbcapi_lib` object. - * @pre The specified `status` object must either be a valid `libmongodbcapi_status` object or - * `NULL`. - * - * @param lib A pointer to a `libmongodbcapi_lib` handle which represents this library. - * - * @param status A pointer to a `libmongodbcapi_status` object which will not be modified unless - * this function reports a failure. - * - * @post Either the Embedded MongoDB Library will be deinitialized, or an error will be reported. - * - * @returns Returns `LIBMONGODB_CAPI_SUCCESS` on success. - * @returns Returns `LIBMONGODB_CAPI_ERROR_LIBRARY_NOT_INITIALIZED` and modifies `status` if - * libmongodbcapi_lib_init() has not been called previously. - * @returns Returns `LIBMONGODB_CAPI_ERROR_HAS_DB_HANDLES_OPEN` and modifies `status` if there are - * open databases that haven't been closed with `libmongodbcapi_instance_create()`. - * @returns Returns `LIBMONGODB_CAPI_ERROR_EXCEPTION` and modifies `status` for errors that resulted - * in an exception. Details can be retrived via `libmongodbcapi_process_get_status()`. - * - * @invariant This function is not thread safe. It cannot be called concurrently with any other - * non-`libmongodbcapi_status` operation. - * - * @note This function exhibits undefined behavior unless its preconditions are met. - * @note This function may return diagnosic errors for violations of its preconditions, but this - * behavior is not guaranteed. - */ -int libmongodbcapi_lib_fini(libmongodbcapi_lib* lib, libmongodbcapi_status* status); - -/** - * An object which represents an instance of an Embedded MongoDB Server. - * - * The Embedded MongoDB Library uses allocated objects of this type (`libmongodbcapi_instance`) to - * indicate the present state of a single "server-like" MongoDB instance. Some operations which the - * library provides need access to this object. Further a construction function and a destruction - * function for these objects are also provided. No more than a single object instance of this type - * may exist at any given time. - * - * @invariant The use of `libmongodbcapi_instance` objects from multiple threads is not threadsafe - * unless all of the threads accessing a single `libmongodbcapi_instance` object are not destroying - * this object. If a single thread is passing a `libmongodbcapi_instance` to its destruction - * function, then no other thread may access the `libmongodbcapi_instance` object. - */ -typedef struct libmongodbcapi_instance libmongodbcapi_instance; - -/** - * Creates an embedded MongoDB instance and returns a handle with the service context. - * - * A `libmongodbcapi_instance` object which represents a single embedded "server-like" context is - * created and returned by this function. At present, only a single server-like instance is - * supported; however, multiple concurrent "server-like" instances may be permissible in future - * releases. - * - * @pre The specified `lib` object must not be `NULL` - * @pre The specified `lib` object must be a valid `libmongodbcapi_lib` object. - * @pre The specified `yaml_config` string must either point to an ASCII null-terminated string or - * be `NULL`. - * @pre The specified `status` object must be either a valid `libmongodbcapi_status` object or - * `NULL`. - * - * @param lib A pointer to a `libmongodbcapi_lib` handle which represents the Embedded MongoDB - * Library. - * - * @param yaml_config A null-terminated YAML formatted Embedded MongoDB Instance configuration. See - * documentation for valid options. - * - * @param status A pointer to a `libmongodbcapi_status` object which will not be modified unless - * this function reports a failure. - * - * @post Either a new Embedded MongoDB Server will be created, or an error will be reported. - * - * @return A pointer to a newly constructed, valid `libmongdbcapi_instance`. - * @return `NULL` and modifies `status` on failure. - * - * @invariant This function is completely threadsafe, as long as its preconditions are met. - * - * @note This function exhibits undefined behavior unless its preconditions are met. - * @note This function may return diagnosic errors for violations of its preconditions, but this - * behavior is not guaranteed. - */ -libmongodbcapi_instance* libmongodbcapi_instance_create(libmongodbcapi_lib* lib, - const char* yaml_config, - libmongodbcapi_status* status); - -/** - * Shuts down an embedded MongoDB instance. - * - * A `libmongodbcapi_instance` embedded "server-like" instance can be terminated by this function. - * All resources used by this instance will be released, and all background tasks associated with it - * will be terminated. - * - * @pre The specified `instance` object must not be `NULL`. - * @pre The specified `instance` object must be a valid `libmongodbcapi_instance` object. - * @pre The specified `status` object must be either a valid `libmongodbcapi_status` object or - * `NULL`. - * @pre All `libmongodbcapi_client` objects associated with this database must be destroyed. - * - * @param instance A pointer to a valid `libmongodbcapi_instance` instance to be destroyed. - * - * @param status A pointer to a `libmongodbcapi_status` object which will not be modified unless - * this function reports a failure. - * - * @post Either the specified Embedded MongoDB Server will be destroyed, or an error will be - * reported. - * - * @returns `LIBMONGODB_CAPI_SUCCESS` on success. - * @returns `LIBMONGODB_CAPI_ERROR_DB_CLIENTS_OPEN` and modifies `status` if there are - * `libmongodbcapi_client` objects still open attached to the `instance`. - * @returns `LIBMONGODB_CAPI_ERROR_EXCEPTION`and modifies `status` for other unspecified errors. - * - * @invariant This function is not threadsafe unless the specified `db` object is not passed - * concurrently to any other function. It is safe to destroy distinct `libmongodbcapi_instance` - * objects on distinct threads. - * - * @note This function exhibits undefined behavior unless its preconditions are met. - * @note This function may return diagnosic errors for violations of its precondition, but this - * behavior is not guaranteed. - */ -int libmongodbcapi_instance_destroy(libmongodbcapi_instance* instance, - libmongodbcapi_status* status); - -/** - * An object which represents "client connection" to an Embedded MongoDB Server. - * - * A `libmongodbcapi_client` connection object is necessary to perform most database operations, - * such as queries. Some operations which the library provides need access to this object. Further - * a construction function and a destruction function for these objects are also provided. Multiple - * object instances of this type may exist at any given time. - * - * @invariant The use of `libmongodbcapi_client` objects from multiple threads is not threadsafe. - */ -typedef struct libmongodbcapi_client libmongodbcapi_client; - -/** - * Creates a new client and returns it. - * - * A client must be created in order to perform database operations. - * - * @pre The specified `instance` object must not be `NULL` - * @pre The specified `instance` object must be a valid `libmongodbcapi_instance` object. - * @pre The specified `status` object must be either a valid `libmongodbcapi_status` object or - * `NULL`. - * - * @post Either a new Embedded MongoDB Client will be created, or an error will be reported. - * - * @param instance The Embedded MongoDB Server instance that will be attached to this client and - * execute its RPC calls - * - * @param status A pointer to a `libmongodbcapi_status` object which will not be modified unless - * this function reports a failure. - * - * @return A pointer to a newly constructed, valid `libmongodbcapi_client`. - * @return `NULL` on error, and modifies `status` on failure. - * - * @invariant This function is completely threadsafe, as long as its preconditions are met. - */ -libmongodbcapi_client* libmongodbcapi_client_create(libmongodbcapi_instance* instance, - libmongodbcapi_status* status); - -/** - * Destroys an Embedded MongoDB Client. - * - * A client must be destroyed before the owning db is destroyed. Database clients must be destroyed - * before the instance associated with them can be destroyed. Further, any resources associated - * with client requests will be relinquished after this call completes. - * - * @pre The specified `client` object must not be `NULL`. - * @pre The specified `client` object must be a valid `libmongodbcapi_client` object. - * @pre The specified `status` object must be either a valid `libmongodbcapi_status` object or - * `NULL`. - * - * @param client A pointer to the client to be destroyed - * - * @param status A pointer to a `libmongodbcapi_status` object which will not be modified unless - * this function reports a failure. - * - * @post Either the specified Embedded MongoDB Client will be destroyed, or an error will be - * reported. - * - * @returns `LIBMONGODB_CAPI_SUCCESS` on success. - * @returns An error code and modifies the specified `status` object on failure. - * - * @invariant This function is not threadsafe unless the specified `client` object is not passed - * concurrently to any other function. It is safe to destroy distinct `libmongodbcapi_client` - * objects on distinct threads. - * - * @note This function exhibits undefined behavior unless its preconditions are met. - * @note This function may return diagnosic errors for violations of its precondition, but this - * behavior is not guaranteed. - */ -int libmongodbcapi_client_destroy(libmongodbcapi_client* client, libmongodbcapi_status* status); - -/** - * Makes an RPC call to the database. - * - * A MongoDB client operation is performed according to the provided BSON object specified by - * `input` and `input_size`. - * - * @pre The specified `client` object must not be `NULL`. - * @pre The specified `client` object must be a valid `libmongodbcapi_client` object. - * @pre The specified `input` buffer must not be `NULL`. - * @pre The specified `input` buffer must be a valid BSON request. - * @pre The specified `output` pointer must not be `NULL` - * @pre The specified `output` pointer must point to a valid, non-const `void *` variable. - * @pre The specified `output_size` pointer must not be `NULL` - * @pre The specified `output` pointer must point to a valid, non-const `size_t` variable. - * @pre The specified `status` object must be either a valid `libmongodbcapi_status` object or - * `NULL`. - * - * @param client The client that will be performing the query on the database - * - * @param input The query to be sent to and then executed by the database - * - * @param input_size The size (number of bytes) of the input query - * - * @param output A pointer to a `void *` where the database can write the location of the output. - * The library will manage the memory pointed to by * `output`. - * - * @param output_size A pointer to a location where this function will write the size (number of - * bytes) of the `output` buffer. - * - * @param status A pointer to a `libmongodbcapi_status` object which will not be modified unless - * this function reports a failure. - * - * @post Either the requested database operation will have been performed, or an error will be - * reported. - * - * @return Returns LIBMONGODB_CAPI_SUCCESS on success. - * @return An error code and modifies `status` on failure - * - * @invariant This function is not thread-safe unless its preconditions are met, and the specified - * `libmongodbcapi_client` object is not concurrently accessed by any other thread until after this - * call has completed. - * - * @note The `output` and `output_size` parameters will not be modified unless the function - * succeeds. - * @note The storage associated with `output` will be valid until the next call to - * `libmongodbcapi_client_wire_protocol_rpc` on the specified `client` object, or the `client` is - * destroyed using `libmongodbcapi_client_destroy`. - * @note That the storage which is referenced by `output` upon successful completion is considered - * to be part of the specified `client` object for the purposes of thread-safety and undefined - * behavior. - */ -int libmongodbcapi_client_invoke(libmongodbcapi_client* client, - const void* input, - size_t input_size, - void** output, - size_t* output_size, - libmongodbcapi_status* status); - -#ifdef __cplusplus -} // extern "C" -#endif - -#ifdef _DOXYGEN -} // namespace LibMongoDBCAPI -#endif - -#endif diff --git a/src/mongo/client/embedded/libmongodbcapi_test.cpp b/src/mongo/client/embedded/libmongodbcapi_test.cpp deleted file mode 100644 index df780bbe265..00000000000 --- a/src/mongo/client/embedded/libmongodbcapi_test.cpp +++ /dev/null @@ -1,721 +0,0 @@ -/** - * Copyright (C) 2017 MongoDB Inc. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * - * As a special exception, the copyright holders give permission to link the - * code of portions of this program with the OpenSSL library under certain - * conditions as described in each individual source file and distribute - * linked combinations including the program with the OpenSSL library. You - * must comply with the GNU Affero General Public License in all respects for - * all of the code used other than as permitted herein. If you modify file(s) - * with this exception, you may extend this exception to your version of the - * file(s), but you are not obligated to do so. If you do not wish to do so, - * delete this exception statement from your version. If you delete this - * exception statement from all source files in the program, then also delete - * it in the license file. - */ - - -#include "mongo/client/embedded/libmongodbcapi.h" - -#include <memory> -#include <set> -#include <yaml-cpp/yaml.h> - -#include "mongo/bson/bsonobjbuilder.h" -#include "mongo/db/commands/test_commands_enabled.h" -#include "mongo/db/json.h" -#include "mongo/db/server_options.h" -#include "mongo/rpc/message.h" -#include "mongo/rpc/op_msg.h" -#include "mongo/stdx/thread.h" -#include "mongo/unittest/temp_dir.h" -#include "mongo/unittest/unittest.h" -#include "mongo/util/options_parser/environment.h" -#include "mongo/util/options_parser/option_section.h" -#include "mongo/util/options_parser/options_parser.h" -#include "mongo/util/quick_exit.h" -#include "mongo/util/shared_buffer.h" -#include "mongo/util/signal_handlers_synchronous.h" - -namespace moe = mongo::optionenvironment; - -libmongodbcapi_lib* global_lib_handle; - -namespace { - -std::unique_ptr<mongo::unittest::TempDir> globalTempDir; - -struct StatusDestructor { - void operator()(libmongodbcapi_status* const p) const noexcept { - if (p) - libmongodbcapi_status_destroy(p); - } -}; - -using CapiStatusPtr = std::unique_ptr<libmongodbcapi_status, StatusDestructor>; - -CapiStatusPtr makeStatusPtr() { - return CapiStatusPtr{libmongodbcapi_status_create()}; -} - -struct ClientDestructor { - void operator()(libmongodbcapi_client* const p) const noexcept { - if (!p) - return; - - auto status = makeStatusPtr(); - if (libmongodbcapi_client_destroy(p, status.get()) != LIBMONGODB_CAPI_SUCCESS) { - std::cerr << "libmongodb_capi_client_destroy failed." << std::endl; - if (status) { - std::cerr << "Error code: " << libmongodbcapi_status_get_error(status.get()) - << std::endl; - std::cerr << "Error message: " - << libmongodbcapi_status_get_explanation(status.get()) << std::endl; - } - } - } -}; - -using MongoDBCAPIClientPtr = std::unique_ptr<libmongodbcapi_client, ClientDestructor>; - -class MongodbCAPITest : public mongo::unittest::Test { -protected: - void setUp() { - status = libmongodbcapi_status_create(); - ASSERT(status != nullptr); - - if (!globalTempDir) { - globalTempDir = std::make_unique<mongo::unittest::TempDir>("embedded_mongo"); - } - - libmongodbcapi_init_params params; - params.log_flags = 0; - params.log_callback = nullptr; - params.log_user_data = nullptr; - - YAML::Emitter yaml; - yaml << YAML::BeginMap; - - yaml << YAML::Key << "storage"; - yaml << YAML::Value << YAML::BeginMap; - yaml << YAML::Key << "dbPath"; - yaml << YAML::Value << globalTempDir->path(); - yaml << YAML::EndMap; // storage - - yaml << YAML::EndMap; - - params.yaml_config = yaml.c_str(); - - lib = libmongodbcapi_lib_init(¶ms, status); - ASSERT(lib != nullptr) << libmongodbcapi_status_get_explanation(status); - - db = libmongodbcapi_instance_create(lib, yaml.c_str(), status); - ASSERT(db != nullptr) << libmongodbcapi_status_get_explanation(status); - } - - void tearDown() { - ASSERT_EQUALS(libmongodbcapi_instance_destroy(db, status), LIBMONGODB_CAPI_SUCCESS) - << libmongodbcapi_status_get_explanation(status); - ASSERT_EQUALS(libmongodbcapi_lib_fini(lib, status), LIBMONGODB_CAPI_SUCCESS) - << libmongodbcapi_status_get_explanation(status); - libmongodbcapi_status_destroy(status); - } - - libmongodbcapi_instance* getDB() const { - return db; - } - - MongoDBCAPIClientPtr createClient() const { - MongoDBCAPIClientPtr client(libmongodbcapi_client_create(db, status)); - ASSERT(client.get() != nullptr) << libmongodbcapi_status_get_explanation(status); - return client; - } - - mongo::Message messageFromBuffer(void* data, size_t dataLen) { - auto sb = mongo::SharedBuffer::allocate(dataLen); - memcpy(sb.get(), data, dataLen); - mongo::Message msg(std::move(sb)); - return msg; - } - - mongo::BSONObj performRpc(MongoDBCAPIClientPtr& client, mongo::OpMsgRequest request) { - auto inputMessage = request.serialize(); - - // declare the output size and pointer - void* output; - size_t outputSize; - - // call the wire protocol - int err = libmongodbcapi_client_invoke( - client.get(), inputMessage.buf(), inputMessage.size(), &output, &outputSize, status); - ASSERT_EQUALS(err, LIBMONGODB_CAPI_SUCCESS); - - // convert the shared buffer to a mongo::message and ensure that it is valid - auto outputMessage = messageFromBuffer(output, outputSize); - ASSERT(outputMessage.size() > 0); - ASSERT(outputMessage.operation() == inputMessage.operation()); - - // convert the message into an OpMessage to examine its BSON - auto outputOpMsg = mongo::OpMsg::parseOwned(outputMessage); - ASSERT(outputOpMsg.body.valid(mongo::BSONVersion::kLatest)); - return outputOpMsg.body; - } - - -protected: - libmongodbcapi_lib* lib; - libmongodbcapi_instance* db; - libmongodbcapi_status* status; -}; - -TEST_F(MongodbCAPITest, CreateAndDestroyDB) { - // Test the setUp() and tearDown() test fixtures -} - -TEST_F(MongodbCAPITest, CreateAndDestroyDBAndClient) { - auto client = createClient(); -} - -// This test is to make sure that destroying the db will fail if there's remaining clients left. -TEST_F(MongodbCAPITest, DoNotDestroyClient) { - auto client = createClient(); - ASSERT(libmongodbcapi_instance_destroy(getDB(), nullptr) != LIBMONGODB_CAPI_SUCCESS); -} - -TEST_F(MongodbCAPITest, CreateMultipleClients) { - const int numClients = 10; - std::set<MongoDBCAPIClientPtr> clients; - for (int i = 0; i < numClients; i++) { - clients.insert(createClient()); - } - - // ensure that each client is unique by making sure that the set size equals the number of - // clients instantiated - ASSERT_EQUALS(static_cast<int>(clients.size()), numClients); -} - -TEST_F(MongodbCAPITest, IsMaster) { - // create the client object - auto client = createClient(); - - // craft the isMaster message - mongo::BSONObj inputObj = mongo::fromjson("{isMaster: 1}"); - auto inputOpMsg = mongo::OpMsgRequest::fromDBAndBody("admin", inputObj); - auto output = performRpc(client, inputOpMsg); - ASSERT(output.getBoolField("ismaster")); -} - -TEST_F(MongodbCAPITest, CreateIndex) { - // create the client object - auto client = createClient(); - - // craft the createIndexes message - mongo::BSONObj inputObj = mongo::fromjson( - R"raw_delimiter({ - createIndexes: 'items', - indexes: - [ - { - key: { - task: 1 - }, - name: 'task_1' - } - ] - })raw_delimiter"); - auto inputOpMsg = mongo::OpMsgRequest::fromDBAndBody("index_db", inputObj); - auto output = performRpc(client, inputOpMsg); - - ASSERT(output.hasField("ok")); - ASSERT(output.getField("ok").numberDouble() == 1.0); - ASSERT(output.getIntField("numIndexesAfter") == output.getIntField("numIndexesBefore") + 1); -} - -TEST_F(MongodbCAPITest, CreateBackgroundIndex) { - // create the client object - auto client = createClient(); - - // craft the createIndexes message - mongo::BSONObj inputObj = mongo::fromjson( - R"raw_delimiter({ - createIndexes: 'items', - indexes: - [ - { - key: { - task: 1 - }, - name: 'task_1', - background: true - } - ] - })raw_delimiter"); - auto inputOpMsg = mongo::OpMsgRequest::fromDBAndBody("background_index_db", inputObj); - auto output = performRpc(client, inputOpMsg); - - ASSERT(output.hasField("ok")); - ASSERT(output.getField("ok").numberDouble() != 1.0); -} - -TEST_F(MongodbCAPITest, TrimMemory) { - // create the client object - auto client = createClient(); - - // craft the isMaster message - mongo::BSONObj inputObj = mongo::fromjson("{trimMemory: 'aggressive'}"); - auto inputOpMsg = mongo::OpMsgRequest::fromDBAndBody("admin", inputObj); - performRpc(client, inputOpMsg); -} - -TEST_F(MongodbCAPITest, BatteryLevel) { - // create the client object - auto client = createClient(); - - // craft the isMaster message - mongo::BSONObj inputObj = mongo::fromjson("{setBatteryLevel: 'low'}"); - auto inputOpMsg = mongo::OpMsgRequest::fromDBAndBody("admin", inputObj); - performRpc(client, inputOpMsg); -} - - -TEST_F(MongodbCAPITest, InsertDocument) { - auto client = createClient(); - - mongo::BSONObj insertObj = mongo::fromjson( - "{insert: 'collection_name', documents: [{firstName: 'Mongo', lastName: 'DB', age: 10}]}"); - auto insertOpMsg = mongo::OpMsgRequest::fromDBAndBody("db_name", insertObj); - auto outputBSON = performRpc(client, insertOpMsg); - ASSERT(outputBSON.hasField("n")); - ASSERT(outputBSON.getIntField("n") == 1); - ASSERT(outputBSON.hasField("ok")); - ASSERT(outputBSON.getField("ok").numberDouble() == 1.0); -} - -TEST_F(MongodbCAPITest, InsertMultipleDocuments) { - auto client = createClient(); - - mongo::BSONObj insertObj = mongo::fromjson( - "{insert: 'collection_name', documents: [{firstName: 'doc1FirstName', lastName: " - "'doc1LastName', age: 30}, {firstName: 'doc2FirstName', lastName: 'doc2LastName', age: " - "20}]}"); - auto insertOpMsg = mongo::OpMsgRequest::fromDBAndBody("db_name", insertObj); - auto outputBSON = performRpc(client, insertOpMsg); - ASSERT(outputBSON.hasField("n")); - ASSERT(outputBSON.getIntField("n") == 2); - ASSERT(outputBSON.hasField("ok")); - ASSERT(outputBSON.getField("ok").numberDouble() == 1.0); -} - -TEST_F(MongodbCAPITest, KillOp) { - auto client = createClient(); - - mongo::stdx::thread killOpThread([this]() { - auto client = createClient(); - - mongo::BSONObj currentOpObj = mongo::fromjson("{currentOp: 1}"); - auto currentOpMsg = mongo::OpMsgRequest::fromDBAndBody("admin", currentOpObj); - mongo::BSONObj outputBSON; - - // Wait for the sleep command to start in the main test thread. - int opid = -1; - do { - outputBSON = performRpc(client, currentOpMsg); - auto inprog = outputBSON.getObjectField("inprog"); - - // See if we find the sleep command among the running commands - for (const auto& elt : inprog) { - auto inprogObj = inprog.getObjectField(elt.fieldNameStringData()); - std::string ns = inprogObj.getStringField("ns"); - if (ns == "admin.$cmd") { - opid = inprogObj.getIntField("opid"); - break; - } - } - } while (opid == -1); - - // Sleep command found, kill it. - std::stringstream ss; - ss << "{'killOp': 1, 'op': " << opid << "}"; - mongo::BSONObj killOpObj = mongo::fromjson(ss.str()); - auto killOpMsg = mongo::OpMsgRequest::fromDBAndBody("admin", killOpObj); - outputBSON = performRpc(client, killOpMsg); - - ASSERT(outputBSON.hasField("ok")); - ASSERT(outputBSON.getField("ok").numberDouble() == 1.0); - }); - - mongo::BSONObj sleepObj = mongo::fromjson("{'sleep': {'secs': 1000}}"); - auto sleepOpMsg = mongo::OpMsgRequest::fromDBAndBody("admin", sleepObj); - auto outputBSON = performRpc(client, sleepOpMsg); - - ASSERT(outputBSON.hasField("ok")); - ASSERT(outputBSON.getField("ok").numberDouble() != 1.0); - ASSERT(outputBSON.getIntField("code") == mongo::ErrorCodes::Interrupted); - - killOpThread.join(); -} - -TEST_F(MongodbCAPITest, ReadDB) { - auto client = createClient(); - - mongo::BSONObj findObj = mongo::fromjson("{find: 'collection_name', limit: 2}"); - auto findMsg = mongo::OpMsgRequest::fromDBAndBody("db_name", findObj); - auto outputBSON = performRpc(client, findMsg); - - - ASSERT(outputBSON.valid(mongo::BSONVersion::kLatest)); - ASSERT(outputBSON.hasField("cursor")); - ASSERT(outputBSON.getField("cursor").embeddedObject().hasField("firstBatch")); - mongo::BSONObj arrObj = - outputBSON.getField("cursor").embeddedObject().getField("firstBatch").embeddedObject(); - ASSERT(arrObj.couldBeArray()); - - mongo::BSONObjIterator i(arrObj); - int index = 0; - while (i.moreWithEOO()) { - mongo::BSONElement e = i.next(); - if (e.eoo()) - break; - index++; - } - ASSERT(index == 2); -} - -TEST_F(MongodbCAPITest, InsertAndRead) { - auto client = createClient(); - - mongo::BSONObj insertObj = mongo::fromjson( - "{insert: 'collection_name', documents: [{firstName: 'Mongo', lastName: 'DB', age: 10}]}"); - auto insertOpMsg = mongo::OpMsgRequest::fromDBAndBody("db_name", insertObj); - auto outputBSON1 = performRpc(client, insertOpMsg); - ASSERT(outputBSON1.valid(mongo::BSONVersion::kLatest)); - ASSERT(outputBSON1.hasField("n")); - ASSERT(outputBSON1.getIntField("n") == 1); - ASSERT(outputBSON1.hasField("ok")); - ASSERT(outputBSON1.getField("ok").numberDouble() == 1.0); - - mongo::BSONObj findObj = mongo::fromjson("{find: 'collection_name', limit: 1}"); - auto findMsg = mongo::OpMsgRequest::fromDBAndBody("db_name", findObj); - auto outputBSON2 = performRpc(client, findMsg); - ASSERT(outputBSON2.valid(mongo::BSONVersion::kLatest)); - ASSERT(outputBSON2.hasField("cursor")); - ASSERT(outputBSON2.getField("cursor").embeddedObject().hasField("firstBatch")); - mongo::BSONObj arrObj = - outputBSON2.getField("cursor").embeddedObject().getField("firstBatch").embeddedObject(); - ASSERT(arrObj.couldBeArray()); - - mongo::BSONObjIterator i(arrObj); - int index = 0; - while (i.moreWithEOO()) { - mongo::BSONElement e = i.next(); - if (e.eoo()) - break; - index++; - } - ASSERT(index == 1); -} - -TEST_F(MongodbCAPITest, InsertAndReadDifferentClients) { - auto client1 = createClient(); - auto client2 = createClient(); - - mongo::BSONObj insertObj = mongo::fromjson( - "{insert: 'collection_name', documents: [{firstName: 'Mongo', lastName: 'DB', age: 10}]}"); - auto insertOpMsg = mongo::OpMsgRequest::fromDBAndBody("db_name", insertObj); - auto outputBSON1 = performRpc(client1, insertOpMsg); - ASSERT(outputBSON1.valid(mongo::BSONVersion::kLatest)); - ASSERT(outputBSON1.hasField("n")); - ASSERT(outputBSON1.getIntField("n") == 1); - ASSERT(outputBSON1.hasField("ok")); - ASSERT(outputBSON1.getField("ok").numberDouble() == 1.0); - - mongo::BSONObj findObj = mongo::fromjson("{find: 'collection_name', limit: 1}"); - auto findMsg = mongo::OpMsgRequest::fromDBAndBody("db_name", findObj); - auto outputBSON2 = performRpc(client2, findMsg); - ASSERT(outputBSON2.valid(mongo::BSONVersion::kLatest)); - ASSERT(outputBSON2.hasField("cursor")); - ASSERT(outputBSON2.getField("cursor").embeddedObject().hasField("firstBatch")); - mongo::BSONObj arrObj = - outputBSON2.getField("cursor").embeddedObject().getField("firstBatch").embeddedObject(); - ASSERT(arrObj.couldBeArray()); - - mongo::BSONObjIterator i(arrObj); - int index = 0; - while (i.moreWithEOO()) { - mongo::BSONElement e = i.next(); - if (e.eoo()) - break; - index++; - } - ASSERT(index == 1); -} - -TEST_F(MongodbCAPITest, InsertAndDelete) { - auto client = createClient(); - mongo::BSONObj insertObj = mongo::fromjson( - "{insert: 'collection_name', documents: [{firstName: 'toDelete', lastName: 'notImportant', " - "age: 10}]}"); - auto insertOpMsg = mongo::OpMsgRequest::fromDBAndBody("db_name", insertObj); - auto outputBSON1 = performRpc(client, insertOpMsg); - ASSERT(outputBSON1.valid(mongo::BSONVersion::kLatest)); - ASSERT(outputBSON1.hasField("n")); - ASSERT(outputBSON1.getIntField("n") == 1); - ASSERT(outputBSON1.hasField("ok")); - ASSERT(outputBSON1.getField("ok").numberDouble() == 1.0); - - - // Delete - mongo::BSONObj deleteObj = mongo::fromjson( - "{delete: 'collection_name', deletes: [{q: {firstName: 'toDelete', age: 10}, limit: " - "1}]}"); - auto deleteOpMsg = mongo::OpMsgRequest::fromDBAndBody("db_name", deleteObj); - auto outputBSON2 = performRpc(client, deleteOpMsg); - ASSERT(outputBSON2.valid(mongo::BSONVersion::kLatest)); - ASSERT(outputBSON2.hasField("n")); - ASSERT(outputBSON2.getIntField("n") == 1); - ASSERT(outputBSON2.hasField("ok")); - ASSERT(outputBSON2.getField("ok").numberDouble() == 1.0); -} - - -TEST_F(MongodbCAPITest, InsertAndUpdate) { - auto client = createClient(); - - mongo::BSONObj insertObj = mongo::fromjson( - "{insert: 'collection_name', documents: [{firstName: 'toUpdate', lastName: 'notImportant', " - "age: 10}]}"); - auto insertOpMsg = mongo::OpMsgRequest::fromDBAndBody("db_name", insertObj); - auto outputBSON1 = performRpc(client, insertOpMsg); - ASSERT(outputBSON1.valid(mongo::BSONVersion::kLatest)); - ASSERT(outputBSON1.hasField("n")); - ASSERT(outputBSON1.getIntField("n") == 1); - ASSERT(outputBSON1.hasField("ok")); - ASSERT(outputBSON1.getField("ok").numberDouble() == 1.0); - - - // Update - mongo::BSONObj updateObj = mongo::fromjson( - "{update: 'collection_name', updates: [ {q: {firstName: 'toUpdate', age: 10}, u: {'$inc': " - "{age: 5}}}]}"); - auto updateOpMsg = mongo::OpMsgRequest::fromDBAndBody("db_name", updateObj); - auto outputBSON2 = performRpc(client, updateOpMsg); - ASSERT(outputBSON2.valid(mongo::BSONVersion::kLatest)); - ASSERT(outputBSON2.hasField("ok")); - ASSERT(outputBSON2.getField("ok").numberDouble() == 1.0); - ASSERT(outputBSON2.hasField("nModified")); - ASSERT(outputBSON2.getIntField("nModified") == 1); -} - -TEST_F(MongodbCAPITest, RunListCommands) { - auto client = createClient(); - - std::vector<std::string> whitelist = {"_hashBSONElement", - "aggregate", - "buildInfo", - "cloneCollectionAsCapped", - "collMod", - "collStats", - "configureFailPoint", - "convertToCapped", - "count", - "create", - "createIndexes", - "currentOp", - "dataSize", - "dbStats", - "delete", - "distinct", - "drop", - "dropDatabase", - "dropIndexes", - "echo", - "explain", - "find", - "findAndModify", - "geoNear", - "getLastError", - "getMore", - "getParameter", - "getPrevError", - "getShardMap", - "insert", - "isMaster", - "killCursors", - "killOp", - "listCollections", - "listCommands", - "listDatabases", - "listIndexes", - "lockInfo", - "ping", - "planCacheClear", - "planCacheClearFilters", - "planCacheListFilters", - "planCacheListPlans", - "planCacheListQueryShapes", - "planCacheSetFilter", - "reIndex", - "renameCollection", - "repairCursor", - "repairDatabase", - "replSetGetStatus", - "resetError", - "serverStatus", - "setBatteryLevel", - "setParameter", - "sleep", - "trimMemory", - "update", - "validate"}; - std::sort(whitelist.begin(), whitelist.end()); - - mongo::BSONObj listCommandsObj = mongo::fromjson("{ listCommands: 1 }"); - auto listCommandsOpMsg = mongo::OpMsgRequest::fromDBAndBody("db_name", listCommandsObj); - auto output = performRpc(client, listCommandsOpMsg); - auto commandsBSON = output["commands"]; - std::vector<std::string> commands; - for (const auto& element : commandsBSON.Obj()) { - commands.push_back(element.fieldNameStringData().toString()); - } - std::sort(commands.begin(), commands.end()); - - std::vector<std::string> missing; - std::vector<std::string> unsupported; - std::set_difference(whitelist.begin(), - whitelist.end(), - commands.begin(), - commands.end(), - std::back_inserter(missing)); - std::set_difference(commands.begin(), - commands.end(), - whitelist.begin(), - whitelist.end(), - std::back_inserter(unsupported)); - - if (!missing.empty()) { - std::cout << "\nMissing commands from the embedded binary:\n"; - } - for (auto&& cmd : missing) { - std::cout << cmd << "\n"; - } - if (!unsupported.empty()) { - std::cout << "\nUnsupported commands in the embedded binary:\n"; - } - for (auto&& cmd : unsupported) { - std::cout << cmd << "\n"; - } - - ASSERT(missing.empty()); - ASSERT(unsupported.empty()); -} - -// This test is temporary to make sure that only one database can be created -// This restriction may be relaxed at a later time -TEST_F(MongodbCAPITest, CreateMultipleDBs) { - auto status = makeStatusPtr(); - ASSERT(status.get()); - libmongodbcapi_instance* db2 = libmongodbcapi_instance_create(lib, nullptr, status.get()); - ASSERT(db2 == nullptr); - ASSERT_EQUALS(libmongodbcapi_status_get_error(status.get()), LIBMONGODB_CAPI_ERROR_DB_MAX_OPEN); -} -} // namespace - -// Define main function as an entry to these tests. -// These test functions cannot use the main() defined for unittests because they -// call runGlobalInitializers(). The embedded C API calls mongoDbMain() which -// calls runGlobalInitializers(). -int main(const int argc, const char* const* const argv) { - moe::Environment environment; - moe::OptionSection options; - - options.addOptionChaining( - "tempPath", "tempPath", moe::String, "directory to place mongo::TempDir subdirectories"); - - std::map<std::string, std::string> env; - mongo::Status ret = moe::OptionsParser().run( - options, std::vector<std::string>(argv, argv + argc), env, &environment); - if (!ret.isOK()) { - std::cerr << options.helpString(); - return EXIT_FAILURE; - } - if (environment.count("tempPath")) { - ::mongo::unittest::TempDir::setTempPath(environment["tempPath"].as<std::string>()); - } - - ::mongo::clearSignalMask(); - ::mongo::setupSynchronousSignalHandlers(); - ::mongo::serverGlobalParams.noUnixSocket = true; - ::mongo::unittest::setupTestLogger(); - - // Allocate an error descriptor for use in non-configured tests - const auto status = makeStatusPtr(); - - mongo::setTestCommandsEnabled(true); - - // Check so we can initialize the library without providing init params - libmongodbcapi_lib* lib = libmongodbcapi_lib_init(nullptr, status.get()); - if (lib == nullptr) { - std::cerr << "libmongodbcapi_init() failed with " - << libmongodbcapi_status_get_error(status.get()) << ": " - << libmongodbcapi_status_get_explanation(status.get()) << std::endl; - return EXIT_FAILURE; - } - - if (libmongodbcapi_lib_fini(lib, status.get()) != LIBMONGODB_CAPI_SUCCESS) { - std::cerr << "libmongodbcapi_fini() failed with " - << libmongodbcapi_status_get_error(status.get()) << ": " - << libmongodbcapi_status_get_explanation(status.get()) << std::endl; - return EXIT_FAILURE; - } - - // Initialize the library with a log callback and test so we receive at least one callback - // during the lifetime of the test - libmongodbcapi_init_params params{}; - - bool receivedCallback = false; - params.log_flags = LIBMONGODB_CAPI_LOG_STDOUT | LIBMONGODB_CAPI_LOG_CALLBACK; - params.log_callback = [](void* user_data, - const char* message, - const char* component, - const char* context, - int severety) { - ASSERT(message); - ASSERT(component); - *reinterpret_cast<bool*>(user_data) = true; - }; - params.log_user_data = &receivedCallback; - - lib = libmongodbcapi_lib_init(¶ms, nullptr); - if (lib == nullptr) { - std::cerr << "libmongodbcapi_init() failed with " - << libmongodbcapi_status_get_error(status.get()) << ": " - << libmongodbcapi_status_get_explanation(status.get()) << std::endl; - } - - if (libmongodbcapi_lib_fini(lib, nullptr) != LIBMONGODB_CAPI_SUCCESS) { - std::cerr << "libmongodbcapi_fini() failed with " - << libmongodbcapi_status_get_error(status.get()) << ": " - << libmongodbcapi_status_get_explanation(status.get()) << std::endl; - } - - if (!receivedCallback) { - std::cerr << "Did not get a log callback." << std::endl; - } - - const auto result = ::mongo::unittest::Suite::run(std::vector<std::string>(), "", 1); - - globalTempDir.reset(); - mongo::quickExit(result); -} diff --git a/src/mongo/client/embedded/mongoe_main.cpp b/src/mongo/client/embedded/mongoe_main.cpp deleted file mode 100644 index 3a7bcd9ec38..00000000000 --- a/src/mongo/client/embedded/mongoe_main.cpp +++ /dev/null @@ -1,136 +0,0 @@ -/** -* Copyright (C) 2018 MongoDB Inc. -* -* This program is free software: you can redistribute it and/or modify -* it under the terms of the GNU Affero General Public License, version 3, -* as published by the Free Software Foundation. -* -* This program is distributed in the hope that it will be useful, -* but WITHOUT ANY WARRANTY; without even the implied warranty of -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -* GNU Affero General Public License for more details. -* -* You should have received a copy of the GNU Affero General Public License -* along with this program. If not, see <http://www.gnu.org/licenses/>. -* -* As a special exception, the copyright holders give permission to link the -* code of portions of this program with the OpenSSL library under certain -* conditions as described in each individual source file and distribute -* linked combinations including the program with the OpenSSL library. You -* must comply with the GNU Affero General Public License in all respects -* for all of the code used other than as permitted herein. If you modify -* file(s) with this exception, you may extend this exception to your -* version of the file(s), but you are not obligated to do so. If you do not -* wish to do so, delete this exception statement from your version. If you -* delete this exception statement from all source files in the program, -* then also delete it in the license file. -*/ - -#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kDefault - -#include "mongo/platform/basic.h" - -#include "mongo/base/init.h" -#include "mongo/client/embedded/embedded.h" -#include "mongo/db/mongod_options.h" -#include "mongo/db/service_context.h" -#include "mongo/transport/transport_layer.h" -#include "mongo/transport/transport_layer_manager.h" -#include "mongo/util/exit.h" -#include "mongo/util/log.h" -#include "mongo/util/options_parser/options_parser.h" -#include "mongo/util/options_parser/startup_options.h" -#include "mongo/util/signal_handlers.h" -#include "mongo/util/text.h" - -#include <yaml-cpp/yaml.h> - -namespace mongo { -namespace { - -MONGO_INITIALIZER_WITH_PREREQUISITES(SignalProcessingStartup, ("ThreadNameInitializer")) -(InitializerContext*) { - // Make sure we call this as soon as possible but before any other threads are started. Before - // embedded::initialize is too early and after is too late. So instead we hook in during the - // global initialization at the right place. - startSignalProcessingThread(); - return Status::OK(); -} - -int mongoeMain(int argc, char* argv[], char** envp) { - ServiceContext* serviceContext = nullptr; - - registerShutdownTask([&]() { - if (!serviceContext) - return; - - if (auto tl = serviceContext->getTransportLayer()) { - log(logger::LogComponent::kNetwork) << "shutdown: going to close listening sockets..."; - tl->shutdown(); - } - - embedded::shutdown(serviceContext); - }); - - setupSignalHandlers(); - - log() << "MongoDB embedded standalone application, for testing purposes only"; - - try { - optionenvironment::OptionSection startupOptions("Options"); - uassertStatusOK(addMongodOptions(&startupOptions)); - - // Manually run the code that's equivalent to the MONGO_INITIALIZERs for mongod. We can't do - // this in initializers because embedded uses a different options format. However as long as - // we store the options in the same place it will be valid for embedded too. Adding all - // options mongod we don't have to maintain a separate set for this executable, some will be - // unused but that's fine as this is just an executable for testing purposes anyway. - std::vector<std::string> args; - std::map<std::string, std::string> env; - - args.reserve(argc); - std::copy(argv, argv + argc, std::back_inserter(args)); - - optionenvironment::OptionsParser parser; - uassertStatusOK( - parser.run(startupOptions, args, env, &optionenvironment::startupOptionsParsed)); - uassertStatusOK(storeMongodOptions(optionenvironment::startupOptionsParsed)); - - // Add embedded specific options that's not available in mongod here. - YAML::Emitter yaml; - serviceContext = embedded::initialize(yaml.c_str()); - - auto tl = - transport::TransportLayerManager::createWithConfig(&serverGlobalParams, serviceContext); - uassertStatusOK(tl->setup()); - - serviceContext->setTransportLayer(std::move(tl)); - - uassertStatusOK(serviceContext->getServiceExecutor()->start()); - uassertStatusOK(serviceContext->getTransportLayer()->start()); - } catch (const std::exception& ex) { - error() << ex.what(); - return EXIT_BADOPTIONS; - } - - return waitForShutdown(); -} - -} // namespace -} // namespace mongo - -#if defined(_WIN32) -// In Windows, wmain() is an alternate entry point for main(), and receives the same parameters -// as main() but encoded in Windows Unicode (UTF-16); "wide" 16-bit wchar_t characters. The -// WindowsCommandLine object converts these wide character strings to a UTF-8 coded equivalent -// and makes them available through the argv() and envp() members. This enables mongoDbMain() -// to process UTF-8 encoded arguments and environment variables without regard to platform. -int wmain(int argc, wchar_t* argvW[], wchar_t* envpW[]) { - mongo::WindowsCommandLine wcl(argc, argvW, envpW); - return mongo::mongoeMain(argc, wcl.argv(), wcl.envp()); -} -#else -int main(int argc, char* argv[], char** envp) { - return mongo::mongoeMain(argc, argv, envp); -} -#endif diff --git a/src/mongo/client/embedded/not_implemented.h b/src/mongo/client/embedded/not_implemented.h deleted file mode 100644 index 21c13aee5fc..00000000000 --- a/src/mongo/client/embedded/not_implemented.h +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Copyright (C) 2018 MongoDB Inc. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * - * As a special exception, the copyright holders give permission to link the - * code of portions of this program with the OpenSSL library under certain - * conditions as described in each individual source file and distribute - * linked combinations including the program with the OpenSSL library. You - * must comply with the GNU Affero General Public License in all respects - * for all of the code used other than as permitted herein. If you modify - * file(s) with this exception, you may extend this exception to your - * version of the file(s), but you are not obligated to do so. If you do not - * wish to do so, delete this exception statement from your version. If you - * delete this exception statement from all source files in the program, - * then also delete it in the license file. - */ - -#pragma once - -#include "mongo/util/assert_util.h" - -/** - * A utility macro to report meaningful information about attempts to invoke unimplemented - * functionality in embedded builds. - */ -#define UASSERT_NOT_IMPLEMENTED \ - const std::string _functionName = __FUNCTION__; \ - uasserted(ErrorCodes::NotImplemented, \ - str::stream() << "Not implemented for embedded: " << _functionName) diff --git a/src/mongo/client/embedded/replication_coordinator_embedded.cpp b/src/mongo/client/embedded/replication_coordinator_embedded.cpp deleted file mode 100644 index bc53da429d7..00000000000 --- a/src/mongo/client/embedded/replication_coordinator_embedded.cpp +++ /dev/null @@ -1,438 +0,0 @@ -/** - * Copyright (C) 2018 MongoDB Inc. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * - * As a special exception, the copyright holders give permission to link the - * code of portions of this program with the OpenSSL library under certain - * conditions as described in each individual source file and distribute - * linked combinations including the program with the OpenSSL library. You - * must comply with the GNU Affero General Public License in all respects for - * all of the code used other than as permitted herein. If you modify file(s) - * with this exception, you may extend this exception to your version of the - * file(s), but you are not obligated to do so. If you do not wish to do so, - * delete this exception statement from your version. If you delete this - * exception statement from all source files in the program, then also delete - * it in the license file. - */ - -#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kReplication - -#include "mongo/platform/basic.h" - -#include "mongo/client/embedded/replication_coordinator_embedded.h" - -#include "mongo/client/embedded/not_implemented.h" -#include "mongo/db/repl/repl_set_config.h" - -namespace mongo { -namespace embedded { - -using namespace repl; - -ReplicationCoordinatorEmbedded::ReplicationCoordinatorEmbedded(ServiceContext* service) - : _service(service) {} - -ReplicationCoordinatorEmbedded::~ReplicationCoordinatorEmbedded() = default; - -void ReplicationCoordinatorEmbedded::startup(OperationContext* opCtx) {} - -void ReplicationCoordinatorEmbedded::shutdown(OperationContext* opCtx) {} - -const ReplSettings& ReplicationCoordinatorEmbedded::getSettings() const { - static ReplSettings _settings; - return _settings; -} - -ReplicationCoordinator::Mode ReplicationCoordinatorEmbedded::getReplicationMode() const { - return ReplicationCoordinator::Mode::modeNone; -} - -bool ReplicationCoordinatorEmbedded::isMasterForReportingPurposes() { - return true; -} - -bool ReplicationCoordinatorEmbedded::canAcceptWritesForDatabase(OperationContext* opCtx, - StringData dbName) { - return true; -} - -bool ReplicationCoordinatorEmbedded::canAcceptWritesForDatabase_UNSAFE(OperationContext* opCtx, - StringData dbName) { - return true; -} - -bool ReplicationCoordinatorEmbedded::canAcceptWritesFor(OperationContext* opCtx, - const NamespaceString& ns) { - return true; -} - -bool ReplicationCoordinatorEmbedded::canAcceptWritesFor_UNSAFE(OperationContext* opCtx, - const NamespaceString& ns) { - return true; -} - -Status ReplicationCoordinatorEmbedded::checkCanServeReadsFor(OperationContext* opCtx, - const NamespaceString& ns, - bool slaveOk) { - return Status::OK(); -} - -Status ReplicationCoordinatorEmbedded::checkCanServeReadsFor_UNSAFE(OperationContext* opCtx, - const NamespaceString& ns, - bool slaveOk) { - return Status::OK(); -} - -bool ReplicationCoordinatorEmbedded::isInPrimaryOrSecondaryState() const { - return false; -} - -bool ReplicationCoordinatorEmbedded::shouldRelaxIndexConstraints(OperationContext* opCtx, - const NamespaceString& ns) { - return false; -} - -bool ReplicationCoordinatorEmbedded::getMaintenanceMode() { - return false; -} - -WriteConcernOptions ReplicationCoordinatorEmbedded::getGetLastErrorDefault() { - return WriteConcernOptions(); -} - -bool ReplicationCoordinatorEmbedded::isReplEnabled() const { - return false; -} - -WriteConcernOptions ReplicationCoordinatorEmbedded::populateUnsetWriteConcernOptionsSyncMode( - WriteConcernOptions wc) { - WriteConcernOptions writeConcern(wc); - writeConcern.syncMode = WriteConcernOptions::SyncMode::NONE; - return writeConcern; -} - -bool ReplicationCoordinatorEmbedded::buildsIndexes() { - return true; -} - -OpTime ReplicationCoordinatorEmbedded::getCurrentCommittedSnapshotOpTime() const { - UASSERT_NOT_IMPLEMENTED; -} - -void ReplicationCoordinatorEmbedded::appendDiagnosticBSON(mongo::BSONObjBuilder*) { - UASSERT_NOT_IMPLEMENTED; -} - -void ReplicationCoordinatorEmbedded::appendConnectionStats( - executor::ConnectionPoolStats* stats) const { - UASSERT_NOT_IMPLEMENTED; -} - -MemberState ReplicationCoordinatorEmbedded::getMemberState() const { - UASSERT_NOT_IMPLEMENTED; -} - -Status ReplicationCoordinatorEmbedded::waitForMemberState(MemberState, Milliseconds) { - UASSERT_NOT_IMPLEMENTED; -} - -Seconds ReplicationCoordinatorEmbedded::getSlaveDelaySecs() const { - UASSERT_NOT_IMPLEMENTED; -} - -void ReplicationCoordinatorEmbedded::clearSyncSourceBlacklist() { - UASSERT_NOT_IMPLEMENTED; -} - -Status ReplicationCoordinatorEmbedded::setFollowerMode(const MemberState&) { - UASSERT_NOT_IMPLEMENTED; -} - -ReplicationCoordinator::ApplierState ReplicationCoordinatorEmbedded::getApplierState() { - UASSERT_NOT_IMPLEMENTED; -} - -void ReplicationCoordinatorEmbedded::signalDrainComplete(OperationContext*, long long) { - UASSERT_NOT_IMPLEMENTED; -} - -Status ReplicationCoordinatorEmbedded::waitForDrainFinish(Milliseconds) { - UASSERT_NOT_IMPLEMENTED; -} - -void ReplicationCoordinatorEmbedded::signalUpstreamUpdater() { - UASSERT_NOT_IMPLEMENTED; -} - -void ReplicationCoordinatorEmbedded::setMyHeartbeatMessage(const std::string&) { - UASSERT_NOT_IMPLEMENTED; -} - -void ReplicationCoordinatorEmbedded::setMyLastAppliedOpTimeForward(const OpTime&, DataConsistency) { - UASSERT_NOT_IMPLEMENTED; -} - -void ReplicationCoordinatorEmbedded::setMyLastDurableOpTimeForward(const OpTime&) { - UASSERT_NOT_IMPLEMENTED; -} - -void ReplicationCoordinatorEmbedded::setMyLastAppliedOpTime(const OpTime&) { - UASSERT_NOT_IMPLEMENTED; -} - -void ReplicationCoordinatorEmbedded::setMyLastDurableOpTime(const OpTime&) { - UASSERT_NOT_IMPLEMENTED; -} - -void ReplicationCoordinatorEmbedded::resetMyLastOpTimes() { - UASSERT_NOT_IMPLEMENTED; -} - -OpTime ReplicationCoordinatorEmbedded::getMyLastAppliedOpTime() const { - UASSERT_NOT_IMPLEMENTED; -} - -OpTime ReplicationCoordinatorEmbedded::getMyLastDurableOpTime() const { - UASSERT_NOT_IMPLEMENTED; -} - -Status ReplicationCoordinatorEmbedded::waitUntilOpTimeForRead(OperationContext*, - const ReadConcernArgs&) { - UASSERT_NOT_IMPLEMENTED; -} - -Status ReplicationCoordinatorEmbedded::waitUntilOpTimeForReadUntil(OperationContext*, - const ReadConcernArgs&, - boost::optional<Date_t>) { - UASSERT_NOT_IMPLEMENTED; -} - -ReplicationCoordinator::StatusAndDuration ReplicationCoordinatorEmbedded::awaitReplication( - OperationContext*, const OpTime&, const WriteConcernOptions&) { - UASSERT_NOT_IMPLEMENTED; -} - -Status ReplicationCoordinatorEmbedded::stepDown(OperationContext*, - const bool, - const Milliseconds&, - const Milliseconds&) { - UASSERT_NOT_IMPLEMENTED; -} - -OID ReplicationCoordinatorEmbedded::getElectionId() { - UASSERT_NOT_IMPLEMENTED; -} - -int ReplicationCoordinatorEmbedded::getMyId() const { - UASSERT_NOT_IMPLEMENTED; -} - -Status ReplicationCoordinatorEmbedded::resyncData(OperationContext*, bool) { - UASSERT_NOT_IMPLEMENTED; -} - -StatusWith<BSONObj> ReplicationCoordinatorEmbedded::prepareReplSetUpdatePositionCommand() const { - UASSERT_NOT_IMPLEMENTED; -} - -Status ReplicationCoordinatorEmbedded::processReplSetGetStatus(BSONObjBuilder*, - ReplSetGetStatusResponseStyle) { - UASSERT_NOT_IMPLEMENTED; -} - -void ReplicationCoordinatorEmbedded::fillIsMasterForReplSet(IsMasterResponse*) { - UASSERT_NOT_IMPLEMENTED; -} - -void ReplicationCoordinatorEmbedded::appendSlaveInfoData(BSONObjBuilder*) { - UASSERT_NOT_IMPLEMENTED; -} - -ReplSetConfig ReplicationCoordinatorEmbedded::getConfig() const { - UASSERT_NOT_IMPLEMENTED; -} - -void ReplicationCoordinatorEmbedded::processReplSetGetConfig(BSONObjBuilder*) { - UASSERT_NOT_IMPLEMENTED; -} - -void ReplicationCoordinatorEmbedded::processReplSetMetadata(const rpc::ReplSetMetadata&) { - UASSERT_NOT_IMPLEMENTED; -} - -void ReplicationCoordinatorEmbedded::cancelAndRescheduleElectionTimeout() { - UASSERT_NOT_IMPLEMENTED; -} - -Status ReplicationCoordinatorEmbedded::setMaintenanceMode(bool) { - UASSERT_NOT_IMPLEMENTED; -} - -Status ReplicationCoordinatorEmbedded::processReplSetSyncFrom(OperationContext*, - const HostAndPort&, - BSONObjBuilder*) { - UASSERT_NOT_IMPLEMENTED; -} - -Status ReplicationCoordinatorEmbedded::processReplSetFreeze(int, BSONObjBuilder*) { - UASSERT_NOT_IMPLEMENTED; -} - -Status ReplicationCoordinatorEmbedded::processHeartbeat(const ReplSetHeartbeatArgs&, - ReplSetHeartbeatResponse*) { - UASSERT_NOT_IMPLEMENTED; -} - -Status ReplicationCoordinatorEmbedded::processReplSetReconfig(OperationContext*, - const ReplSetReconfigArgs&, - BSONObjBuilder*) { - UASSERT_NOT_IMPLEMENTED; -} - -Status ReplicationCoordinatorEmbedded::processReplSetInitiate(OperationContext*, - const BSONObj&, - BSONObjBuilder*) { - UASSERT_NOT_IMPLEMENTED; -} - -Status ReplicationCoordinatorEmbedded::abortCatchupIfNeeded() { - UASSERT_NOT_IMPLEMENTED; -} - -Status ReplicationCoordinatorEmbedded::processReplSetFresh(const ReplSetFreshArgs&, - BSONObjBuilder*) { - UASSERT_NOT_IMPLEMENTED; -} - -Status ReplicationCoordinatorEmbedded::processReplSetElect(const ReplSetElectArgs&, - BSONObjBuilder*) { - UASSERT_NOT_IMPLEMENTED; -} - -Status ReplicationCoordinatorEmbedded::processReplSetUpdatePosition(const UpdatePositionArgs&, - long long*) { - UASSERT_NOT_IMPLEMENTED; -} - -std::vector<HostAndPort> ReplicationCoordinatorEmbedded::getHostsWrittenTo(const OpTime&, bool) { - UASSERT_NOT_IMPLEMENTED; -} - -std::vector<HostAndPort> ReplicationCoordinatorEmbedded::getOtherNodesInReplSet() const { - UASSERT_NOT_IMPLEMENTED; -} - -Status ReplicationCoordinatorEmbedded::checkIfWriteConcernCanBeSatisfied( - const WriteConcernOptions&) const { - UASSERT_NOT_IMPLEMENTED; -} - -Status ReplicationCoordinatorEmbedded::checkReplEnabledForCommand(BSONObjBuilder*) { - return Status(ErrorCodes::NoReplicationEnabled, "no replication on embedded"); -} - -HostAndPort ReplicationCoordinatorEmbedded::chooseNewSyncSource(const OpTime&) { - UASSERT_NOT_IMPLEMENTED; -} - -void ReplicationCoordinatorEmbedded::blacklistSyncSource(const HostAndPort&, Date_t) { - UASSERT_NOT_IMPLEMENTED; -} - -void ReplicationCoordinatorEmbedded::resetLastOpTimesFromOplog(OperationContext*, DataConsistency) { - UASSERT_NOT_IMPLEMENTED; -} - -bool ReplicationCoordinatorEmbedded::shouldChangeSyncSource( - const HostAndPort&, const rpc::ReplSetMetadata&, boost::optional<rpc::OplogQueryMetadata>) { - UASSERT_NOT_IMPLEMENTED; -} - -void ReplicationCoordinatorEmbedded::advanceCommitPoint(const OpTime&) { - UASSERT_NOT_IMPLEMENTED; -} - -OpTime ReplicationCoordinatorEmbedded::getLastCommittedOpTime() const { - UASSERT_NOT_IMPLEMENTED; -} - -Status ReplicationCoordinatorEmbedded::processReplSetRequestVotes(OperationContext*, - const ReplSetRequestVotesArgs&, - ReplSetRequestVotesResponse*) { - UASSERT_NOT_IMPLEMENTED; -} - -void ReplicationCoordinatorEmbedded::prepareReplMetadata(const BSONObj&, - const OpTime&, - BSONObjBuilder*) const { - UASSERT_NOT_IMPLEMENTED; -} - -bool ReplicationCoordinatorEmbedded::isV1ElectionProtocol() const { - UASSERT_NOT_IMPLEMENTED; -} - -bool ReplicationCoordinatorEmbedded::getWriteConcernMajorityShouldJournal() { - UASSERT_NOT_IMPLEMENTED; -} - -Status ReplicationCoordinatorEmbedded::processHeartbeatV1(const ReplSetHeartbeatArgsV1&, - ReplSetHeartbeatResponse*) { - UASSERT_NOT_IMPLEMENTED; -} - -void ReplicationCoordinatorEmbedded::summarizeAsHtml(ReplSetHtmlSummary*) { - UASSERT_NOT_IMPLEMENTED; -} - -long long ReplicationCoordinatorEmbedded::getTerm() { - UASSERT_NOT_IMPLEMENTED; -} - -Status ReplicationCoordinatorEmbedded::updateTerm(OperationContext*, long long) { - UASSERT_NOT_IMPLEMENTED; -} - -void ReplicationCoordinatorEmbedded::waitUntilSnapshotCommitted(OperationContext*, - const Timestamp&) { - UASSERT_NOT_IMPLEMENTED; -} - -size_t ReplicationCoordinatorEmbedded::getNumUncommittedSnapshots() { - UASSERT_NOT_IMPLEMENTED; -} - -void ReplicationCoordinatorEmbedded::dropAllSnapshots() { - UASSERT_NOT_IMPLEMENTED; -} - -Status ReplicationCoordinatorEmbedded::stepUpIfEligible() { - UASSERT_NOT_IMPLEMENTED; -} - -ReplSettings::IndexPrefetchConfig ReplicationCoordinatorEmbedded::getIndexPrefetchConfig() const { - UASSERT_NOT_IMPLEMENTED; -} - -void ReplicationCoordinatorEmbedded::setIndexPrefetchConfig( - const ReplSettings::IndexPrefetchConfig) { - UASSERT_NOT_IMPLEMENTED; -} - -void ReplicationCoordinatorEmbedded::signalDropPendingCollectionsRemovedFromStorage() { - UASSERT_NOT_IMPLEMENTED; -} - -} // namespace embedded -} // namespace mongo diff --git a/src/mongo/client/embedded/replication_coordinator_embedded.h b/src/mongo/client/embedded/replication_coordinator_embedded.h deleted file mode 100644 index c30cb6a77c8..00000000000 --- a/src/mongo/client/embedded/replication_coordinator_embedded.h +++ /dev/null @@ -1,243 +0,0 @@ -/** - * Copyright (C) 2018 MongoDB Inc. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * - * As a special exception, the copyright holders give permission to link the - * code of portions of this program with the OpenSSL library under certain - * conditions as described in each individual source file and distribute - * linked combinations including the program with the OpenSSL library. You - * must comply with the GNU Affero General Public License in all respects for - * all of the code used other than as permitted herein. If you modify file(s) - * with this exception, you may extend this exception to your version of the - * file(s), but you are not obligated to do so. If you do not wish to do so, - * delete this exception statement from your version. If you delete this - * exception statement from all source files in the program, then also delete - * it in the license file. - */ - -#pragma once - -#include "mongo/db/repl/replication_coordinator.h" - -namespace mongo { -namespace embedded { - -class ReplicationCoordinatorEmbedded final : public repl::ReplicationCoordinator { - -public: - ReplicationCoordinatorEmbedded(ServiceContext* serviceContext); - ~ReplicationCoordinatorEmbedded(); - - ReplicationCoordinatorEmbedded(ReplicationCoordinatorEmbedded&) = delete; - ReplicationCoordinatorEmbedded& operator=(ReplicationCoordinatorEmbedded&) = delete; - - // Members that are implemented and safe to call of public ReplicationCoordinator API - - void startup(OperationContext* opCtx) override; - - void shutdown(OperationContext* opCtx) override; - - // Returns the ServiceContext where this instance runs. - ServiceContext* getServiceContext() override { - return _service; - } - - const repl::ReplSettings& getSettings() const override; - - Mode getReplicationMode() const override; - bool getMaintenanceMode() override; - - bool isReplEnabled() const override; - bool isMasterForReportingPurposes() override; - bool isInPrimaryOrSecondaryState() const override; - - bool canAcceptWritesForDatabase(OperationContext* opCtx, StringData dbName) override; - bool canAcceptWritesForDatabase_UNSAFE(OperationContext* opCtx, StringData dbName) override; - - bool canAcceptWritesFor(OperationContext* opCtx, const NamespaceString& ns) override; - bool canAcceptWritesFor_UNSAFE(OperationContext* opCtx, const NamespaceString& ns) override; - - Status checkCanServeReadsFor(OperationContext* opCtx, - const NamespaceString& ns, - bool slaveOk) override; - Status checkCanServeReadsFor_UNSAFE(OperationContext* opCtx, - const NamespaceString& ns, - bool slaveOk) override; - - bool shouldRelaxIndexConstraints(OperationContext* opCtx, const NamespaceString& ns) override; - - WriteConcernOptions getGetLastErrorDefault() override; - - WriteConcernOptions populateUnsetWriteConcernOptionsSyncMode(WriteConcernOptions wc) override; - - bool buildsIndexes() override; - - // Not implemented members that should not be called. Will assert or invariant. - - - repl::MemberState getMemberState() const override; - - Status waitForMemberState(repl::MemberState, Milliseconds) override; - - Seconds getSlaveDelaySecs() const override; - - void clearSyncSourceBlacklist() override; - - repl::ReplicationCoordinator::StatusAndDuration awaitReplication( - OperationContext*, const repl::OpTime&, const WriteConcernOptions&) override; - - Status stepDown(OperationContext*, bool, const Milliseconds&, const Milliseconds&) override; - - Status checkIfWriteConcernCanBeSatisfied(const WriteConcernOptions&) const override; - - void setMyLastAppliedOpTime(const repl::OpTime&) override; - void setMyLastDurableOpTime(const repl::OpTime&) override; - - void setMyLastAppliedOpTimeForward(const repl::OpTime&, DataConsistency) override; - void setMyLastDurableOpTimeForward(const repl::OpTime&) override; - - void resetMyLastOpTimes() override; - - void setMyHeartbeatMessage(const std::string&) override; - - repl::OpTime getMyLastAppliedOpTime() const override; - repl::OpTime getMyLastDurableOpTime() const override; - - Status waitUntilOpTimeForReadUntil(OperationContext*, - const repl::ReadConcernArgs&, - boost::optional<Date_t>) override; - - Status waitUntilOpTimeForRead(OperationContext*, const repl::ReadConcernArgs&) override; - - OID getElectionId() override; - - int getMyId() const override; - - Status setFollowerMode(const repl::MemberState&) override; - - ApplierState getApplierState() override; - - void signalDrainComplete(OperationContext*, long long) override; - - Status waitForDrainFinish(Milliseconds) override; - - void signalUpstreamUpdater() override; - - Status resyncData(OperationContext*, bool) override; - - StatusWith<BSONObj> prepareReplSetUpdatePositionCommand() const override; - - Status processReplSetGetStatus(BSONObjBuilder*, ReplSetGetStatusResponseStyle) override; - - void fillIsMasterForReplSet(repl::IsMasterResponse*) override; - - void appendSlaveInfoData(BSONObjBuilder*) override; - - repl::ReplSetConfig getConfig() const override; - - void processReplSetGetConfig(BSONObjBuilder*) override; - - void processReplSetMetadata(const rpc::ReplSetMetadata&) override; - - void advanceCommitPoint(const repl::OpTime& committedOpTime) override; - - void cancelAndRescheduleElectionTimeout() override; - - Status setMaintenanceMode(bool) override; - - Status processReplSetSyncFrom(OperationContext*, const HostAndPort&, BSONObjBuilder*) override; - - Status processReplSetFreeze(int, BSONObjBuilder*) override; - - Status processHeartbeat(const repl::ReplSetHeartbeatArgs&, - repl::ReplSetHeartbeatResponse*) override; - - Status processReplSetReconfig(OperationContext*, - const ReplSetReconfigArgs&, - BSONObjBuilder*) override; - - Status processReplSetInitiate(OperationContext*, const BSONObj&, BSONObjBuilder*) override; - - Status processReplSetFresh(const ReplSetFreshArgs&, BSONObjBuilder*) override; - - Status processReplSetElect(const ReplSetElectArgs& args, BSONObjBuilder* response) override; - - Status processReplSetUpdatePosition(const repl::UpdatePositionArgs&, long long*) override; - - std::vector<HostAndPort> getHostsWrittenTo(const repl::OpTime&, bool) override; - - std::vector<HostAndPort> getOtherNodesInReplSet() const override; - - Status checkReplEnabledForCommand(BSONObjBuilder*) override; - - - HostAndPort chooseNewSyncSource(const repl::OpTime&) override; - - void blacklistSyncSource(const HostAndPort&, Date_t) override; - - void resetLastOpTimesFromOplog(OperationContext*, DataConsistency) override; - - bool shouldChangeSyncSource(const HostAndPort&, - const rpc::ReplSetMetadata&, - boost::optional<rpc::OplogQueryMetadata>) override; - - repl::OpTime getLastCommittedOpTime() const override; - - Status processReplSetRequestVotes(OperationContext*, - const repl::ReplSetRequestVotesArgs&, - repl::ReplSetRequestVotesResponse*) override; - - void prepareReplMetadata(const BSONObj&, const repl::OpTime&, BSONObjBuilder*) const override; - - Status processHeartbeatV1(const repl::ReplSetHeartbeatArgsV1&, - repl::ReplSetHeartbeatResponse*) override; - - bool isV1ElectionProtocol() const override; - - bool getWriteConcernMajorityShouldJournal() override; - - void summarizeAsHtml(repl::ReplSetHtmlSummary*) override; - - void dropAllSnapshots() override; - - long long getTerm() override; - - Status updateTerm(OperationContext*, long long) override; - - repl::OpTime getCurrentCommittedSnapshotOpTime() const override; - - void waitUntilSnapshotCommitted(OperationContext*, const Timestamp&) override; - - void appendDiagnosticBSON(BSONObjBuilder*) override; - - void appendConnectionStats(executor::ConnectionPoolStats* stats) const override; - - size_t getNumUncommittedSnapshots() override; - - repl::ReplSettings::IndexPrefetchConfig getIndexPrefetchConfig() const override; - void setIndexPrefetchConfig(const repl::ReplSettings::IndexPrefetchConfig) override; - - Status stepUpIfEligible() override; - - Status abortCatchupIfNeeded() override; - - void signalDropPendingCollectionsRemovedFromStorage() final; - -private: - // Back pointer to the ServiceContext that has started the instance. - ServiceContext* const _service; -}; - -} // namespace embedded -} // namespace mongo diff --git a/src/mongo/client/embedded/service_context_embedded.cpp b/src/mongo/client/embedded/service_context_embedded.cpp deleted file mode 100644 index cbb8de4bdde..00000000000 --- a/src/mongo/client/embedded/service_context_embedded.cpp +++ /dev/null @@ -1,87 +0,0 @@ -/** - * Copyright (C) 2018 MongoDB Inc. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * - * As a special exception, the copyright holders give permission to link the - * code of portions of this program with the OpenSSL library under certain - * conditions as described in each individual source file and distribute - * linked combinations including the program with the OpenSSL library. You - * must comply with the GNU Affero General Public License in all respects for - * all of the code used other than as permitted herein. If you modify file(s) - * with this exception, you may extend this exception to your version of the - * file(s), but you are not obligated to do so. If you do not wish to do so, - * delete this exception statement from your version. If you delete this - * exception statement from all source files in the program, then also delete - * it in the license file. - */ - -#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kStorage - -#include "mongo/platform/basic.h" - -#include "mongo/base/init.h" -#include "mongo/base/initializer.h" -#include "mongo/client/embedded/service_context_embedded.h" -#include "mongo/client/embedded/service_entry_point_embedded.h" -#include "mongo/db/client.h" -#include "mongo/db/concurrency/lock_state.h" -#include "mongo/db/operation_context.h" -#include "mongo/db/service_context_registrar.h" -#include "mongo/db/storage/storage_engine.h" -#include "mongo/db/storage/storage_engine_lock_file.h" -#include "mongo/db/storage/storage_engine_metadata.h" -#include "mongo/db/storage/storage_options.h" -#include "mongo/stdx/memory.h" -#include "mongo/util/log.h" -#include "mongo/util/map_util.h" -#include "mongo/util/mongoutils/str.h" -#include "mongo/util/scopeguard.h" -#include "mongo/util/system_clock_source.h" -#include "mongo/util/system_tick_source.h" - -namespace mongo { -namespace { -ServiceContextRegistrar serviceContextCreator([]() { - auto service = std::make_unique<ServiceContextMongoEmbedded>(); - service->setServiceEntryPoint(std::make_unique<ServiceEntryPointEmbedded>(service.get())); - service->setTickSource(std::make_unique<SystemTickSource>()); - service->setFastClockSource(std::make_unique<SystemClockSource>()); - service->setPreciseClockSource(std::make_unique<SystemClockSource>()); - return service; -}); -} // namespace - -extern bool _supportsDocLocking; - -ServiceContextMongoEmbedded::ServiceContextMongoEmbedded() = default; - -ServiceContextMongoEmbedded::~ServiceContextMongoEmbedded() = default; - -std::unique_ptr<OperationContext> ServiceContextMongoEmbedded::_newOpCtx(Client* client, - unsigned opId) { - invariant(&cc() == client); - auto opCtx = stdx::make_unique<OperationContext>(client, opId); - - if (isMMAPV1()) { - opCtx->setLockState(stdx::make_unique<MMAPV1LockerImpl>()); - } else { - opCtx->setLockState(stdx::make_unique<DefaultLockerImpl>()); - } - - opCtx->setRecoveryUnit(getStorageEngine()->newRecoveryUnit(), - WriteUnitOfWork::RecoveryUnitState::kNotInUnitOfWork); - return opCtx; -} - -} // namespace mongo diff --git a/src/mongo/client/embedded/service_context_embedded.h b/src/mongo/client/embedded/service_context_embedded.h deleted file mode 100644 index 3f697ec9a91..00000000000 --- a/src/mongo/client/embedded/service_context_embedded.h +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Copyright (C) 2018 MongoDB Inc. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * - * As a special exception, the copyright holders give permission to link the - * code of portions of this program with the OpenSSL library under certain - * conditions as described in each individual source file and distribute - * linked combinations including the program with the OpenSSL library. You - * must comply with the GNU Affero General Public License in all respects for - * all of the code used other than as permitted herein. If you modify file(s) - * with this exception, you may extend this exception to your version of the - * file(s), but you are not obligated to do so. If you do not wish to do so, - * delete this exception statement from your version. If you delete this - * exception statement from all source files in the program, then also delete - * it in the license file. - */ - -#pragma once - -#include "mongo/db/service_context.h" - -namespace mongo { - -class Client; -class StorageEngineLockFile; - -class ServiceContextMongoEmbedded final : public ServiceContext { -public: - ServiceContextMongoEmbedded(); - - ~ServiceContextMongoEmbedded(); - -private: - std::unique_ptr<OperationContext> _newOpCtx(Client* client, unsigned opId) override; -}; - -} // namespace mongo diff --git a/src/mongo/client/embedded/service_entry_point_embedded.cpp b/src/mongo/client/embedded/service_entry_point_embedded.cpp deleted file mode 100644 index 257235a7332..00000000000 --- a/src/mongo/client/embedded/service_entry_point_embedded.cpp +++ /dev/null @@ -1,109 +0,0 @@ -/** - * Copyright (C) 2018 MongoDB Inc. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * - * As a special exception, the copyright holders give permission to link the - * code of portions of this program with the OpenSSL library under certain - * conditions as described in each individual source file and distribute - * linked combinations including the program with the OpenSSL library. You - * must comply with the GNU Affero General Public License in all respects for - * all of the code used other than as permitted herein. If you modify file(s) - * with this exception, you may extend this exception to your version of the - * file(s), but you are not obligated to do so. If you do not wish to do so, - * delete this exception statement from your version. If you delete this - * exception statement from all source files in the program, then also delete - * it in the license file. - */ - -#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kCommand - -#include "mongo/platform/basic.h" - -#include "mongo/client/embedded/service_entry_point_embedded.h" - -#include "mongo/base/checked_cast.h" -#include "mongo/bson/mutable/document.h" -#include "mongo/db/audit.h" -#include "mongo/db/auth/authorization_session.h" -#include "mongo/db/auth/impersonation_session.h" -#include "mongo/db/client.h" -#include "mongo/db/command_can_run_here.h" -#include "mongo/db/commands.h" -#include "mongo/db/concurrency/global_lock_acquisition_tracker.h" -#include "mongo/db/curop.h" -#include "mongo/db/curop_metrics.h" -#include "mongo/db/cursor_manager.h" -#include "mongo/db/dbdirectclient.h" -#include "mongo/db/initialize_operation_session_info.h" -#include "mongo/db/introspect.h" -#include "mongo/db/jsobj.h" -#include "mongo/db/lasterror.h" -#include "mongo/db/logical_clock.h" -#include "mongo/db/logical_session_id.h" -#include "mongo/db/logical_session_id_helpers.h" -#include "mongo/db/logical_time_validator.h" -#include "mongo/db/query/find.h" -#include "mongo/db/read_concern.h" -#include "mongo/db/repl/optime.h" -#include "mongo/db/repl/read_concern_args.h" -#include "mongo/db/repl/repl_client_info.h" -#include "mongo/db/service_entry_point_common.h" -#include "mongo/db/stats/counters.h" -#include "mongo/db/stats/top.h" -#include "mongo/rpc/factory.h" -#include "mongo/rpc/get_status_from_command_result.h" -#include "mongo/rpc/message.h" -#include "mongo/rpc/metadata.h" -#include "mongo/rpc/metadata/config_server_metadata.h" -#include "mongo/rpc/metadata/logical_time_metadata.h" -#include "mongo/rpc/metadata/oplog_query_metadata.h" -#include "mongo/rpc/metadata/repl_set_metadata.h" -#include "mongo/rpc/metadata/sharding_metadata.h" -#include "mongo/rpc/metadata/tracking_metadata.h" -#include "mongo/rpc/op_msg.h" -#include "mongo/rpc/reply_builder_interface.h" -#include "mongo/s/grid.h" -#include "mongo/util/fail_point_service.h" -#include "mongo/util/log.h" -#include "mongo/util/scopeguard.h" - -namespace mongo { - -class ServiceEntryPointEmbedded::Hooks : public ServiceEntryPointCommon::Hooks { -public: - bool lockedForWriting() const override { - return false; - } - - void waitForReadConcern(OperationContext*, - const CommandInvocation*, - const OpMsgRequest&) const override {} - - void waitForWriteConcern(OperationContext*, - const CommandInvocation*, - const repl::OpTime&, - BSONObjBuilder&) const override {} - - void waitForLinearizableReadConcern(OperationContext*) const override {} - - void uassertCommandDoesNotSpecifyWriteConcern(const BSONObj&) const override {} - - void attachCurOpErrInfo(OperationContext*, const BSONObj&) const override {} -}; - -DbResponse ServiceEntryPointEmbedded::handleRequest(OperationContext* opCtx, const Message& m) { - return ServiceEntryPointCommon::handleRequest(opCtx, m, Hooks{}); -} - -} // namespace mongo diff --git a/src/mongo/client/embedded/service_entry_point_embedded.h b/src/mongo/client/embedded/service_entry_point_embedded.h deleted file mode 100644 index 1f0c7af475f..00000000000 --- a/src/mongo/client/embedded/service_entry_point_embedded.h +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Copyright (C) 2018 MongoDB Inc. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * - * As a special exception, the copyright holders give permission to link the - * code of portions of this program with the OpenSSL library under certain - * conditions as described in each individual source file and distribute - * linked combinations including the program with the OpenSSL library. You - * must comply with the GNU Affero General Public License in all respects for - * all of the code used other than as permitted herein. If you modify file(s) - * with this exception, you may extend this exception to your version of the - * file(s), but you are not obligated to do so. If you do not wish to do so, - * delete this exception statement from your version. If you delete this - * exception statement from all source files in the program, then also delete - * it in the license file. - */ - -#pragma once - -#include "mongo/base/disallow_copying.h" -#include "mongo/transport/service_entry_point_impl.h" - -namespace mongo { - -/** - * The entry point into mongod. Just a wrapper around assembleResponse. - */ -class ServiceEntryPointEmbedded final : public ServiceEntryPointImpl { - MONGO_DISALLOW_COPYING(ServiceEntryPointEmbedded); - -public: - using ServiceEntryPointImpl::ServiceEntryPointImpl; - DbResponse handleRequest(OperationContext* opCtx, const Message& request) override; - -private: - class Hooks; -}; - -} // namespace mongo |