source: trunk/FACT++/src/scheduler.cc@ 11113

Last change on this file since 11113 was 11056, checked in by tbretz, 13 years ago
Removed RunDim and replaces it with RunShell and LocalStream
File size: 32.1 KB
Line 
1#include <vector>
2
3#include <boost/bind.hpp>
4#if BOOST_VERSION < 104400
5#if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ > 4))
6#undef BOOST_HAS_RVALUE_REFS
7#endif
8#endif
9#include <boost/thread.hpp>
10#include <boost/regex.hpp>
11
12#include <mysql++/mysql++.h>
13
14#include "Dim.h"
15#include "Time.h"
16#include "Event.h"
17#include "Shell.h"
18#include "StateMachineDim.h"
19#include "Connection.h"
20#include "Configuration.h"
21#include "Timers.h"
22#include "Console.h"
23#include "Converter.h"
24#include "LocalControl.h"
25
26#include "tools.h"
27
28using namespace std;
29using namespace boost::gregorian;
30using namespace boost::posix_time;
31
32// things to be done/checked/changed
33// * --schedule-database should be required
34// * move definition of config parameters to AutoScheduler class
35// + read in from config
36// * in some (all?) loops iterator over vector can be replaced by counter
37
38// other things to do
39//
40// define what to transmit as info/warn/error
41
42
43// config parameters:
44// mintime
45// runtimec
46// runtimep
47// repostime
48
49// missing:
50//
51// calculate time for std obs
52// calculate sun set/rise
53//
54// return errors and other otherput from sendcommand to webinterface
55
56// in which cases should the scheduler go in error state?
57// when db is unavailable
58// does one also need a 'set scheduler to ready' function then?
59// do we want any error state at all?
60
61
62// =========================================================================
63
64template <class T>
65class AutoScheduler : public T
66{
67 bool fNextIsPreview;
68public:
69 enum states_t
70 {
71 kSM_Scheduling=1,
72 kSM_Comitting,
73 };
74
75 struct ObservationParameters
76 {
77 int obskey;
78 int obsmode;
79 int obstype;
80 int splitflag;
81 int telsetup;
82 float fluxweight;
83 float slope;
84 float flux;
85 float ra;
86 float dec;
87 ptime start;
88 ptime stop;
89 time_duration duration_db;
90 string sourcename;
91 int sourcekey;
92 };
93
94 struct FixedObs
95 {
96 int obskey;
97 int sourcekey;
98 string sourcename;
99 int obsmode;
100 int obstype;
101 int telsetup;
102 float ra;
103 float dec;
104 ptime start;
105 ptime stop;
106 };
107
108 // will need other types of obs
109 // FloatingObs (duration < stop-start + splitflag no)
110 // FloatingSplittedObs (duration < stop-start + splitflag yes)
111 // FixedSlot, i.e. just block a time slot
112
113 struct StdObs
114 {
115 int obskey_std;
116 int sourcekey_std;
117 string sourcename_std;
118 int obsmode_std;
119 int obstype_std;
120 int telsetup_std;
121 float fluxweight_std;
122 float slope_std;
123 float flux_std;
124 float ra_std;
125 float dec_std;
126 ptime obsstdstart;
127 ptime obsstdstop;
128 };
129
130 struct ScheduledObs
131 {
132 int obskey_obs;
133 int sourcekey_obs;
134 string sourcename_obs;
135 int obsmode_obs;
136 int obstype_obs;
137 int telsetup_obs;
138 ptime obsstart;
139 ptime obsstop;
140 };
141
142 struct ScheduledRun
143 {
144 //int runnumber; // to be seen, if runnumber is needed
145 int obskey_run;
146 int runtype;
147 int sourcekey_run;
148 string sourcename_run;//for convenience
149 int obsmode_run;
150 int obstype_run;
151 int telsetup_run;
152 ptime runstart;
153 ptime runstop;
154 };
155
156 int fSessionId;
157 string fDatabase;
158 string fDBName;
159 int fDurationCalRun; //unit: minutes
160 int fDurationPedRun; //unit: minutes
161 int fDurationRepos; //unit: minutes
162
163 int Schedule()
164 {
165 bool error = false;
166
167 time_duration runtimec(0, fDurationCalRun, 0);
168 time_duration runtimep(0, fDurationPedRun, 0);
169 time_duration repostime(0, fDurationRepos, 0);
170 time_duration mintime(1, 0, 0);
171
172 const ptime startsched(microsec_clock::local_time());
173 const ptime stopsched=startsched+years(1);
174
175 ostringstream str;
176 str << "Scheduling for the period from " << startsched << " to " << stopsched;
177 T::Message(str);
178
179 static const boost::regex expr("(([[:word:].-]+)(:(.+))?@)?([[:word:].-]+)(:([[:digit:]]+))?(/([[:word:].-]+))");
180 // 2: user
181 // 4: pass
182 // 5: server
183 // 7: port
184 // 9: db
185
186 boost::smatch what;
187 if (!boost::regex_match(fDatabase, what, expr, boost::match_extra))
188 {
189 ostringstream msg;
190 msg << "Regex to parse database '" << fDatabase << "' empty.";
191 T::Error(msg);
192 return T::kSM_Error;
193 }
194
195 if (what.size()!=10)
196 {
197 ostringstream msg;
198 msg << "Parsing database name failed: '" << fDatabase << "'";
199 T::Error(msg);
200 return T::kSM_Error;
201 }
202
203 const string user = what[2];
204 const string passwd = what[4];
205 const string server = what[5];
206 const string db = fDBName.empty() ? what[9] : fDBName;
207 const int port = atoi(string(what[7]).c_str());
208
209 ostringstream dbnamemsg;
210 dbnamemsg << "Scheduling started -> using database " << fDBName << ".";
211 T::Message(dbnamemsg);
212
213 str.str("");
214 str << "Connecting to '";
215 if (!user.empty())
216 str << user << "@";
217 str << server;
218 if (port)
219 str << ":" << port;
220 if (!db.empty())
221 str << "/" << db;
222 str << "'";
223 T::Info(str);
224
225 mysqlpp::Connection conn(db.c_str(), server.c_str(), user.c_str(), passwd.c_str(), port);
226 /* throws exceptions
227 if (!conn.connected())
228 {
229 ostringstream msg;
230 msg << "MySQL connection error: " << conn.error();
231 T::Error(msg);
232 return T::kSM_Error;
233 }*/
234
235 // get observation parameters from DB
236 // maybe order by priority?
237 const mysqlpp::StoreQueryResult res =
238 conn.query("SELECT fObservationKEY, fStartTime, fStopTime, fDuration, fSourceName, fSourceKEY, fSplitFlag, fFluxWeight, fSlope, fFlux, fRightAscension, fDeclination, fObservationModeKEY, fObservationTypeKEY , fTelescopeSetupKEY FROM ObservationParameters LEFT JOIN Source USING(fSourceKEY) ORDER BY fStartTime").store();
239 // FIXME: Maybe we have to check for a successfull
240 // query but an empty result
241 /* thorws exceptions?
242 if (!res)
243 {
244 ostringstream msg;
245 msg << "MySQL query failed: " << query.error();
246 T::Error(msg);
247 return T::kSM_Error;
248 }*/
249
250 str.str("");
251 str << "Found " << res.num_rows() << " Observation Parameter sets.";
252 T::Debug(str);
253
254 ObservationParameters olist[res.num_rows()];
255 vector<FixedObs> obsfixedlist;
256 vector<StdObs> obsstdlist;
257 vector<ScheduledObs> obslist;
258 vector<ScheduledRun> runlist;
259
260 // loop over observation parameters from DB
261 // fill these parameters into FixedObs and StdObs
262 int counter=0;
263 int counter2=0;
264 int counter3=0;
265 cout << "Obs: <obskey> <sourcename>(<sourcekey>, <fluxweight>) from <starttime> to <stoptime>" << endl;
266 for (vector<mysqlpp::Row>::const_iterator v=res.begin(); v<res.end(); v++)
267 {
268 cout << " Obs: " << (*v)[0].c_str() << " " << (*v)[4].c_str() << "(" << (*v)[5].c_str() << flush;
269 cout << ", " << (*v)[7].c_str() << ")" << flush;
270 cout << " from " << (*v)[1].c_str() << " to " << (*v)[2].c_str() << endl;
271
272 //0: obskey
273 //1: startime
274 //2: stoptime
275 //3: duration
276 //4: sourcename
277 //5: sourcekey
278 //6: splitflag
279 //7: fluxweight
280 //8: slope
281 //9: flux
282 //10: ra
283 //11: dec
284 //12: obsmode
285 //13: obstype
286 //14: telsetup
287 stringstream t1;
288 stringstream t2;
289 stringstream t3;
290 t1 << (*v)[1].c_str();
291 t2 << (*v)[2].c_str();
292 t3 << (*v)[3].c_str();
293
294 //boost::posix_time::time_duration mintime(0,conf.Get<int>("mintime"), 0);
295 t1 >> Time::sql >> olist[counter].start;
296 t2 >> Time::sql >> olist[counter].stop;
297 t3 >> olist[counter].duration_db;
298 const time_period period(olist[counter].start, olist[counter].stop);
299
300 olist[counter].sourcename=(*v)[4].c_str();
301 olist[counter].sourcekey=(*v)[5];
302
303 if (!(*v)[0].is_null())
304 olist[counter].obskey=(*v)[0];
305 if (!(*v)[12].is_null())
306 olist[counter].obsmode=(*v)[12];
307 if (!(*v)[13].is_null())
308 olist[counter].obstype=(*v)[13];
309 if (!(*v)[14].is_null())
310 olist[counter].telsetup=(*v)[14];
311 if (!(*v)[6].is_null())
312 olist[counter].splitflag=(*v)[6];
313 if (!(*v)[7].is_null())
314 olist[counter].fluxweight=(*v)[7];
315 else
316 olist[counter].fluxweight=0;//set fluxweight to 0 for check below
317 if (!(*v)[8].is_null())
318 olist[counter].slope=(*v)[8];
319 if (!(*v)[9].is_null())
320 olist[counter].flux=(*v)[9];
321 if (!(*v)[10].is_null())
322 olist[counter].ra=(*v)[10];
323 if (!(*v)[11].is_null())
324 olist[counter].dec=(*v)[11];
325
326 // time_duration cannot be used, as only up to 99 hours are handeled
327 const time_duration duration = period.length();
328
329 /*
330 if (olist[counter].stoptime < olist[counter].starttime+mintime)
331 cout << " ====> WARN: Observation too short. " << endl;
332
333 if (olist[counter].starttime.is_not_a_date_time())
334 cout << " WARN: starttime not a date_time. " << endl;
335 else
336 cout << " start: " << Time::sql << olist[counter].starttime << endl;
337 if (olist[counter].stoptime.is_not_a_date_time())
338 cout << " WARN: stoptime not a date_time. " << endl;
339 else
340 cout << " stop: " << Time::sql << olist[counter].stoptime << endl;
341 if (!(olist[counter].starttime.is_not_a_date_time() || olist[counter].stoptime.is_not_a_date_time()))
342 cout << " diff: " << period << endl;
343 if (olist[counter].stoptime < olist[counter].starttime)
344 cout << " ====> WARN: stop time (" << olist[counter].stoptime << ") < start time (" << olist[counter].starttime << "). " << endl;
345 cout << "diff: " << duration << flush;
346 cout << "dur_db: " << olist[counter].duration_db << endl;
347 */
348
349 // always filled: obstype
350 //
351 // fixed observations:
352 // filled: starttime, stoptime
353 // not filled: fluxweight
354 // maybe filled: obsmode, telsetup, source (not filled for FixedSlotObs)
355 // maybe filled: duration (filled for FloatingObs and FloatingSplittedObs)
356 // maybe filled: splitflag (filled for FloatingSplittedObs)
357 //
358 // std observations:
359 // filled: fluxweight, telsetup, obsmore, source
360 // not filled: starttime, stoptime, duration
361
362 // fixed observations
363 if (!(olist[counter].stop.is_not_a_date_time()
364 && olist[counter].start.is_not_a_date_time())
365 && olist[counter].fluxweight==0
366 )
367 {
368 obsfixedlist.resize(counter2+1);
369 obsfixedlist[counter2].start=olist[counter].start;
370 obsfixedlist[counter2].stop=olist[counter].stop;
371 obsfixedlist[counter2].sourcename=olist[counter].sourcename;
372 obsfixedlist[counter2].obskey=olist[counter].obskey;
373 obsfixedlist[counter2].obstype=olist[counter].obstype;
374 obsfixedlist[counter2].obsmode=olist[counter].obsmode;
375 obsfixedlist[counter2].telsetup=olist[counter].telsetup;
376 obsfixedlist[counter2].sourcekey=olist[counter].sourcekey;
377 obsfixedlist[counter2].ra=olist[counter].ra;
378 obsfixedlist[counter2].dec=olist[counter].dec;
379 counter2++;
380 }
381
382 // std obs
383 if (olist[counter].stop.is_not_a_date_time()
384 && olist[counter].start.is_not_a_date_time()
385 && olist[counter].fluxweight>0
386 )
387 {
388 obsstdlist.resize(counter3+1);
389 obsstdlist[counter3].sourcename_std=olist[counter].sourcename;
390 obsstdlist[counter3].obskey_std=olist[counter].obskey;
391 obsstdlist[counter3].obsmode_std=olist[counter].obsmode;
392 obsstdlist[counter3].obstype_std=olist[counter].obstype;
393 obsstdlist[counter3].telsetup_std=olist[counter].telsetup;
394 obsstdlist[counter3].sourcekey_std=olist[counter].sourcekey;
395 obsstdlist[counter3].fluxweight_std=olist[counter].fluxweight;
396 obsstdlist[counter3].flux_std=olist[counter].flux;
397 obsstdlist[counter3].slope_std=olist[counter].slope;
398 obsstdlist[counter3].ra_std=olist[counter].ra;
399 obsstdlist[counter3].dec_std=olist[counter].dec;
400 counter3++;
401 }
402
403 counter++;
404 }
405 ostringstream fixedobsmsg;
406 fixedobsmsg << obsfixedlist.size() << " fixed observations found. ";
407 T::Message(fixedobsmsg);
408 cout << obsfixedlist.size() << " fixed observations found. " << endl;
409
410 ostringstream stdobsmsg;
411 stdobsmsg << obsstdlist.size() << " standard observations found. ";
412 T::Message(stdobsmsg);
413 cout << obsstdlist.size() << " standard observations found. " << endl;
414
415 // loop to add the fixed observations to the ScheduledObs list
416 // performed checks:
417 // * overlap of fixed observations: the overlap is split half-half
418 // * check for scheduling time range: only take into account fixed obs within the range
419 // missing checks and evaluation
420 // * check for mintime (pb with overlap checks)
421 // * check for sun
422 // * check for moon
423 counter2=0;
424 int skipcounter=0;
425 ptime finalobsfixedstart;
426 ptime finalobsfixedstop;
427 time_duration delta0(0,0,0);
428
429 cout << "Fixed Observations: " << endl;
430 for (struct vector<FixedObs>::const_iterator vobs=obsfixedlist.begin(); vobs!=obsfixedlist.end(); vobs++)
431 {
432 if (obsfixedlist[counter2].start < startsched
433 || obsfixedlist[counter2].stop > stopsched)
434 {
435 ostringstream skipfixedobsmsg;
436 skipfixedobsmsg << "Skip 1 fixed observation (obskey ";
437 skipfixedobsmsg << obsfixedlist[counter2].obskey;
438 skipfixedobsmsg << ") as it is out of scheduling time range.";
439 T::Message(skipfixedobsmsg);
440
441 counter2++;
442 skipcounter++;
443 continue;
444 }
445 counter3=0;
446
447 time_duration delta1=delta0;
448 time_duration delta2=delta0;
449
450 finalobsfixedstart=obsfixedlist[counter2].start;
451 finalobsfixedstop=obsfixedlist[counter2].stop;
452
453 for (struct vector<FixedObs>::const_iterator vobs5=obsfixedlist.begin(); vobs5!=obsfixedlist.end(); vobs5++)
454 {
455 if (vobs5->start < obsfixedlist[counter2].stop
456 && obsfixedlist[counter2].stop <= vobs5->stop
457 && obsfixedlist[counter2].start <= vobs5->start
458 && counter2!=counter3)
459 {
460 delta1=(obsfixedlist[counter2].stop-vobs5->start)/2;
461 finalobsfixedstop=obsfixedlist[counter2].stop-delta1;
462
463 ostringstream warndelta1;
464 warndelta1 << "Overlap between two fixed observations (";
465 warndelta1 << obsfixedlist[counter2].obskey << " ";
466 warndelta1 << vobs5->obskey << "). The stoptime of ";
467 warndelta1 << obsfixedlist[counter2].obskey << " has been changed.";
468 T::Warn(warndelta1);
469 }
470 if (vobs5->start <= obsfixedlist[counter2].start
471 && obsfixedlist[counter2].start < vobs5->stop
472 && obsfixedlist[counter2].stop >= vobs5->stop
473 && counter2!=counter3)
474 {
475 delta2=(vobs5->stop-obsfixedlist[counter2].start)/2;
476 finalobsfixedstart=obsfixedlist[counter2].start+delta2;
477
478 ostringstream warndelta2;
479 warndelta2 << "Overlap between two fixed observations (";
480 warndelta2 << obsfixedlist[counter2].obskey << " ";
481 warndelta2 << vobs5->obskey << "). The starttime of ";
482 warndelta2 << obsfixedlist[counter2].obskey << " has been changed.";
483
484 T::Warn(warndelta2);
485 }
486 counter3++;
487 }
488
489 const int num=counter2-skipcounter;
490 obslist.resize(num+1);
491 obslist[num].obsstart=finalobsfixedstart;
492 obslist[num].obsstop=finalobsfixedstop;
493 obslist[num].sourcename_obs=obsfixedlist[counter2].sourcename;
494 obslist[num].obsmode_obs=obsfixedlist[counter2].obsmode;
495 obslist[num].obstype_obs=obsfixedlist[counter2].obstype;
496 obslist[num].telsetup_obs=obsfixedlist[counter2].telsetup;
497 obslist[num].sourcekey_obs=obsfixedlist[counter2].sourcekey;
498 obslist[num].obskey_obs=obsfixedlist[counter2].obskey;
499 counter2++;
500
501 cout << " " << vobs->sourcename << " " << vobs->start;
502 cout << " - " << vobs->stop << endl;
503 }
504 ostringstream obsmsg;
505 obsmsg << "Added " << obslist.size() << " fixed observations to ScheduledObs. ";
506 T::Message(obsmsg);
507 cout << "Added " << obslist.size() << " fixed observations to ScheduledObs. " << endl;
508
509 for (int i=0; i<(int)obsstdlist.size(); i++)
510 {
511 for (int j=0; j<(int)obsstdlist.size(); j++)
512 {
513 if (obsstdlist[i].sourcekey_std == obsstdlist[j].sourcekey_std && i!=j)
514 {
515 cout << "One double sourcekey in std observations: " << obsstdlist[j].sourcekey_std << endl;
516 ostringstream errdoublestd;
517 errdoublestd << "One double sourcekey in std observations: " << obsstdlist[j].sourcekey_std << " (" << obsstdlist[j].sourcename_std << ").";
518 T::Error(errdoublestd);
519 T::Message("Scheduling stopped.");
520 return error ? T::kSM_Error : T::kSM_Ready;
521 }
522 }
523 }
524
525 // loop over nights
526 // calculate sunset and sunrise
527 // check if there is already scheduled obs in that night
528 //
529
530 // in this loop the standard observations shall be
531 // checked, evaluated
532 // the observation times shall be calculated
533 // and the observations added to the ScheduledObs list
534 cout << "Standard Observations: " << endl;
535 for (struct vector<StdObs>::const_iterator vobs2=obsstdlist.begin(); vobs2!=obsstdlist.end(); vobs2++)
536 {
537 cout << " " << vobs2->sourcename_std << endl;
538 }
539
540 // in this loop the ScheduledRuns are filled
541 // (only data runs -> no runtype yet)
542 // might be merged with next loop
543 counter2=0;
544 for (struct vector<ScheduledObs>::const_iterator vobs3=obslist.begin(); vobs3!=obslist.end(); vobs3++)
545 {
546 runlist.resize(counter2+1);
547 runlist[counter2].runstart=obslist[counter2].obsstart;
548 runlist[counter2].runstop=obslist[counter2].obsstop;
549 runlist[counter2].sourcename_run=obslist[counter2].sourcename_obs;
550 runlist[counter2].obsmode_run=obslist[counter2].obsmode_obs;
551 runlist[counter2].obstype_run=obslist[counter2].obstype_obs;
552 runlist[counter2].telsetup_run=obslist[counter2].telsetup_obs;
553 runlist[counter2].sourcekey_run=obslist[counter2].sourcekey_obs;
554 runlist[counter2].obskey_run=obslist[counter2].obskey_obs;
555 counter2++;
556 //cout << (*vobs3).sourcename_obs << endl;
557 }
558
559 //delete old scheduled runs from the DB
560 const mysqlpp::SimpleResult res0 =
561 conn.query("DELETE FROM ScheduledRun").execute();
562 // FIXME: Maybe we have to check for a successfull
563 // query but an empty result
564 /* throws exceptions
565 if (!res0)
566 {
567 ostringstream msg;
568 msg << "MySQL query failed: " << query0.error();
569 T::Error(msg);
570 return T::kSM_Error;
571 }*/
572
573 // in this loop the ScheduledRuns are inserted to the DB
574 // before the runtimes are adapted according to
575 // duration of P-Run, C-Run and repositioning
576 counter3=0;
577 int insertcount=0;
578 ptime finalstarttime;
579 ptime finalstoptime;
580 for (struct vector<ScheduledRun>::const_iterator vobs4=runlist.begin(); vobs4!=runlist.end(); vobs4++)
581 {
582 for (int i=2; i<5; i++)
583 {
584 switch(i)
585 {
586 case 2:
587 finalstarttime=runlist[counter3].runstart+repostime+runtimec+runtimep;
588 finalstoptime=runlist[counter3].runstop;
589 break;
590 case 3:
591 finalstarttime=runlist[counter3].runstart+repostime;
592 finalstoptime=runlist[counter3].runstart+runtimep+repostime;
593 break;
594 case 4:
595 finalstarttime=runlist[counter3].runstart+runtimep+repostime;
596 finalstoptime=runlist[counter3].runstart+repostime+runtimep+runtimec;
597 break;
598 }
599 ostringstream q1;
600 //cout << (*vobs4).sourcename_run << endl;
601 q1 << "INSERT ScheduledRun set fStartTime='" << Time::sql << finalstarttime;
602 q1 << "', fStopTime='" << Time::sql << finalstoptime;
603 q1 << "', fSourceKEY='" << (*vobs4).sourcekey_run;
604 q1 << "', fObservationKEY='" << (*vobs4).obskey_run;
605 q1 << "', fRunTypeKEY='" << i;
606 q1 << "', fTelescopeSetupKEY='" << (*vobs4).telsetup_run;
607 q1 << "', fObservationTypeKEY='" << (*vobs4).obstype_run;
608 q1 << "', fObservationModeKEY='" << (*vobs4).obsmode_run;
609 q1 << "'";
610
611 //cout << "executing query: " << q1.str() << endl;
612
613 const mysqlpp::SimpleResult res1 = conn.query(q1.str()).execute();
614 // FIXME: Maybe we have to check for a successfull
615 // query but an empty result
616 /* throws exceptions
617 if (!res1)
618 {
619 ostringstream msg;
620 msg << "MySQL query failed: " << query1.error();
621 T::Error(str);
622 return T::kSM_Error;
623 }*/
624 insertcount++;
625 }
626 counter3++;
627 }
628 ostringstream insertmsg;
629 insertmsg << "Inserted " << insertcount << " runs into the DB.";
630 T::Message(insertmsg);
631 //usleep(3000000);
632 T::Message("Scheduling done.");
633
634 fSessionId = -1;
635
636 return error ? T::kSM_Error : T::kSM_Ready;
637 }
638
639 /*
640 // commit probably done by webinterface
641 int Commit()
642 {
643 ostringstream str;
644 str << "Comitting preview (id=" << fSessionId << ")";
645 T::Message(str);
646
647 usleep(3000000);
648 T::Message("Comitted.");
649
650 fSessionId = -1;
651
652 bool error = false;
653 return error ? T::kSM_Error : T::kSM_Ready;
654 }
655 */
656
657 AutoScheduler(ostream &out=cout) : T(out, "SCHEDULER"), fNextIsPreview(true), fSessionId(-1), fDBName("")
658 {
659 AddStateName(kSM_Scheduling, "Scheduling", "Scheduling in progress.");
660
661 AddEvent(kSM_Scheduling, "SCHEDULE", "C", T::kSM_Ready)
662 ("FIXME FIXME FIXME (explanation for the command)"
663 "|database[string]:FIXME FIXME FIMXE (meaning and format)");
664
665 AddEvent(T::kSM_Ready, "RESET", T::kSM_Error)
666 ("Reset command to get out of the error state");
667
668 //AddEvent(kSM_Comitting, "COMMIT", T::kSM_Ready);
669
670 T::PrintListOfEvents();
671 }
672
673 int Execute()
674 {
675 switch (T::GetCurrentState())
676 {
677 case kSM_Scheduling:
678 try
679 {
680 return Schedule();
681 }
682 catch (const mysqlpp::Exception &e)
683 {
684 T::Error(string("MySQL: ")+e.what());
685 return T::kSM_Error;
686 }
687
688 // This does an autmatic reset (FOR TESTING ONLY)
689 case T::kSM_Error:
690 return T::kSM_Ready;
691
692 //case kSM_Comitting:
693 // return Commit();
694 }
695 return T::GetCurrentState();
696 }
697
698 int Transition(const Event &evt)
699 {
700 switch (evt.GetTargetState())
701 {
702 case kSM_Scheduling:
703 if (evt.GetSize()>0)
704 fDBName = evt.GetText();
705 //case kSM_Comitting:
706 //fSessionId = evt.GetInt();
707 break;
708 }
709
710 return evt.GetTargetState();
711 }
712 int Configure(const Event &)
713 {
714 return T::GetCurrentState();
715 }
716
717 bool SetConfiguration(const Configuration &conf)
718 {
719 fDatabase = conf.Get<string>("schedule-database");
720 fDurationCalRun = conf.Get<int>("duration-cal-run");
721 fDurationPedRun = conf.Get<int>("duration-ped-run");
722 fDurationRepos = conf.Get<int>("duration-repos");
723
724 return true;
725 }
726
727};
728
729
730// ------------------------------------------------------------------------
731
732void RunThread(StateMachineImp *io_service)
733{
734 // This is necessary so that the StateMachien Thread can signal the
735 // Readline to exit
736 io_service->Run();
737 Readline::Stop();
738}
739
740/*
741template<class S>
742int RunDim(Configuration &conf)
743{
744 WindowLog wout;
745
746 ReadlineColor::PrintBootMsg(wout, conf.GetName(), false);
747
748 //log.SetWindow(stdscr);
749 if (conf.Has("log"))
750 if (!wout.OpenLogFile(conf.Get<string>("log")))
751 wout << kRed << "ERROR - Couldn't open log-file " << conf.Get<string>("log") << ": " << strerror(errno) << endl;
752
753 // Start io_service.Run to use the StateMachineImp::Run() loop
754 // Start io_service.run to only use the commandHandler command detaching
755 AutoScheduler<S> io_service(wout);
756 if (!io_service.SetConfiguration(conf))
757 return -1;
758
759 io_service.Run();
760
761 return 0;
762}
763*/
764
765template<class T, class S>
766int RunShell(Configuration &conf)
767{
768 static T shell(conf.GetName().c_str(), conf.Get<int>("console")!=1);
769
770 WindowLog &win = shell.GetStreamIn();
771 WindowLog &wout = shell.GetStreamOut();
772
773 if (conf.Has("log"))
774 if (!wout.OpenLogFile(conf.Get<string>("log")))
775 win << kRed << "ERROR - Couldn't open log-file " << conf.Get<string>("log") << ": " << strerror(errno) << endl;
776
777 AutoScheduler<S> io_service(wout);
778 if (!io_service.SetConfiguration(conf))
779 return -1;
780
781 shell.SetReceiver(io_service);
782
783// boost::thread t(boost::bind(&AutoScheduler<S>::Run, &io_service));
784 boost::thread t(boost::bind(RunThread, &io_service));
785
786 //io_service.SetReady();
787 if (conf.Has("exec"))
788 {
789 const vector<string> v = conf.Get<vector<string>>("exec");
790 for (vector<string>::const_iterator it=v.begin(); it!=v.end(); it++)
791 shell.Execute(*it);
792 }
793
794 shell.Run(); // Run the shell
795 io_service.Stop(); // Signal Loop-thread to stop
796 // io_service.Close(); // Obsolete, done by the destructor
797 // wout << "join: " << t.timed_join(boost::posix_time::milliseconds(0)) << endl;
798
799 // Wait until the StateMachine has finished its thread
800 // before returning and destroying the dim objects which might
801 // still be in use.
802 t.join();
803
804 return 0;
805}
806
807void SetupConfiguration(Configuration &conf)
808{
809 const string n = conf.GetName()+".log";
810
811 //po::options_description config("Program options");
812 po::options_description config("Configuration");
813 config.add_options()
814 ("dns", var<string>("localhost"), "Dim nameserver host name (Overwites DIM_DNS_NODE environment variable)")
815 ("log,l", var<string>(n), "Write log-file")
816 ("no-dim,d", po_switch(), "Disable dim services")
817 ("console,c", var<int>(), "Use console (0=shell, 1=simple buffered, X=simple unbuffered)")
818 ("exec,e", vars<string>(), "Execute one or more scrips at startup");
819
820 po::options_description control("Scheduler options");
821 control.add_options()
822 ("schedule-database", var<string>()
823#if BOOST_VERSION >= 104200
824 ->required()
825#endif
826 , "Database link as in\n\t[user:[password]@][server][:port][/database]\nOverwrites options from the default configuration file.")
827 ("mintime", var<int>(), "minimum observation time")
828 ("duration-cal-run", var<int>()
829#if BOOST_VERSION >= 104200
830 ->required()
831#endif
832 , "duration of calibration run [min]")
833 ("duration-ped-run", var<int>()
834#if BOOST_VERSION >= 104200
835 ->required()
836#endif
837 , "duration of pedestal run [min]")
838 ("duration-repos", var<int>()
839#if BOOST_VERSION >= 104200
840 ->required()
841#endif
842 , "duration of repositioning [min]")
843 ;
844
845 po::positional_options_description p;
846 p.add("schedule-database", 1); // The first positional options
847
848 conf.AddEnv("dns", "DIM_DNS_NODE");
849 conf.AddOptions(config);
850 conf.AddOptions(control);
851 conf.SetArgumentPositions(p);
852}
853
854void PrintUsage()
855{
856 cout <<
857 "The scheduler... TEXT MISSING\n"
858 "\n"
859 "The default is that the program is started without user intercation. "
860 "All actions are supposed to arrive as DimCommands. Using the -c "
861 "option, a local shell can be initialized. With h or help a short "
862 "help message about the usuage can be brought to the screen.\n"
863 "\n"
864 "Usage: scheduler [-c type] [OPTIONS] <schedule-database>\n"
865 " or: scheduler [OPTIONS] <schedule-database>\n";
866 cout << endl;
867}
868
869void PrintHelp()
870{
871 /* Additional help text which is printed after the configuration
872 options goes here */
873}
874
875int main(int argc, const char* argv[])
876{
877 Configuration conf(argv[0]);
878 conf.SetPrintUsage(PrintUsage);
879 SetupConfiguration(conf);
880
881 po::variables_map vm;
882 try
883 {
884 vm = conf.Parse(argc, argv);
885 }
886#if BOOST_VERSION > 104000
887 catch (po::multiple_occurrences &e)
888 {
889 cerr << "Program options invalid due to: " << e.what() << " of '" << e.get_option_name() << "'." << endl;
890 return -1;
891 }
892#endif
893 catch (exception& e)
894 {
895 cerr << "Program options invalid due to: " << e.what() << endl;
896 return -1;
897 }
898
899 if (conf.HasVersion() || conf.HasPrint())
900 return -1;
901
902 if (conf.HasHelp())
903 {
904 PrintHelp();
905 return -1;
906 }
907
908 Dim::Setup(conf.Get<string>("dns"));
909
910// try
911 {
912 // No console access at all
913 if (!conf.Has("console"))
914 {
915 if (conf.Get<bool>("no-dim"))
916 return RunShell<LocalStream, StateMachine>(conf);
917 else
918 return RunShell<LocalStream, StateMachineDim>(conf);
919 }
920 // Cosole access w/ and w/o Dim
921 if (conf.Get<bool>("no-dim"))
922 {
923 if (conf.Get<int>("console")==0)
924 return RunShell<LocalShell, StateMachine>(conf);
925 else
926 return RunShell<LocalConsole, StateMachine>(conf);
927 }
928 else
929 {
930 if (conf.Get<int>("console")==0)
931 return RunShell<LocalShell, StateMachineDim>(conf);
932 else
933 return RunShell<LocalConsole, StateMachineDim>(conf);
934 }
935 }
936/* catch (std::exception& e)
937 {
938 std::cerr << "Exception: " << e.what() << "\n";
939 }*/
940
941 return 0;
942}
Note: See TracBrowser for help on using the repository browser.