NCBI C++ ToolKit
bdb_env_keeper.cpp
Go to the documentation of this file.

Go to the SVN repository for this file.

1 /* $Id: bdb_env_keeper.cpp 92153 2020-12-22 17:11:22Z grichenk $
2  * ===========================================================================
3  *
4  * PUBLIC DOMAIN NOTICE
5  * National Center for Biotechnology Information
6  *
7  * This software/database is a "United States Government Work" under the
8  * terms of the United States Copyright Act. It was written as part of
9  * the author's official duties as a United States Government employee and
10  * thus cannot be copyrighted. This software/database is freely available
11  * to the public for use. The National Library of Medicine and the U.S.
12  * Government have not placed any restriction on its use or reproduction.
13  *
14  * Although all reasonable efforts have been taken to ensure the accuracy
15  * and reliability of the software and data, the NLM and the U.S.
16  * Government do not and cannot warrant the performance or results that
17  * may be obtained by using this software or data. The NLM and the U.S.
18  * Government disclaim all warranties, express or implied, including
19  * warranties of performance, merchantability or fitness for any particular
20  * purpose.
21  *
22  * Please cite the author in any work or product based on this material.
23  *
24  * ===========================================================================
25  *
26  * Authors: Anatoliy Kuznetsov
27  *
28  * File Description:
29  * BDB environment keeper server
30  *
31  */
32 
33 #include <ncbi_pch.hpp>
34 #include <corelib/ncbiapp.hpp>
35 #include <corelib/ncbiargs.hpp>
36 #include <corelib/ncbienv.hpp>
37 #include <corelib/ncbi_system.hpp>
40 #include <connect/ncbi_socket.hpp>
41 #include <connect/ncbi_util.h>
42 #include <connect/server.hpp>
43 
44 #include <db/bdb/bdb_util.hpp>
45 #include <db/bdb/bdb_env.hpp>
46 
47 #if defined(NCBI_OS_UNIX)
48 # include <corelib/ncbi_process.hpp>
49 # include <signal.h>
50 #endif
51 
52 
54 
55 #define BDB_ENV_KEEPER_VERSION "0.1.1"
56 
57 #define BDB_ENV_KEEPER_FULL_VERSION \
58  "NCBI BDB Env keeper server version " BDB_ENV_KEEPER_VERSION \
59  " build " __DATE__ " " __TIME__
60 
61 /// Main server class
62 ///
63 ///
65 {
66 public:
69  {}
70  virtual bool ShutdownRequested(void) { return m_ShutdownRequested; }
71  void RequestShutdown(void) { m_ShutdownRequested = true; }
72 private:
73  volatile bool m_ShutdownRequested;
74 };
75 
76 
77 
78 /// @internal
80 
81 
82 
83 /// Actual event (command) responder (session state machine)
84 ///
86 {
87 public:
89  m_Server(server)
90  {
91  }
92  virtual void OnOpen(void);
93  virtual void OnMessage(BUF buf);
94  virtual void OnWrite(void) {}
95 private:
97 };
98 
100 {
101  CSocket& socket = GetSocket();
102  socket.DisableOSSendDelay();
103 }
104 
105 /// @internal
106 static
108 {
109  size_t size = BUF_Size(buf);
110  string ret(size, '\0');
111  BUF_Read(buf, &ret[0], size);
112  return ret;
113 }
114 
115 
117 {
118  CSocket &socket = GetSocket();
119 
120  string cmd = s_ReadStrFromBUF(buf);
121 
122  if (cmd == "VERSION") {
123  string msg = BDB_ENV_KEEPER_FULL_VERSION;
124  msg.append("\n");
125  socket.Write(msg.c_str(), msg.length());
126  } else
127  if (cmd == "SHUT" || cmd == "SHUTDOWN") {
128  string msg = "Shutdown initiated.\n";
129  socket.Write(msg.c_str(), msg.length() - 1);
131  } else {
132  string msg = "Incorrect command.\n";
133  socket.Write(msg.c_str(), msg.length() - 1);
134  }
135 
136  socket.Close();
137 }
138 
139 
141 {
142 public:
144  m_Server(server)
145  {
146  }
149  }
150 private:
152 };
153 
154 
155 // Application
157 {
158 public:
159  virtual void Init(void);
160  virtual int Run(void);
161 };
162 
163 
165 {
166  unique_ptr<CArgDescriptions> arg_desc(new CArgDescriptions);
167 
168  arg_desc->SetUsageContext(GetArguments().GetProgramBasename(),
169  "BDB Environment Keeper");
170 
171  SetupArgDescriptions(arg_desc.release());
172 }
173 
174 // Check for shutdown request every second
175 static STimeout kAcceptTimeout = { 1, 0 };
176 
177 /// @internal
178 extern "C" void Server_SignalHandler(int signum)
179 {
180  if (s_server && (!s_server->ShutdownRequested()) ) {
182  }
183 }
184 
185 
187 {
189 
190  const CNcbiRegistry& reg = GetConfig();
191  bool is_daemon =
192  reg.GetBool("server", "daemon", false, 0, CNcbiRegistry::eReturn);
193 
194 #if defined(NCBI_OS_UNIX)
195  // attempt to get server gracefully shutdown on signal
196  signal( SIGINT, Server_SignalHandler);
197  signal( SIGTERM, Server_SignalHandler);
198 #endif
199 
200 
201 
202 #if defined(NCBI_OS_UNIX)
203  if (is_daemon) {
204  LOG_POST("Entering UNIX daemon mode...");
205  bool daemon
207  if (!daemon) {
208  return 0;
209  }
210 
211  }
212 
213 #endif
214 
215 
216  unique_ptr<CBDB_Env> env(BDB_CreateEnv(reg, "bdb"));
217 
218 // const CArgs& args = GetArgs();
219 
220  unsigned short port =
221  reg.GetInt("server", "port", 9200, 0, CNcbiRegistry::eReturn);
222 
223  SServer_Parameters params;
224  params.init_threads = 1;
225  params.max_threads = 3;
226  params.accept_timeout = &kAcceptTimeout;
227 
228  CBDBEnvKeeperServer server;
229  s_server = &server;
230  server.SetParameters(params);
231 
232  server.AddListener(new CBDBEnvKeeperConnectionFactory(&server), port);
233 
234  server.Run();
235 
236 
237  // Finalization
238  {{
239  if (env->IsTransactional()) {
240  env->ForceTransactionCheckpoint();
241  }
242 
243 
244  if (env->CheckRemove()) {
245  LOG_POST(Info
246  << "Environment has been unmounted and deleted.");
247  } else {
249  << "Environment still in use. Cannot delete it.");
250  }
251  }}
252 
253  return 0;
254 }
255 
256 
258 
260 
261 int main(int argc, const char* argv[])
262 {
263  return CBDBEnvKeeperApp().AppMain(argc, argv);
264 }
Wrapper around Berkeley DB environment structure.
static string s_ReadStrFromBUF(BUF buf)
static CBDBEnvKeeperServer * s_server
int main(int argc, const char *argv[])
void Server_SignalHandler(int signum)
USING_NCBI_SCOPE
#define BDB_ENV_KEEPER_FULL_VERSION
static STimeout kAcceptTimeout
CArgDescriptions –.
Definition: ncbiargs.hpp:541
virtual int Run(void)
Run the application.
virtual void Init(void)
Initialize the application.
IServer_ConnectionHandler * Create(void)
CBDBEnvKeeperServer * m_Server
CBDBEnvKeeperConnectionFactory(CBDBEnvKeeperServer *server)
Actual event (command) responder (session state machine)
virtual void OnWrite(void)
The client is ready to receive data.
virtual void OnMessage(BUF buf)
CBDBEnvKeeperConnectionHandler(CBDBEnvKeeperServer *server)
virtual void OnOpen(void)
Runs in response to an external event [asynchronous].
CBDBEnvKeeperServer * m_Server
Main server class.
virtual bool ShutdownRequested(void)
Runs synchronously between iterations.
volatile bool m_ShutdownRequested
void RequestShutdown(void)
CNcbiRegistry –.
Definition: ncbireg.hpp:913
CServer::
Definition: server.hpp:97
CSocket::
IServer_ConnectionFactory::
Definition: server.hpp:388
IServer_ConnectionHandler::
Definition: server.hpp:226
IServer_LineMessageHandler::
Definition: server.hpp:347
static CS_COMMAND * cmd
Definition: ct_dynamic.c:26
#define false
Definition: bool.h:36
static HENV env
Definition: transaction2.c:38
#define daemon(d, c)
Definition: replacements.h:170
const CNcbiRegistry & GetConfig(void) const
Get the application's cached configuration parameters (read-only).
int AppMain(int argc, const char *const *argv, const char *const *envp=0, EAppDiagStream diag=eDS_Default, const char *conf=NcbiEmptyCStr, const string &name=NcbiEmptyString)
Main function (entry point) for the NCBI application.
Definition: ncbiapp.cpp:819
virtual void SetupArgDescriptions(CArgDescriptions *arg_desc)
Setup the command line argument descriptions.
Definition: ncbiapp.cpp:1195
const CNcbiArguments & GetArguments(void) const
Get the application's cached unprocessed command-line arguments.
CBDB_Env * BDB_CreateEnv(const CNcbiRegistry &reg, const string &section_name)
Create and configure BDB environment using CNcbiRegistry as a parameter container.
Definition: bdb_util.cpp:236
size_t BUF_Size(BUF buf)
Definition: ncbi_buffer.c:84
size_t BUF_Read(BUF buf, void *data, size_t size)
Definition: ncbi_buffer.c:414
#define ERR_POST(message)
Error posting with file, line number information but without error codes.
Definition: ncbidiag.hpp:186
#define LOG_POST(message)
This macro is deprecated and it's strongly recomended to move in all projects (except tests) to macro...
Definition: ncbidiag.hpp:226
void Warning(CExceptionArgs_Base &args)
Definition: ncbiexpt.hpp:1191
void Info(CExceptionArgs_Base &args)
Definition: ncbiexpt.hpp:1185
static TPid Daemonize(const char *logfile=0, TDaemonFlags flags=0)
Go daemon.
@ fDF_KeepCWD
Don't change CWD to "/".
virtual bool GetBool(const string &section, const string &name, bool default_value, TFlags flags=0, EErrAction err_action=eThrow) const
Get boolean value of specified parameter name.
Definition: ncbireg.cpp:391
virtual int GetInt(const string &section, const string &name, int default_value, TFlags flags=0, EErrAction err_action=eThrow) const
Get integer value of specified parameter name.
Definition: ncbireg.cpp:362
@ eReturn
Return default value.
Definition: ncbireg.hpp:203
#define END_NCBI_SCOPE
End previously defined NCBI scope.
Definition: ncbistl.hpp:103
#define BEGIN_NCBI_SCOPE
Define ncbi namespace.
Definition: ncbistl.hpp:100
EIO_Status Close(void)
Close socket.
void DisableOSSendDelay(bool on_off=true)
EIO_Status Write(const void *buf, size_t size, size_t *n_written=0, EIO_WriteMethod how=eIO_WritePersist)
Write to socket.
const STimeout * accept_timeout
Maximum t between exit checks.
Definition: server.hpp:440
void AddListener(IServer_ConnectionFactory *factory, unsigned short port)
Register a listener.
Definition: server.cpp:605
void SetParameters(const SServer_Parameters &new_params)
Definition: server.cpp:618
unsigned int max_threads
Maximum simultaneous threads.
Definition: server.hpp:447
void Run(void)
Enter the main loop.
Definition: server.cpp:771
CSocket & GetSocket(void)
Get underlying socket.
Definition: server.hpp:294
unsigned int init_threads
Number of initial threads.
Definition: server.hpp:446
char * buf
const struct ncbi::grid::netcache::search::fields::SIZE size
Defines process management classes.
Defines the CNcbiApplication and CAppException classes for creating NCBI applications.
Defines command line argument related classes.
Defines unified interface to application:
T signum(T x_)
Framework to create multithreaded network servers with thread-per-request scheduling.
SServer_Parameters::
Definition: server.hpp:434
Timeout structure.
Definition: ncbi_types.h:76
Modified on Sat Apr 13 11:45:19 2024 by modify_doxy.py rev. 669887