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

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