Protocols: Move __THROW__ macro to MMSException header file
[remote/remote-mci.git] / mcs / moteserver.cc
blobf082a32599836f243682d2ad19fdd22343689c03
1 #include "FileDescriptor.h"
2 #include "SessionListener.h"
3 #include "HostListener.h"
4 #include "database.h"
5 #include "MMSException.h"
6 #include "macros.h"
7 #include <exception>
8 #include <unistd.h>
9 #include "libutil/File.h"
10 #include "libutil/Config.h"
12 using namespace remote;
13 using namespace remote::mcs;
14 using namespace remote::util;
16 std::string dbName = "REMOTE";
17 std::string dbHost = "localhost";
18 std::string dbUser = "remote_admin";
19 std::string dbPassword = "remote";
20 std::string logFile = "/var/log/remote-mcs.log";
21 std::string errorFile = "/var/log/remote-mcs-error.log";
22 std::string pidFile = "/var/run/remote-mcs.pid";
23 uint16_t sessionPort = 10000;
24 uint16_t moteHostPort = 10001;
25 bool daemonize = false;
27 void handleExit()
29 log("Shutting down\n");
30 remove(pidFile.c_str());
33 int main(int argc,char** argv)
35 std::ostringstream oss;
36 std::string pid;
37 bool eCode = true;
38 Config config("remote-mcs", "/etc/remote-mcs.cfg");
40 config("daemonize", &daemonize, "Run as daemon");
41 config("pidFile", &pidFile, "Path to PID file");
42 config("dbName", &dbName, "Database user name");
43 config("dbHost", &dbHost, "Database host name");
44 config("dbUser", &dbUser, "Database user name");
45 config("dbPassword", &dbPassword, "Database password");
46 config("sessionPort", &sessionPort, "Port number for sessions");
47 config("moteHostPort", &moteHostPort, "Port number for mote hosts");
48 config("logFile", &logFile, "Path to log file when running as a daemon");
49 config("errorFile", &errorFile, "Path to error file when running as a daemon");
51 config("sessionListenerPort", "sessionPort");
52 config("hostListenerPort", "moteHostPort");
53 config("log-file", "logFile");
54 config("errorlog-file", "errorFile");
56 if (!config.read(argc, argv))
57 return EXIT_FAILURE;
59 if (daemonize) {
60 printf("Daemonizing!\n");
61 if (fork()) exit(0);
62 setsid();
63 fclose(stdin);
64 close(1);
65 // reopen stdout
66 if (!freopen(logFile.c_str(), "a", stdout)) {
67 fprintf(stderr, "Unable to open file %s for logging! Bailing out!\n", logFile.c_str());
68 return -1;
70 if (!freopen(errorFile.c_str(), "a", stderr)) {
71 return -1;
75 log("Starting mote server\n");
77 atexit(handleExit);
79 oss << getpid() << std::endl;
80 pid = oss.str();
82 if (!File::writeFile(pidFile, pid.c_str(), pid.size()))
83 log("Failed to create .pid file\n");
85 do {
86 dbConn.connect(dbName, dbHost, dbUser, dbPassword);
87 log("Connected to database\n");
88 Mote::resetDb();
89 log("Deleted old mote data\n");
90 Session::resetDb();
91 log("Deleted old session data\n");
92 HostListener hostListener(moteHostPort);
93 SessionListener sessionListener(sessionPort);
94 log("Entering service loop\n");
95 eCode = FileDescriptor::serviceLoop();
96 } while (eCode);