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

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