source: trunk/FACT++/src/Main.h@ 17365

Last change on this file since 17365 was 17362, checked in by tbretz, 11 years ago
Added server name to startup message.
File size: 10.0 KB
Line 
1#ifndef FACT_Main
2#define FACT_Main
3
4#include <map>
5#include <thread>
6#include <functional>
7
8#include <boost/filesystem.hpp>
9
10#include "dim.h"
11
12#include "Dim.h"
13#include "Time.h"
14#include "MainImp.h"
15#include "Readline.h"
16#include "WindowLog.h"
17#include "MessageImp.h"
18#include "Configuration.h"
19
20namespace Main
21{
22 using namespace std;
23 namespace fs = boost::filesystem;
24
25 void SetupConfiguration(Configuration &conf)
26 {
27 const string n = conf.GetName()+".log";
28
29 po::options_description config("Program options");
30 config.add_options()
31 ("dns", var<string>("localhost"), "Dim nameserver (overwites DIM_DNS_NODE environment variable)")
32 ("host", var<string>(), "Address with which the Dim nameserver can connect to this host (overwites DIM_HOST_NODE environment variable)")
33 ("log,l", var<string>(n), "Name of local log-file")
34 ("logpath", var<string>(), "Absolute path to log-files (default: excutable's directory)")
35 ("no-log", po_switch(), "Supress log-file")
36 ("append-log", po_bool(), "Append log information to local log-file")
37 ("null", po_switch(), "Suppresses almost all console output - including errors (only available without --console option)")
38 ("console,c", var<int>(), "Use console (0=shell, 1=simple buffered, X=simple unbuffered)")
39 ("cmd", vars<string>(), "Execute one or more commands at startup")
40 ("exec,e", vars<string>(), "Execute one or more scrips at startup ('file:N' - start at label N)")
41 ("arg:*", var<string>(), "Arguments for script execution with --exc, e.g. --arg:ra='12.5436'")
42 ("home", var<string>(), "Path to home directory (used as default for logpath if standard log files not writable)")
43 ("quit", po_switch(), "Quit after startup");
44 ;
45
46 conf.AddEnv("dns", "DIM_DNS_NODE");
47 conf.AddEnv("host", "DIM_HOST_NODE");
48 conf.AddEnv("home", "HOME");
49
50 conf.AddOptions(config);
51 }
52
53 void PrintUsage()
54 {
55 cout <<
56 "Files:\n"
57 "The following files are written by each program by default\n"
58 " program.evt: A log of all executed of skipped events\n"
59 " program.his: The history accessible by Pg-up/dn\n"
60 " program.log: All output piped to the log-stream\n"
61 << endl;
62 }
63
64 template<class T>
65 void PrintHelp()
66 {
67 Dim::Setup();
68
69 ofstream fout("/dev/null");
70
71 T io_service(fout);
72
73 io_service.PrintListOfStates(cout);
74 cout << "\nList of available commands:\n";
75 io_service.PrintListOfEvents(cout);
76 cout << "\n";
77 }
78
79 void Thread(MainImp *io_service, bool dummy, int &rc)
80 {
81 // This is necessary so that the StateMachien Thread can signal the
82 // Readline to exit
83 rc = io_service->Run(dummy);
84 Readline::Stop();
85 }
86
87 template<class T, class S>
88 int execute(Configuration &conf, bool dummy=false)
89 {
90 Dim::Setup(conf.Get<string>("dns"), conf.Has("host")?conf.Get<string>("host"):"");
91
92 // -----------------------------------------------------------------
93 const fs::path program(conf.GetName());
94
95 // Split path to program into path and filename
96 const string prgpath = program.parent_path().string();
97
98#if BOOST_VERSION < 104600
99 const string prgname = program.filename();
100#else
101 const string prgname = program.filename().string();
102#endif
103
104 fs::path path = conf.Has("logpath") ? conf.Get<string>("logpath") : "";
105
106 // No explicit path given
107 if (path.empty())
108 {
109 path = prgpath;
110
111 // default path not accessible
112 if (access(prgpath.empty() ? "." : prgpath.c_str(), W_OK))
113 {
114 path = conf.Get<string>("home");
115 path /= ".fact++";
116 }
117 }
118
119 // Create directories if necessary
120 fs::create_directories(path);
121
122 // -----------------------------------------------------------------
123
124 static T shell((path/prgname).string().c_str(),
125 conf.Has("console") ? conf.Get<int>("console")!=1 : conf.Get<bool>("null"));
126
127 WindowLog &win = shell.GetStreamIn();
128 WindowLog &wout = shell.GetStreamOut();
129
130 // Switching off buffering is not strictly necessary, since
131 // the destructor of shell should flush everything still buffered,
132 // nevertheless it helps to debug problems in the initialization
133 // sequence.
134 const bool backlog = wout.GetBacklog();
135 const bool null = wout.GetNullOutput();
136 if (conf.Has("console") || !conf.Get<bool>("null"))
137 {
138 wout.SetBacklog(false);
139 wout.SetNullOutput(false);
140 wout.Display(true);
141 }
142
143 if (conf.Has("log") && !conf.Get<bool>("no-log"))
144 {
145#if BOOST_VERSION < 104600
146 const fs::path file = fs::path(conf.Get<string>("log")).filename();
147#else
148 const fs::path file = fs::path(conf.Get<string>("log")).filename();
149#endif
150 if (!wout.OpenLogFile((path/file).string(), conf.Get<bool>("append-log")))
151 win << kYellow << "WARNING - Couldn't open log-file " << path.string() << ": " << strerror(errno) << endl;
152 }
153
154 S io_service(wout);
155
156 const Time now;
157 io_service.Write(now, "/----------------------- Program ------------------------");
158 io_service.Write(now, "| Program: "PACKAGE_STRING" ("+prgname+":"+to_string(getpid())+")");
159 io_service.Write(now, "| CallPath: "+prgpath);
160 io_service.Write(now, "| Compiled: "__DATE__" "__TIME__);
161 io_service.Write(now, "| Revision: "REVISION);
162 io_service.Write(now, "| DIM: v"+to_string(DIM_VERSION_NUMBER/100)+"r"+to_string(DIM_VERSION_NUMBER%100)+" ("+io_service.GetName()+")");
163 io_service.Write(now, "| Contact: "PACKAGE_BUGREPORT);
164 io_service.Write(now, "| URL: "PACKAGE_URL);
165 io_service.Write(now, "| Start: "+now.GetAsStr("%c"));
166 io_service.Write(now, "\\----------------------- Options ------------------------");
167 const multimap<string,string> mmap = conf.GetOptions();
168 for (auto it=mmap.begin(); it!=mmap.end(); it++)
169 io_service.Write(now, ": "+it->first+(it->second.empty()?"":" = ")+it->second);
170
171 const map<string,string> &args = conf.GetOptions<string>("arg:");
172 if (!args.empty())
173 {
174 io_service.Write(now, "------------------------ Arguments ----------------------", MessageImp::kMessage);
175
176 for (auto it=args.begin(); it!=args.end(); it++)
177 {
178 ostringstream str;
179 str.setf(ios_base::left);
180 str << ": " << it->first << " = " << it->second;
181 io_service.Write(now, str.str(), MessageImp::kMessage);
182 }
183 }
184
185 io_service.Write(now, "\\------------------- Evaluating options -----------------");
186 const int rc = io_service.EvalOptions(conf);
187 if (rc>=0)
188 {
189 ostringstream str;
190 str << "Exit triggered by EvalOptions with rc=" << rc;
191 io_service.Write(now, str.str(), rc==0?MessageImp::kInfo:MessageImp::kError);
192 return rc;
193 }
194
195 const map<string,string> &wco = conf.GetWildcardOptions();
196 if (!wco.empty())
197 {
198 io_service.Write(now, "------------- Unrecognized wildcard options -------------", MessageImp::kWarn);
199
200 size_t max = 0;
201 for (auto it=wco.begin(); it!=wco.end(); it++)
202 if (it->second.length()>max)
203 max = it->second.length();
204
205 for (auto it=wco.begin(); it!=wco.end(); it++)
206 {
207 ostringstream str;
208 str.setf(ios_base::left);
209 str << setw(max+1) << it->second << " : " << it->first;
210 io_service.Write(now, str.str(), MessageImp::kWarn);
211 }
212 io_service.Write(now, "Unrecognized options found, will exit with rc=127", MessageImp::kError);
213 return 127;
214 }
215
216 io_service.Message("==================== Starting main loop =================");
217
218 if (conf.Has("console") || !conf.Get<bool>("null"))
219 {
220 wout.SetNullOutput(null);
221 wout.SetBacklog(backlog);
222 }
223
224 shell.SetReceiver(io_service);
225
226 // boost::thread t(boost::bind(&AutoScheduler<S>::Run, &io_service));
227 int ret = 0;
228 thread t(bind(Main::Thread, &io_service, dummy, ref(ret)));
229
230 // Wait until state machine is ready (The only case I can imagine
231 // in which the state will never chane is when DIM triggers
232 // an exit before the state machine has been started at all.
233 // Hopefully checking the readline (see Threed) should fix
234 // that -- difficult to test.)
235 while ((io_service.GetCurrentState()<StateMachineImp::kSM_Ready ||
236 !io_service.MessageQueueEmpty()) && !shell.IsStopped())
237 usleep(1);
238
239 // Execute command line commands
240 const vector<string> v1 = conf.Vec<string>("cmd");
241 for (vector<string>::const_iterator it=v1.begin(); it!=v1.end(); it++)
242 shell.ProcessLine(*it);
243
244 const vector<string> v2 = conf.Vec<string>("exec");
245 for (vector<string>::const_iterator it=v2.begin(); it!=v2.end(); it++)
246 shell.Execute(*it, args);
247
248 // Run the shell if no immediate exit was requested
249 if (!conf.Get<bool>("quit"))
250 shell.Run();
251
252 io_service.Stop(); // Signal Loop-thread to stop
253 // io_service.Close(); // Obsolete, done by the destructor
254 // wout << "join: " << t.timed_join(boost::posix_time::milliseconds(0)) << endl;
255
256 // Wait until the StateMachine has finished its thread
257 // before returning and destroying the dim objects which might
258 // still be in use.
259 t.join();
260
261 return ret;
262 }
263}
264
265#endif
Note: See TracBrowser for help on using the repository browser.