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

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