source: flair-src/trunk/lib/FlairCore/src/FrameworkManager_impl.cpp@ 437

Last change on this file since 437 was 424, checked in by Sanahuja Guillaume, 3 years ago

use utmp for autdetecting ip address

File size: 28.4 KB
Line 
1// %flair:license{
2// This file is part of the Flair framework distributed under the
3// CECILL-C License, Version 1.0.
4// %flair:license}
5// created: 2011/08/31
6// filename: FrameworkManager.cpp
7//
8// author: Guillaume Sanahuja
9// Copyright Heudiasyc UMR UTC/CNRS 7253
10//
11// version: $Id: $
12//
13// purpose: Classe de base de la librairie
14//
15//
16/*********************************************************************/
17
18#include "FrameworkManager_impl.h"
19#include "FrameworkManager.h"
20#include "Widget_impl.h"
21#include <unistd.h>
22#include "IODevice.h"
23#include "IODevice_impl.h"
24#include "TabWidget.h"
25#include "Layout.h"
26#include "PushButton.h"
27#include "communication.h"
28#include "config.h"
29#include "Watchdog.h"
30#include <errno.h>
31#include <string.h>
32#include <arpa/inet.h>
33#include <sys/mman.h>
34#include <execinfo.h>
35#include <signal.h>
36#include <fcntl.h>
37#include <utmp.h>
38#ifdef __XENO__
39#include <native/task.h>
40#include <rtdk.h>
41#endif
42
43using namespace std;
44using namespace flair::core;
45using namespace flair::gui;
46
47ui_com *FrameworkManager_impl::com = NULL;
48FrameworkManager_impl *FrameworkManager_impl::_this = NULL;
49
50namespace {
51#ifdef __XENO__
52
53#ifdef SIGDEBUG
54static const char *reason_str[] = {
55 "undefined", "received signal", "invoked syscall", "triggered fault",
56 "affected by priority inversion", "missing mlockall", "runaway thread",
57};
58
59void warn_upon_switch(int sig, siginfo_t *si, void *context) {
60 unsigned int reason = si->si_value.sival_int;
61 void *bt[32];
62 int nentries;
63#ifdef SIGDEBUG_WATCHDOG
64 printf("\nSIGDEBUG received, reason %d: %s\n", reason,
65 reason <= SIGDEBUG_WATCHDOG ? reason_str[reason] : "<unknown>");
66 printf("entering secondary mode\n");
67#endif
68 // Dump a backtrace of the frame which caused the switch to secondary mode:
69 nentries = backtrace(bt, sizeof(bt) / sizeof(bt[0]));
70 backtrace_symbols_fd(bt, nentries, fileno(stdout));
71}
72#else // SIGDEBUG
73void warn_upon_switch(int sig __attribute__((unused))) {
74 void *bt[32];
75 int nentries;
76
77 /* Dump a backtrace of the frame which caused the switch to
78 secondary mode: */
79 nentries = backtrace(bt, sizeof(bt) / sizeof(bt[0]));
80 backtrace_symbols_fd(bt, nentries, fileno(stdout));
81}
82#endif // SIGDEBUG
83#endif //__XENO__
84void seg_fault(int sig __attribute__((unused))) {
85 void *bt[32];
86 int nentries;
87
88 printf("Segmentation fault:\n");
89 /* Dump a backtrace of the frame which caused the segfault: */
90 nentries = backtrace(bt, sizeof(bt) / sizeof(bt[0]));
91 backtrace_symbols_fd(bt, nentries, fileno(stdout));
92
93 exit(1);
94}
95}
96
97FrameworkManager_impl::FrameworkManager_impl(FrameworkManager *self,
98 string name)
99 : Thread(self, "FrameworkManager", FRAMEWORK_TASK_PRIORITY) {
100 this->self = self;
101 is_logging = false;
102 logger_defined = false;
103 disable_errors = false;
104 ui_defined = false;
105 rcv_buf = NULL;
106 gcs_watchdog = NULL;
107 _this = this;
108 tabwidget=NULL;
109
110 // Avoids memory swapping for this program
111 mlockall(MCL_CURRENT | MCL_FUTURE);
112
113 // catch segfault
114 signal(SIGSEGV, seg_fault);
115
116// catch primary->secondary switch
117#ifdef __XENO__
118#ifdef SIGDEBUG
119 struct sigaction sa;
120 sigemptyset(&sa.sa_mask);
121 sa.sa_sigaction = warn_upon_switch;
122 sa.sa_flags = SA_SIGINFO;
123 sigaction(SIGDEBUG, &sa, NULL);
124#else //SIGDEBUG
125 signal(SIGXCPU, warn_upon_switch);
126#endif //SIGDEBUG
127 string task_name = "Framework_" + name;
128
129 // Perform auto-init of rt_print buffers if the task doesn't do so
130 rt_print_auto_init(1);
131 // Initialise the rt_print buffer for this task explicitly
132 rt_print_init(512, task_name.c_str());
133
134 int status = rt_task_shadow(NULL, task_name.c_str(), 10, 0);
135 if (status != 0) {
136 char errorMsg[256];
137 self->Err("rt_task_shadow error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
138 }
139
140#endif //__XENO__
141}
142
143void FrameworkManager_impl::SetConnectionLost(void) {
144 Err("connection lost\n");
145 if(gcs_watchdog!=NULL) gcs_watchdog->SafeStop();
146 connection_lost = true;
147}
148
149FrameworkManager_impl::~FrameworkManager_impl() {
150 // Printf("destruction FrameworkManager_impl\n");
151 int status;
152
153 SafeStop();
154 Join();
155
156 if(gcs_watchdog!=NULL) gcs_watchdog->SafeStop();
157
158 if (rcv_buf != NULL)
159 free(rcv_buf);
160
161 if (logger_defined == true) {
162 continuer = false;
163 (void)pthread_join(log_th, NULL);
164
165 status = DeletePipe(&cmd_pipe);
166 if (status != 0) {
167 char errorMsg[256];
168 Err("Error deleting pipe (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
169 }
170 status = DeletePipe(&data_pipe);
171 if (status != 0) {
172 char errorMsg[256];
173 Err("Error deleting pipe (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
174 }
175
176#ifdef __XENO__
177 status = rt_heap_delete(&log_heap);
178 if (status != 0) {
179 char errorMsg[256];
180 Err("rt_heap_delete error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
181 }
182#endif
183
184 logs.clear();
185 }
186
187 if (file_doc != NULL)
188 xmlFreeDoc(file_doc);
189
190 if (ui_defined)
191 delete top_layout;
192
193 if (com != NULL) {
194 delete com;
195 //avoid waiting on closing if connection is lost
196 if(connection_lost) {
197 bool blocking = false;
198 if (UDT::setsockopt(com_sock, 0, UDT_SNDSYN, &blocking, sizeof(bool)) != 0)
199 Err("UDT::setsockopt error (UDT_SNDSYN)\n");
200 }
201 status = UDT::close(com_sock);
202 if (status != 0)
203 Printf("Error udt::close %s", UDT::getlasterror().getErrorMessage());
204
205 SleepMS(200); // a revoir, sinon UDT::cleanup bloque en RT
206
207 if(connection_lost) {
208 //don't know why?
209 Warn("Cleaning up UDT socket, this can take some time\n");
210 }
211 if (UDT::cleanup() != 0)
212 Err("UDT::cleanup error\n");
213 }
214
215 // Printf("destruction FrameworkManager_impl ok\n");
216}
217
218void FrameworkManager_impl::SetupConnection(string address, uint16_t port,Time watchdogTimeout,
219 size_t rcv_buf_size) {
220 if (com != NULL) {
221 Err("SetupConnection should be called only one time\n");
222 return;
223 }
224 if(address=="autodetect") {
225 Printf("Autodetecting gcs ip address based on ssh connection\n");
226 address=AutoDetectGCS();
227 }
228 this->address=address;
229 this->port=port;
230
231 UDT::startup2(1024*256,1024*256,1024*256);
232 this->rcv_buf_size = rcv_buf_size;
233
234 // socket file_socket, doit être créé en premier, cf station sol
235 Printf("Connecting to FlairGCS on %s:%i\n", address.c_str(), port);
236 //file_sock = GetSocket(address, port);
237 com_sock = GetSocket();
238
239 // receive buffer allocation
240 rcv_buf = (char *)malloc(rcv_buf_size);
241 if (rcv_buf == NULL) {
242 Err("receive buffer malloc error\n");
243 }
244
245 com = new ui_com(this, com_sock);
246
247 Start();
248
249 // watchdog for connection with ground station
250 connection_lost = false;
251 gcs_watchdog = new Watchdog(this, std::bind(&FrameworkManager_impl::SetConnectionLost, this),watchdogTimeout);
252 gcs_watchdog->Start();
253}
254
255string FrameworkManager_impl::AutoDetectGCS(void) {
256 int logsize = 10;//should be sufficient
257 int file;
258 struct utmp log[logsize];
259
260 file = open("/var/run/utmp", O_RDONLY);
261
262//return only first matching occurence
263//TODO: check also log->ut_addr_v6[0]
264 if (file) {
265 int read_size=read(file, &log, sizeof(log));
266 int nb=read_size/sizeof(struct utmp);
267
268 for(int i = 0; i < nb; i++) {
269 //printf("\n ut_user: %s host: %s %x\n ut_type: %ld line %s\n", log[i].ut_user,log[i].ut_host,log[i].ut_addr_v6[0], log[i].ut_type,log[i].ut_line);
270 if(log[i].ut_type==USER_PROCESS) {
271 close(file);
272 return log[i].ut_host;
273 }
274
275 }
276
277 close(file);
278 }
279
280 Err("Failed to run autodetect command\n" );
281 return "";
282}
283
284void FrameworkManager_impl::SetupUserInterface(string xml_file) {
285 ui_defined = true;
286 this->xml_file = xml_file;
287
288 // top_layout=new Layout(NULL,XML_ROOT_ELEMENT,XML_ROOT_TYPE);
289 top_layout = new Layout(NULL, self->ObjectName(), XML_ROOT_TYPE);
290
291 // xml setup of the main widget
292 if (xml_file != "") {
293 xmlNodePtr *file_node = &(((Widget *)(top_layout))->pimpl_->file_node);
294 file_doc = xmlParseFile(xml_file.c_str());
295 if (file_doc == NULL) {
296 self->Warn("XML document not parsed successfully. Creating a new one.\n");
297 file_doc = xmlNewDoc((xmlChar *)"1.0");
298 *file_node = xmlNewNode(NULL, (xmlChar *)XML_ROOT_TYPE);
299 xmlSetProp(*file_node, (xmlChar *)"name",
300 (xmlChar *)ObjectName().c_str());
301 xmlDocSetRootElement(file_doc, *file_node);
302 // PrintXml();
303 } else {
304 *file_node = xmlDocGetRootElement(file_doc);
305 if (xmlStrcmp((*file_node)->name, (xmlChar *)XML_ROOT_TYPE)) {
306 self->Warn("%s, no match found in xml file\n", XML_ROOT_TYPE);
307 *file_node = xmlNewNode(NULL, (xmlChar *)XML_ROOT_TYPE);
308 xmlSetProp(*file_node, (xmlChar *)"name",
309 (xmlChar *)ObjectName().c_str());
310 xmlDocSetRootElement(file_doc, *file_node);
311 }
312 }
313 } else {
314 self->Err("xml file not defined\n");
315 }
316
317 // gui
318 tabwidget =
319 new TabWidget(top_layout->At(0, 0), XML_MAIN_TABWIDGET, TabWidget::North);
320 save_button =
321 new PushButton(top_layout->At(1, 0),
322 "save config on target (" + self->ObjectName() + ")");
323 // load_button=new PushButton(top_layout->At(1,1),"load config on target (" +
324 // self->ObjectName() + ")");
325}
326
327// in case of RT, this thread switches to secondary mode when calling
328// com->Receive
329// it switches back to RT in ProcessXML when mutex are locked
330void FrameworkManager_impl::Run(void) {
331
332 if (self->ErrorOccured() == true) {
333 return ;
334 }
335
336
337 while (!ToBeStopped()) {
338 ssize_t bytesRead;
339 bytesRead = com->Receive(rcv_buf, rcv_buf_size);
340 com->CheckConnection();
341//printf("%i\n",bytesRead);
342 if (bytesRead == (ssize_t)rcv_buf_size)
343 Err("FrameworkManager max receive size, augmenter le buffer size!\n");
344
345 if (bytesRead > 0) {
346 //printf("recu %ld, trame %x %lld\n",bytesRead,(uint8_t)rcv_buf[0],GetTime()/(1000000));
347 //rcv_buf[bytesRead-1]=0;//pour affichage
348 //printf("%s\n",rcv_buf);
349
350 switch ((uint8_t)rcv_buf[0]) {
351 case XML_HEADER: {
352 xmlDoc *doc;
353 rcv_buf[bytesRead] = 0;
354 //Printf("%s\n",rcv_buf);
355 doc = xmlReadMemory(rcv_buf, (int)bytesRead, "include.xml",
356 "ISO-8859-1", 0);
357 xmlNode *cur_node = NULL;
358
359 for (cur_node = xmlDocGetRootElement(doc); cur_node;
360 cur_node = cur_node->next) {
361 if (cur_node->type == XML_ELEMENT_NODE) {
362 if (!xmlStrcmp(cur_node->name, (xmlChar *)XML_ROOT_TYPE)) {
363#ifdef __XENO__
364 WarnUponSwitches(
365 true); // ProcessXML should not switch to secondary mode
366#endif
367 top_layout->Widget::pimpl_->ProcessXML(cur_node->children);
368#ifdef __XENO__
369 WarnUponSwitches(false); // other parts of this thread can switch
370 // to secondary mode
371#endif
372 break;
373 }
374 }
375 }
376
377 xmlFreeDoc(doc);
378
379 if (save_button->Clicked())
380 SaveXml();
381
382 SaveXmlChange(rcv_buf);
383
384 break;
385 }
386 case WATCHDOG_HEADER: {
387 if(gcs_watchdog!=NULL) gcs_watchdog->Touch();
388 break;
389 }
390 default:
391 Err("unknown id: %x\n", (uint8_t)rcv_buf[0]);
392 break;
393 }
394 } else {
395 if (com->ConnectionLost())
396 SleepMS(10); // avoid infinite loop in this case
397 }
398 }
399}
400
401void FrameworkManager_impl::SaveXml(void) {
402 if (ui_defined)
403 xmlSaveFormatFile(xml_file.c_str(), file_doc, 1);
404}
405
406void FrameworkManager_impl::SaveXmlChange(char *buf) {
407 if (is_logging == true) {
408 FILE *xml_change;
409 char filename[256];
410 Time time = GetTime();
411
412 sprintf(filename, "%s/changes_at_%lld.xml", log_path.c_str(), time);
413
414 xml_change = fopen(filename, "a");
415 fprintf(xml_change, "%s", buf);
416 fclose(xml_change);
417
418 sprintf(filename, "changes_at_%lld.xml", time);
419 xml_changes.push_back(filename);
420 }
421}
422
423void FrameworkManager_impl::SendFile(UDTSOCKET socket,string path, string name) {
424 char *buf, *more_buf;
425 int size;
426 filebuf *pbuf;
427 ssize_t nb_write;
428 string filename = path + "/" + name;
429
430 // open the file
431 fstream ifs(filename.c_str(), ios::in | ios::binary);
432 ifs.seekg(0, ios::end);
433 size = ifs.tellg();
434 ifs.seekg(0, ios::beg);
435 pbuf = ifs.rdbuf();
436
437 if (size <= 0) {
438 Err("error opening file %s\n", filename.c_str());
439 return;
440 }
441
442 buf = (char *)malloc(sizeof(uint8_t) + sizeof(int) + name.size());
443 if (buf == NULL) {
444 Err("malloc error, not sending file\n");
445 return;
446 }
447
448 if (IsBigEndian()) {
449 buf[0] = FILE_INFO_BIG_ENDIAN;
450 } else {
451 buf[0] = FILE_INFO_LITTLE_ENDIAN;
452 }
453
454 memcpy(buf + 1, &size, sizeof(int));
455 memcpy(buf + 1 + sizeof(int), name.c_str(), name.size());
456 Printf("sending %s, size: %i\n", filename.c_str(), size);
457 // send file information
458 UDT::sendmsg(socket, buf, sizeof(uint8_t) + sizeof(int) + name.size(), -1,true);
459
460 more_buf = (char *)realloc((void *)buf, size);
461 if (more_buf == NULL) {
462 Err("realloc error, not sending file\n");
463 free(buf);
464 return;
465 } else {
466 buf = more_buf;
467 }
468
469 pbuf->sgetn(buf, size);
470 // send the file
471 nb_write = UDT::sendmsg(socket, buf, size, -1, true);
472
473 if (nb_write < 0) {
474 Err("UDT::sendmsg error (%s)\n", UDT::getlasterror().getErrorMessage());
475 } else if (nb_write != size) {
476 Err("UDT::sendmsg error, sent %ld/%i\n", nb_write, size);
477 }
478
479 ifs.close();
480 free(buf);
481}
482
483void FrameworkManager_impl::FinishSending(UDTSOCKET socket) {
484 char rm_cmd[256];
485
486 // send orignal xml
487 SendFile(socket,log_path, "setup.xml");
488 sprintf(rm_cmd, "rm %s/setup.xml", log_path.c_str());
489 system(rm_cmd);
490
491 // send xml changes
492 for (size_t i = 0; i < xml_changes.size(); i++) {
493 // Printf("%s\n",xml_changes.at(i).c_str());
494 SendFile(socket,log_path, xml_changes.at(i).c_str());
495 sprintf(rm_cmd, "rm %s/%s", log_path.c_str(), xml_changes.at(i).c_str());
496 system(rm_cmd);
497 }
498 xml_changes.clear();
499
500 // end notify
501 char buf = END_SENDING_FILES;
502 int nb_write = UDT::sendmsg(socket, &buf, 1, -1, true);
503
504 if (nb_write < 0) {
505 Err("UDT::sendmsg error (%s)\n", UDT::getlasterror().getErrorMessage());
506 } else if (nb_write != 1) {
507 Err("UDT::sendmsg error, sent %i/%i\n", nb_write, 1);
508 }
509
510 //wait end ACK
511 int nb_read = UDT::recvmsg(socket,&buf,1);
512 if(nb_read<0) {
513 Err("UDT::recvmsg error (%s)\n",UDT::getlasterror().getErrorMessage());
514 } else if (nb_read != 1) {
515 Err("UDT::recvmsg error, sent %i/%i\n",nb_read,1);
516 }
517}
518
519UDTSOCKET FrameworkManager_impl::GetSocket(void) {
520 while (1) {
521 UDTSOCKET new_fd;
522 new_fd = UDT::socket(AF_INET, SOCK_DGRAM, 0);
523 if (new_fd == UDT::INVALID_SOCK) {
524 Err("socket error: %s\n", UDT::getlasterror().getErrorMessage());
525 return 0;
526 }
527
528 sockaddr_in serv_addr;
529 serv_addr.sin_family = AF_INET;
530 serv_addr.sin_port = htons(short(port));
531
532 if (inet_pton(AF_INET, address.c_str(), &serv_addr.sin_addr) <= 0) {
533 Err("incorrect network address\n");
534 return 0;
535 }
536
537 memset(&(serv_addr.sin_zero), '\0', 8);
538
539 if (UDT::ERROR ==
540 UDT::connect(new_fd, (sockaddr *)&serv_addr, sizeof(serv_addr))) {
541 // Printf("connect error: %s
542 // %i\n",UDT::getlasterror().getErrorMessage(),UDT::getlasterror().getErrorCode());
543 UDT::close(new_fd);
544 if (UDT::getlasterror().getErrorCode() != 1001 &&
545 UDT::getlasterror().getErrorCode() != 1002) {
546 Err("connect error: %s\n", UDT::getlasterror().getErrorMessage());
547 return 0;
548 }
549 } else {
550 // printf("connected to
551 // %s:%i\n",inet_ntoa(serv_addr.sin_addr),serv_addr.sin_port);
552 return new_fd;
553 }
554 }
555}
556
557#ifdef __XENO__
558int FrameworkManager_impl::CreatePipe(RT_PIPE *fd, string name) {
559 name = self->ObjectName() + "-" + name;
560 // xenomai limitation
561 if (name.size() > 31)
562 self->Err("rt_pipe_create error (%s is too long)\n", name.c_str());
563// start log writter
564#ifdef RT_PIPE_SIZE
565 return rt_pipe_create(fd, name.c_str(), P_MINOR_AUTO, RT_PIPE_SIZE);
566#else
567 return rt_pipe_create(fd, name.c_str(), P_MINOR_AUTO, 0);
568#endif
569}
570#else
571int FrameworkManager_impl::CreatePipe(int (*fd)[2], string name) {
572 // if(pipe2(fd[0],O_NONBLOCK) == -1)
573 if (pipe(fd[0]) == -1) {
574 return errno;
575 } else {
576 int attr = fcntl((*fd)[0], F_GETFL, 0);
577 if (attr == -1) {
578 return errno;
579 }
580 if (fcntl((*fd)[0], F_SETFL, attr | O_NONBLOCK) == -1) {
581 return errno;
582 }
583 attr = fcntl((*fd)[1], F_GETFL, 0);
584 if (attr == -1) {
585 return errno;
586 }
587 if (fcntl((*fd)[1], F_SETFL, attr | O_NONBLOCK) == -1) {
588 return errno;
589 }
590
591 return 0;
592 }
593}
594#endif
595
596#ifdef __XENO__
597int FrameworkManager_impl::DeletePipe(RT_PIPE *fd) {
598 return rt_pipe_delete(fd);
599}
600#else
601int FrameworkManager_impl::DeletePipe(int (*fd)[2]) {
602 int status1 = close((*fd)[0]);
603 int status2 = close((*fd)[1]);
604 if (status1 == 0 && status2 == 0)
605 return 0;
606 if (status1 != 0)
607 return status1;
608 if (status2 != 0)
609 return status2;
610}
611#endif
612
613void FrameworkManager_impl::SetupLogger(string log_path,uint32_t stackSize) {
614
615 if (logger_defined == true) {
616 Warn("SetupLogger() was already called.\n");
617 return;
618 }
619
620 this->log_path = log_path;
621
622 int status = CreatePipe(&cmd_pipe, "log_cmd");
623 if (status != 0) {
624 char errorMsg[256];
625 Err("Error creating pipe (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
626 return;
627 }
628
629 status = CreatePipe(&data_pipe, "log_data");
630 if (status != 0) {
631 char errorMsg[256];
632 Err("Error creating pipe (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
633 return;
634 }
635
636#ifdef __XENO__
637 string tmp_name;
638 tmp_name = self->ObjectName() + "-log_heap";
639 status = rt_heap_create(&log_heap, tmp_name.c_str(), RT_LOG_HEAP, H_FIFO);
640 if (status != 0) {
641 char errorMsg[256];
642 Err("rt_heap_create error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
643 return;
644 }
645#endif //__XENO__
646
647 continuer = true;
648
649 // Initialize thread creation attributes
650 pthread_attr_t attr;
651 status=pthread_attr_init(&attr);
652 if (status != 0) {
653 char errorMsg[256];
654 Err("pthread_attr_init error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
655 return;
656 }
657
658 status=pthread_attr_setstacksize(&attr, stackSize);
659 if (status != 0) {
660 char errorMsg[256];
661 Err("pthread_attr_setstacksize error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
662 return;
663 }
664
665 status=pthread_create(&log_th, &attr, write_log_user, (void *)this);
666 if (status < 0) {
667 char errorMsg[256];
668 Err("pthread_create error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
669 return;
670 }
671
672 status=pthread_attr_destroy(&attr);
673 if (status != 0) {
674 char errorMsg[256];
675 Err("pthread_attr_destroy error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
676 return;
677 }
678
679 logger_defined = true;
680}
681
682void FrameworkManager_impl::AddDeviceToLog(IODevice *device) {
683 if (logger_defined == false) {
684 Warn("SetupLogger() was not called, not adding to log\n");
685 return;
686 }
687
688 if (is_logging == false) {
689 if (!device->pimpl_->IsSetToBeLogged()) {
690 device->pimpl_->SetToBeLogged();
691 log_desc_t tmp;
692 tmp.device = device;
693 logs.push_back(tmp);
694 } else {
695 Warn("not adding it twice\n");
696 }
697 } else {
698 Err("impossible while logging\n");
699 }
700}
701
702bool FrameworkManager_impl::IsDeviceLogged(const IODevice *device) const {
703 return device->pimpl_->IsSetToBeLogged();
704}
705
706void FrameworkManager_impl::StartLog(void) {
707 if (logger_defined == false) {
708 Err("SetupLogger() was not called, not starting log\n");
709 return;
710 }
711
712 ssize_t written;
713 size_t nb_err = 0;
714
715 if (logs.size() == 0) {
716 Warn("Not starting log: nothing to log!\n");
717 return;
718 }
719
720 if (is_logging == false) {
721 for (size_t i = 0; i < logs.size(); i++) {
722
723 logs.at(i).running = true;
724 logs.at(i).dbtFile = NULL;
725 logs.at(i).size = logs.at(i).device->pimpl_->LogSize();
726#ifdef __XENO__
727 written =
728 rt_pipe_write(&cmd_pipe, &logs.at(i), sizeof(log_desc_t), P_NORMAL);
729#else
730 written = write(cmd_pipe[1], &logs.at(i), sizeof(log_desc_t));
731#endif
732
733 if (written < 0) {
734 char errorMsg[256];
735 Err("write pipe error (%s)\n", strerror_r(-written, errorMsg, sizeof(errorMsg)));
736 nb_err++;
737 logs.at(i).running = false;
738 } else if (written != sizeof(log_desc_t)) {
739 Err("write pipe error %ld/%ld\n", written, sizeof(log_desc_t));
740 nb_err++;
741 logs.at(i).running = false;
742 }
743 }
744
745 if (nb_err != logs.size())
746 is_logging = true;
747 } else {
748 Warn("Already logging\n");
749 }
750}
751
752void FrameworkManager_impl::StopLog(void) {
753 ssize_t written;
754
755 if (is_logging == true) {
756 for (size_t i = 0; i < logs.size(); i++) {
757 logs.at(i).running = false;
758 }
759// send only one running false condition, user thread will stop and send all
760#ifdef __XENO__
761 written =
762 rt_pipe_write(&cmd_pipe, &logs.at(0), sizeof(log_desc_t), P_NORMAL);
763#else
764 written = write(cmd_pipe[1], &logs.at(0), sizeof(log_desc_t));
765#endif
766
767 if (written < 0) {
768 char errorMsg[256];
769 Err("write pipe error (%s)\n", strerror_r(-written, errorMsg, sizeof(errorMsg)));
770 return;
771 } else if (written != sizeof(log_desc_t)) {
772 Err("write pipe error %ld/%ld\n", written, sizeof(log_desc_t));
773 return;
774 }
775
776 is_logging = false;
777 } else {
778 Warn("Not logging\n");
779 }
780}
781
782char *FrameworkManager_impl::GetBuffer(size_t sz) {
783// Printf("alloc %i\n",sz);
784#ifdef __XENO__
785 void *ptr;
786 int status = rt_heap_alloc(&log_heap, sz, TM_NONBLOCK, &ptr);
787 if (status != 0) {
788 char errorMsg[256];
789 Err("rt_heap_alloc error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
790 ptr = NULL;
791 }
792 return (char *)ptr;
793#else
794 return (char *)malloc(sz);
795#endif
796}
797
798void FrameworkManager_impl::ReleaseBuffer(char *buf) {
799#ifdef __XENO__
800 int status = rt_heap_free(&log_heap, buf);
801
802 if (status != 0) {
803 char errorMsg[256];
804 Err("rt_heap_free error (%s)\n", strerror_r(-status, errorMsg, sizeof(errorMsg)));
805 }
806#else
807 free(buf);
808#endif
809}
810
811void FrameworkManager_impl::WriteLog(const char *buf, size_t size) {
812 ssize_t written;
813
814#ifdef __XENO__
815 written = rt_pipe_write(&data_pipe, buf, size, P_NORMAL);
816#else
817 written = write(data_pipe[1], buf, size);
818#endif
819
820 if (written < 0) {
821 char errorMsg[256];
822 Err("error write pipe (%s)\n", strerror_r(-written, errorMsg, sizeof(errorMsg)));
823 } else if (written != (ssize_t)size) {
824 Err("error write pipe %ld/%ld\n", written, size);
825 }
826}
827
828void *FrameworkManager_impl::write_log_user(void *arg) {
829 int cmd_pipe = -1;
830 int data_pipe = -1;
831 fd_set set;
832 struct timeval timeout;
833 FrameworkManager_impl *caller = (FrameworkManager_impl *)arg;
834 int rv;
835
836 vector<log_desc_t> logs;
837
838#ifdef __XENO__
839 while (cmd_pipe < 0) {
840 string filename = NRT_PIPE_PATH + caller->self->ObjectName() + "-log_cmd";
841 cmd_pipe = open(filename.c_str(), O_RDWR);
842 if (cmd_pipe < 0 && errno != ENOENT) {
843 char errorMsg[256];
844 caller->self->Err("open rt_pipe error: %s %s\n", filename.c_str(), strerror_r(errno, errorMsg, sizeof(errorMsg)));
845 }
846 usleep(1000);
847 }
848 while (data_pipe < 0) {
849 string filename = NRT_PIPE_PATH + caller->self->ObjectName() + "-log_data";
850 data_pipe = open(filename.c_str(), O_RDWR);
851 if (data_pipe < 0 && errno != ENOENT) {
852 char errorMsg[256];
853 caller->self->Err("open rt_pipe error: %s %s\n", filename.c_str(), strerror_r(errno, errorMsg, sizeof(errorMsg)));
854 }
855 usleep(1000);
856 }
857#else
858 cmd_pipe = caller->cmd_pipe[0];
859 data_pipe = caller->data_pipe[0];
860#endif
861
862 while (caller->continuer == true) {
863 FD_ZERO(&set);
864 FD_SET(cmd_pipe, &set);
865 FD_SET(data_pipe, &set);
866
867 timeout.tv_sec = 0;
868 timeout.tv_usec = SELECT_TIMEOUT_MS * 1000;
869 rv = select(FD_SETSIZE, &set, NULL, NULL, &timeout);
870
871 if (rv == -1) {
872 caller->Err("select error\n"); // an error accured
873 } else if (rv == 0) {
874 // printf("timeout write_log_user %s\n",caller->ObjectName().c_str()); //
875 // a timeout occured
876 } else {
877 if (FD_ISSET(cmd_pipe, &set)) {
878 log_desc_t tmp;
879 read(cmd_pipe, &tmp, sizeof(log_desc_t));
880
881 if (tmp.running == true) {// start logging
882 string filename = caller->log_path + "/" + caller->FileName(tmp.device) + ".dbt";
883 printf("Creating log file %s (log size %i)\n", filename.c_str(), (int)tmp.size);
884 tmp.dbtFile = inithdFile((char *)filename.c_str(), UAV, tmp.size);
885 logs.push_back(tmp);
886
887 if (logs.size() == 1) {
888 filename = caller->log_path + "/setup.xml";
889 xmlSaveFile(filename.c_str(), caller->file_doc);
890 }
891 } else {// stop logging
892 //disable watchdog temporarly
893 //this is necessary because GCS is no longer sending the heartbeat when receiving files...
894 //TODO: add a thread in GCS for receiving file
895 //but be careful that with a xbee modem for exemple, sending files can saturate communication and
896 //avoid the heartbeat to be received... so disabling watchdog is not a so bad option...
897 if(caller->gcs_watchdog!=NULL) {
898 caller->gcs_watchdog->SafeStop();
899 caller->gcs_watchdog->Join();
900 }
901 //create a socket for files
902 UDTSOCKET file_sock = caller->GetSocket();
903 char data=START_SENDING_FILES;
904 ssize_t nb_write = UDT::sendmsg(file_sock, &data, 1, -1, true);
905 if (nb_write < 0) {
906 caller->Err("UDT::sendmsg error (%s)\n", UDT::getlasterror().getErrorMessage());
907 if (UDT::getlasterror().getErrorCode() == CUDTException::ECONNLOST ||
908 UDT::getlasterror().getErrorCode() == CUDTException::EINVSOCK) {
909 }
910 } else if (nb_write != 1) {
911 caller->Err("%s, code %i (%ld/%ld)\n", UDT::getlasterror().getErrorMessage(),
912 UDT::getlasterror().getErrorCode(), nb_write, 1);
913 }
914 for (size_t i = 0; i < logs.size(); i++) {
915 if (logs.at(i).dbtFile != NULL) {
916 close_hdfile(logs.at(i).dbtFile);
917
918 string filename = caller->FileName(logs.at(i).device) + ".dbt";
919 caller->SendFile(file_sock,caller->log_path, filename);
920
921 fstream txt_file;
922 filename = caller->FileName(logs.at(i).device) + ".txt";
923 txt_file.open((caller->log_path + "/" + filename).c_str(),
924 fstream::out);
925 txt_file << "1: time (us)\n2: time (ns)\n";
926 int index = 3;
927 logs.at(i).device->pimpl_->WriteLogsDescriptors(txt_file, &index);
928 txt_file.close();
929
930 caller->SendFile(file_sock,caller->log_path, filename);
931 }
932 }
933 // a revoir celui ci est le xml enregistré et pas forcement l'actuel
934 // if(caller->xml_file!="") caller->SendFile(caller->xml_file);
935 caller->FinishSending(file_sock);
936
937 int status = UDT::close(file_sock);
938 if (status != 0)
939 caller->Err("Error udt::close %s", UDT::getlasterror().getErrorMessage());
940
941 logs.clear();
942 //enable watchdog again
943 if(caller->gcs_watchdog!=NULL) {
944 caller->gcs_watchdog->Start();
945 }
946 }
947 }
948
949 if (FD_ISSET(data_pipe, &set)) {
950 log_header_t header;
951 read(data_pipe, &header, sizeof(log_header_t));
952
953 for (size_t i = 0; i < logs.size(); i++) {
954 if (logs.at(i).device == header.device) {
955 char *buf = (char *)malloc(header.size);
956 read(data_pipe, buf, header.size);
957 // printf("%s \n",header.device->ObjectName().c_str());
958 // for(int i=0;i<header.size;i++) printf("%x ",buf[i]);
959 // printf("\n");
960 if (logs.at(i).size == header.size) {
961 if (logs.at(i).dbtFile != NULL) {
962 write_hdfile(
963 logs.at(i).dbtFile, buf, (road_time_t)(header.time / 1000),
964 (road_timerange_t)(header.time % 1000), header.size);
965 } else {
966 printf("err\n");
967 }
968 } else {
969 caller->self->Err("%s log size is not correct %i/%i\n",
970 header.device->ObjectName().c_str(),
971 header.size, logs.at(i).size);
972 }
973 free(buf);
974 }
975 }
976 }
977 }
978 }
979
980#ifdef __XENO__
981 close(cmd_pipe);
982 close(data_pipe);
983#endif
984
985 pthread_exit(0);
986}
987
988string FrameworkManager_impl::FileName(IODevice *device) {
989 return getFrameworkManager()->ObjectName() + "_" + device->ObjectName();
990}
991
992void FrameworkManager_impl::PrintXml(void) const {
993 xmlChar *xmlbuff;
994 int buffersize;
995 xmlDocDumpFormatMemory(file_doc, &xmlbuff, &buffersize, 1);
996 Printf("xml:\n%s\n", xmlbuff);
997 xmlFree(xmlbuff);
998}
Note: See TracBrowser for help on using the repository browser.