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

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