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

Last change on this file since 19672 was 19455, checked in by tbretz, 6 years ago
I directly split now filog lename and log path into the two resources, this is more transparent for the user.
File size: 10.3 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 auto n = fs::path(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.filename().string()), "Name of local log-file")
35 ("logpath", var<string>(n.parent_path().string()), "Path to log-files")
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 cerr << "Writing logfile to '" << (path/file).string() << endl;
159
160 if (!wout.OpenLogFile((path/file).string(), conf.Get<bool>("append-log")))
161 win << kYellow << "WARNING - Couldn't open log-file " << (path/file).string() << ": " << strerror(errno) << endl;
162 }
163
164 S io_service(wout);
165
166 const Time now;
167 io_service.Write(now, "/----------------------- Program ------------------------");
168 io_service.Write(now, "| Program: " PACKAGE_STRING " ("+prgname+":"+to_string(getpid())+")");
169 io_service.Write(now, "| CallPath: "+prgpath);
170 io_service.Write(now, "| Compiled: " __DATE__ " " __TIME__ );
171 io_service.Write(now, "| Revision: " REVISION);
172 io_service.Write(now, "| DIM: v"+to_string(DIM_VERSION_NUMBER/100)+"r"+to_string(DIM_VERSION_NUMBER%100)+" ("+io_service.GetName()+")");
173 io_service.Write(now, "| Contact: " PACKAGE_BUGREPORT);
174 io_service.Write(now, "| URL: " PACKAGE_URL);
175 io_service.Write(now, "| Start: "+now.GetAsStr("%c"));
176 io_service.Write(now, "\\----------------------- Options ------------------------");
177 const multimap<string,string> mmap = conf.GetOptions();
178 for (auto it=mmap.begin(); it!=mmap.end(); it++)
179 io_service.Write(now, ": "+it->first+(it->second.empty()?"":" = ")+it->second);
180
181 const map<string,string> &args = conf.GetOptions<string>("arg:");
182 if (!args.empty())
183 {
184 io_service.Write(now, "------------------------ Arguments ----------------------", MessageImp::kMessage);
185
186 for (auto it=args.begin(); it!=args.end(); it++)
187 {
188 ostringstream str;
189 str.setf(ios_base::left);
190 str << ": " << it->first << " = " << it->second;
191 io_service.Write(now, str.str(), MessageImp::kMessage);
192 }
193 }
194
195 io_service.Write(now, "\\------------------- Evaluating options -----------------");
196 const int rc = io_service.EvalOptions(conf);
197 if (rc>=0)
198 {
199 ostringstream str;
200 str << "Exit triggered by EvalOptions with rc=" << rc;
201 io_service.Write(now, str.str(), rc==0?MessageImp::kInfo:MessageImp::kError);
202 return rc;
203 }
204
205 const map<string,string> &wco = conf.GetWildcardOptions();
206 if (!wco.empty())
207 {
208 io_service.Write(now, "------------- Unrecognized wildcard options -------------", MessageImp::kWarn);
209
210 size_t max = 0;
211 for (auto it=wco.begin(); it!=wco.end(); it++)
212 if (it->second.length()>max)
213 max = it->second.length();
214
215 for (auto it=wco.begin(); it!=wco.end(); it++)
216 {
217 ostringstream str;
218 str.setf(ios_base::left);
219 str << setw(max+1) << it->second << " : " << it->first;
220 io_service.Write(now, str.str(), MessageImp::kWarn);
221 }
222 io_service.Write(now, "Unrecognized options found, will exit with rc=127", MessageImp::kError);
223 return 127;
224 }
225
226 io_service.Message("==================== Starting main loop =================");
227
228 if (conf.Has("console") || !conf.Get<bool>("null"))
229 {
230 wout.SetNullOutput(null);
231 wout.SetBacklog(backlog);
232 }
233
234 shell.SetReceiver(io_service);
235
236 int ret = 0;
237 thread t(bind(Main::Thread, &io_service, dummy, ref(ret)));
238
239 // Wait until state machine is ready (The only case I can imagine
240 // in which the state will never chane is when DIM triggers
241 // an exit before the state machine has been started at all.
242 // Hopefully checking the readline (see Threed) should fix
243 // that -- difficult to test.)
244 while ((io_service.GetCurrentState()<StateMachineImp::kSM_Ready ||
245 !io_service.MessageQueueEmpty()) && !shell.IsStopped())
246 usleep(1);
247
248 // Execute command line commands
249 const vector<string> v1 = conf.Vec<string>("cmd");
250 for (vector<string>::const_iterator it=v1.begin(); it!=v1.end(); it++)
251 shell.ProcessLine(*it);
252
253 const vector<string> v2 = conf.Vec<string>("exec");
254 for (vector<string>::const_iterator it=v2.begin(); it!=v2.end(); it++)
255 shell.Execute(*it, args);
256
257 // Run the shell if no immediate exit was requested
258 if (!conf.Get<bool>("quit"))
259 shell.Run();
260
261 io_service.Stop(); // Signal Loop-thread to stop
262 // io_service.Close(); // Obsolete, done by the destructor
263 // wout << "join: " << t.timed_join(boost::posix_time::milliseconds(0)) << endl;
264
265 // Wait until the StateMachine has finished its thread
266 // before returning and destroying the dim objects which might
267 // still be in use.
268 t.join();
269
270 return ret;
271 }
272}
273
274#endif
Note: See TracBrowser for help on using the repository browser.