1 
2 /**
3  *    Copyright (C) 2018-present MongoDB, Inc.
4  *
5  *    This program is free software: you can redistribute it and/or modify
6  *    it under the terms of the Server Side Public License, version 1,
7  *    as published by MongoDB, Inc.
8  *
9  *    This program is distributed in the hope that it will be useful,
10  *    but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *    Server Side Public License for more details.
13  *
14  *    You should have received a copy of the Server Side Public License
15  *    along with this program. If not, see
16  *    <http://www.mongodb.com/licensing/server-side-public-license>.
17  *
18  *    As a special exception, the copyright holders give permission to link the
19  *    code of portions of this program with the OpenSSL library under certain
20  *    conditions as described in each individual source file and distribute
21  *    linked combinations including the program with the OpenSSL library. You
22  *    must comply with the Server Side Public License in all respects for
23  *    all of the code used other than as permitted herein. If you modify file(s)
24  *    with this exception, you may extend this exception to your version of the
25  *    file(s), but you are not obligated to do so. If you do not wish to do so,
26  *    delete this exception statement from your version. If you delete this
27  *    exception statement from all source files in the program, then also delete
28  *    it in the license file.
29  */
30 
31 #pragma once
32 
33 #include "mongo/db/jsobj.h"
34 #include "mongo/platform/atomic_word.h"
35 #include "mongo/platform/process_id.h"
36 #include "mongo/s/catalog/sharding_catalog_client.h"
37 #include "mongo/stdx/variant.h"
38 #include "mongo/util/net/cidr.h"
39 
40 namespace mongo {
41 
42 const int DEFAULT_UNIX_PERMS = 0700;
43 constexpr size_t DEFAULT_MAX_CONN = 1000000;
44 
45 enum class ClusterRole { None, ShardServer, ConfigServer };
46 
47 struct ServerGlobalParams {
48     std::string binaryName;  // mongod or mongos
49     std::string cwd;         // cwd of when process started
50 
51     int port = DefaultDBPort;  // --port
52     enum { DefaultDBPort = 27017, ConfigServerPort = 27019, ShardServerPort = 27018 };
isDefaultPortServerGlobalParams53     bool isDefaultPort() const {
54         return port == DefaultDBPort;
55     }
56 
57     std::vector<std::string> bind_ips;  // --bind_ip
58     bool enableIPv6 = false;
59     bool rest = false;  // --rest
60 
61     int listenBacklog = 0;  // --listenBacklog, real default is SOMAXCONN
62 
63     bool indexBuildRetry = true;  // --noIndexBuildRetry
64 
65     AtomicBool quiet{false};  // --quiet
66 
67     ClusterRole clusterRole = ClusterRole::None;  // --configsvr/--shardsvr
68 
69     bool cpu = false;  // --cpu show cpu time periodically
70 
71     bool objcheck = true;  // --objcheck
72 
73     int defaultProfile = 0;                // --profile
74     int slowMS = 100;                      // --time in ms that is "slow"
75     double sampleRate = 1.0;               // --samplerate rate at which to sample slow queries
76     int defaultLocalThresholdMillis = 15;  // --localThreshold in ms to consider a node local
77     bool moveParanoia = false;             // for move chunk paranoia
78 
79     bool noUnixSocket = false;    // --nounixsocket
80     bool doFork = false;          // --fork
81     std::string socket = "/tmp";  // UNIX domain socket directory
82     std::string transportLayer;   // --transportLayer (must be either "asio" or "legacy")
83 
84     // --serviceExecutor ("adaptive", "synchronous")
85     std::string serviceExecutor;
86 
87     size_t maxConns = DEFAULT_MAX_CONN;  // Maximum number of simultaneous open connections.
88     std::vector<stdx::variant<CIDR, std::string>> maxConnsOverride;
89     int reservedAdminThreads = 0;
90 
91     int unixSocketPermissions = DEFAULT_UNIX_PERMS;  // permissions for the UNIX domain socket
92 
93     std::string keyFile;           // Path to keyfile, or empty if none.
94     std::string pidFile;           // Path to pid file, or empty if none.
95     std::string timeZoneInfoPath;  // Path to time zone info directory, or empty if none.
96 
97     std::string logpath;            // Path to log file, if logging to a file; otherwise, empty.
98     bool logAppend = false;         // True if logging to a file in append mode.
99     bool logRenameOnRotate = true;  // True if logging should rename log files on rotate
100     bool logWithSyslog = false;     // True if logging to syslog; must not be set if logpath is set.
101     int syslogFacility;             // Facility used when appending messages to the syslog.
102 
103 #ifndef _WIN32
104     ProcessId parentProc;  // --fork pid of initial process
105     ProcessId leaderProc;  // --fork pid of leader process
106 #endif
107 
108     /**
109      * Switches to enable experimental (unsupported) features.
110      */
111     struct ExperimentalFeatures {
ExperimentalFeaturesServerGlobalParams::ExperimentalFeatures112         ExperimentalFeatures() : storageDetailsCmdEnabled(false) {}
113         bool storageDetailsCmdEnabled;  // -- enableExperimentalStorageDetailsCmd
114     } experimental;
115 
116     time_t started = ::time(0);
117 
118     BSONArray argvArray;
119     BSONObj parsedOpts;
120 
121     enum AuthState { kEnabled, kDisabled, kUndefined };
122 
123     AuthState authState = AuthState::kUndefined;
124 
125     bool transitionToAuth = false;  // --transitionToAuth, mixed mode for rolling auth upgrade
126     AtomicInt32 clusterAuthMode;    // --clusterAuthMode, the internal cluster auth mode
127 
128     enum ClusterAuthModes {
129         ClusterAuthMode_undefined,
130         /**
131         * Authenticate using keyfile, accept only keyfiles
132         */
133         ClusterAuthMode_keyFile,
134 
135         /**
136         * Authenticate using keyfile, accept both keyfiles and X.509
137         */
138         ClusterAuthMode_sendKeyFile,
139 
140         /**
141         * Authenticate using X.509, accept both keyfiles and X.509
142         */
143         ClusterAuthMode_sendX509,
144 
145         /**
146         * Authenticate using X.509, accept only X.509
147         */
148         ClusterAuthMode_x509
149     };
150 
151     // for the YAML config, sharding._overrideShardIdentity. Can only be used when in
152     // queryableBackupMode.
153     BSONObj overrideShardIdentity;
154 
155     struct FeatureCompatibility {
156         /**
157          * The combination of the fields in the admin.system.version document in the format
158          * (version, targetVersion) are represented by this enum and determine this node's behavior.
159          *
160          * The legal enum (and featureCompatiblityVersion document) states are:
161          *
162          * kFullyDowngradedTo34
163          * (3.4, Unset): Only 3.4 features are available, and new and existing storage
164          *               engine entries use the 3.4 format
165          *
166          * kUpgradingTo36
167          * (3.4, 3.6): Only 3.4 features are available, but new storage engine entries
168          *             use the 3.6 format, and existing entries may have either the
169          *             3.4 or 3.6 format
170          *
171          * kFullyUpgradedTo36
172          * (3.6, Unset): 3.6 features are available, and new and existing storage
173          *               engine entries use the 3.6 format
174          *
175          * kDowngradingTo34
176          * (3.4, 3.4): Only 3.4 features are available and new storage engine
177          *             entries use the 3.4 format, but existing entries may have
178          *             either the 3.4 or 3.6 format
179          *
180          * kUnsetDefault34Behavior
181          * (Unset, Unset): This is the case on startup before the fCV document is
182          *                 loaded into memory. isVersionInitialized() will return
183          *                 false, and getVersion() will return the default
184          *                 (kFullyDowngradedTo34).
185          *
186          */
187         enum class Version {
188             kFullyDowngradedTo34,
189             kUpgradingTo36,
190             kFullyUpgradedTo36,
191             kDowngradingTo34,
192             kUnsetDefault34Behavior
193         };
194 
195         /**
196          * On startup, the featureCompatibilityVersion may not have been explicitly set yet. This
197          * exposes the actual state of the featureCompatibilityVersion if it is uninitialized.
198          */
isVersionInitializedServerGlobalParams::FeatureCompatibility199         const bool isVersionInitialized() const {
200             return _version.load() != Version::kUnsetDefault34Behavior;
201         }
202 
203         /**
204          * This safe getter for the featureCompatibilityVersion returns a default value when the
205          * version has not yet been set.
206          */
getVersionServerGlobalParams::FeatureCompatibility207         const Version getVersion() const {
208             Version v = _version.load();
209             return (v == Version::kUnsetDefault34Behavior) ? Version::kFullyDowngradedTo34 : v;
210         }
211 
resetServerGlobalParams::FeatureCompatibility212         void reset() {
213             _version.store(Version::kFullyDowngradedTo34);
214         }
215 
setVersionServerGlobalParams::FeatureCompatibility216         void setVersion(Version version) {
217             return _version.store(version);
218         }
219 
220         // This determines whether to give Collections UUIDs upon creation.
isSchemaVersion36ServerGlobalParams::FeatureCompatibility221         const bool isSchemaVersion36() {
222             return (getVersion() == Version::kFullyUpgradedTo36 ||
223                     getVersion() == Version::kUpgradingTo36);
224         }
225 
226     private:
227         AtomicWord<Version> _version{Version::kUnsetDefault34Behavior};
228 
229     } featureCompatibility;
230 
231     // Feature validation differs depending on the role of a mongod in a replica set or
232     // master/slave configuration. Masters/primaries can accept user-initiated writes and
233     // validate based on the feature compatibility version. A secondary/slave (which is not also
234     // a master) always validates in the upgraded mode so that it can sync new features, even
235     // when in the downgraded feature compatibility mode.
236     AtomicWord<bool> validateFeaturesAsMaster{true};
237 
238     std::vector<std::string> disabledSecureAllocatorDomains;
239 
240     bool enableMajorityReadConcern = true;
241 };
242 
243 extern ServerGlobalParams serverGlobalParams;
244 
245 template <typename NameTrait>
246 struct TraitNamedDomain {
pegTraitNamedDomain247     static bool peg() {
248         const auto& dsmd = serverGlobalParams.disabledSecureAllocatorDomains;
249         const auto contains = [&](StringData dt) {
250             return std::find(dsmd.begin(), dsmd.end(), dt) != dsmd.end();
251         };
252         static const bool ret = !(contains("*"_sd) || contains(NameTrait::DomainType));
253         return ret;
254     }
255 };
256 }
257