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

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