summaryrefslogtreecommitdiff
path: root/maximus/system/src/Station.cpp
blob: 91792630f197c3f2ae580572e78d8b329aaceca0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
/************************************************************************
                        Station.cpp - Copyright buret

Here you can write a license for your code, some comments or any other
information you want to have in your generated code. To to this simply
configure the "headings" directory in uml to point to a directory
where you have your heading files.

or you can just replace the contents of this file with your own.
If you want to do this, this file is located at

/usr/share/apps/umbrello/headings/heading.cpp

-->Code Generators searches for heading files based on the file extension
   i.e. it will look for a file name ending in ".h" to include in C++ header
   files, and for a file name ending in ".java" to include in all generated
   java code.
   If you name the file "heading.<extension>", Code Generator will always
   choose this file even if there are other files with the same extension in the
   directory. If you name the file something else, it must be the only one with that
   extension in the directory to guarantee that Code Generator will choose it.

you can use variables in your heading files which are replaced at generation
time. possible variables are : author, date, time, filename and filepath.
just write %variable_name%

This file was generated on %date% at %time%
The original location of this file is /home/buret/eclipse/maximus/system/src/Station.cpp
**************************************************************************/

#include "Station.h"

#include "StationConfiguration.h"

#include "Error.h"
#include "Logger.h"

#include "host/socket.h" // for 'STATION_SOCK'

#include <sys/types.h> // for 'waitpid()'
#include <sys/wait.h> // for 'waitpid()'
#include <fcntl.h>
#include <unistd.h> // for 'exec()' and 'system()'
#include <sys/signal.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <errno.h>
#include <iomanip> // for 'setfill()' and 'setw()'
using namespace std;

extern bool UNITTEST;
extern string stationTest;


// Constructors/Destructors
//  


Station::Station ( const string & station_executable, const Network_Clock_Tick current_tick_value ):
mInputFileDescriptor(-1),
mOutputFileDescriptor(-1),
mLogPipe(-1),
mPid(0),
mStationStatus(MAXIMUS_STATION_STATUS_NONE),
mStationIdleCounter(1), // once a station has been launched, Maximus has to wait for a system IDLE message
mpStationConfiguration(NULL)
{
  logFunction();
  string stationExecutable = station_executable;

  if (UNITTEST)
  {
    stationExecutable = stationTest;
  }

  mpStationConfiguration = new StationConfiguration (stationExecutable);
  if (NULL == mpStationConfiguration)
  {
    throw Error(__PRETTY_FUNCTION__ , "Station configuration pointer is NULL");
  }

  initAttributes();

  startProcess(current_tick_value);
}


void Station::initAttributes ( )
{
  logFunction();
}


Station::~Station ( )
{
  logFunction();
  clog << logger(LOG_COM) << "delete station " \
       << getStationId() << " (0x" << setfill('0') << setw(4) << uppercase << hex << getStationId() << ")" << dec << endl;
  
  stopProcess();
  if (NULL != mpStationConfiguration)
  {
    delete (mpStationConfiguration);
    mpStationConfiguration = NULL;
  }  
}


//  
// Methods
//  


// Other methods
//


// public methods
//

    
bool Station::operator== ( const Station & station ) const
{
  logFunction();
  bool bOperator = false;
  
  if (  (getStationStatus() == station.getStationStatus())
        && (getStationConfiguration() == station.getStationConfiguration())
        && (getInputFileDescriptor() == station.getInputFileDescriptor())
        && (getOutputFileDescriptor() == station.getOutputFileDescriptor())
        && (getLogFileDescriptor() == station.getLogFileDescriptor())
        && (getStationId() == station.getStationId()) )
  {
    bOperator = true;
  }

  return bOperator;
}


Station & Station::operator= ( const Station & station )
{
  logFunction();
  
  if (  (!setInputFileDescriptor (station.getInputFileDescriptor()))
        || (!setOutputFileDescriptor (station.getOutputFileDescriptor()))
        || (!setLogFileDescriptor (station.getLogFileDescriptor()))
        || (!setStationStatus (station.getStationStatus()))
        || (!setStationConfiguration (station.getStationConfiguration())) )
  {
    throw Error(__PRETTY_FUNCTION__ , "Error when setting attributes");
  }
  
  return *this;
}


void Station::displayStation ( ) const
{
  logFunction();
  
  clog << logger(LOG_INFO) << "\t[input file descriptor = " << dec << getInputFileDescriptor() \
       << ", output file descriptor = " << getOutputFileDescriptor() \
       << ", log file descriptor = " << getLogFileDescriptor() \
       << ", process id = " << getStationId() << " (0x" << setfill('0') << setw(4) << uppercase << hex << getStationId() << ")" \
       << ", executable = " << getStationConfiguration()->getStationExecutable() \
       << ", name = " << getStationConfiguration()->getStationName() << "]" << dec << endl;
}


bool Station::launchDebugger ( const string & command_line ) const
{
  logFunction();
  bool bLaunch = false;

  string commandLine(command_line);
  size_t found = 0;

  do
  {
    found = commandLine.find("%n", found, 2);
    if (string::npos != found)
    {
      commandLine.replace(found, 2, getStationConfiguration()->getStationName());
    }
  }
  while (found != string::npos);

  found = 0;  
  do
  {
    found = commandLine.find("%e", found, 2);
    if (string::npos != found)
    {
      commandLine.replace(found, 2, getStationConfiguration()->getStationExecutable());
    }
  }
  while (found != string::npos);

  found = 0;
  do
  {
    found = commandLine.find("%p", found, 2);
    if (string::npos != found)
    {
      char processId[6];
      sprintf(processId, "%d", getPid());
      commandLine.replace(found, 2, processId);
    }
  }
  while (found != string::npos);

  clog << logger(LOG_INFO) << "debugger command line = " << commandLine << endl;

  system(commandLine.c_str());

  return bLaunch;
}  


// Accessor methods
//  


// public attribute accessor methods
//  


// private attribute accessor methods
//  


const Sci_Msg_Station_Id Station::getStationId ( ) const
{
  return static_cast<Sci_Msg_Station_Id>(mPid);
}


const pid_t Station::getPid ( ) const
{
  return mPid;
}


bool Station::setInputFileDescriptor ( const File_Descriptor input_file_descriptor )
{
  mInputFileDescriptor = input_file_descriptor;

  return true;
}


bool Station::setOutputFileDescriptor ( const File_Descriptor output_file_descriptor )
{
  mOutputFileDescriptor = output_file_descriptor;

  return true;
}


bool Station::setLogFileDescriptor ( const File_Descriptor log_file_descriptor )
{
  mLogPipe = log_file_descriptor;
  
  return true;
}


const File_Descriptor Station::getInputFileDescriptor ( ) const
{
  return mInputFileDescriptor;
}


const File_Descriptor Station::getOutputFileDescriptor ( ) const
{
  return mOutputFileDescriptor;
}


const File_Descriptor Station::getLogFileDescriptor ( ) const
{
  return mLogPipe;
}


Station_Status Station::getStationStatus ( ) const
{
  return mStationStatus;
}


bool Station::setStationStatus ( const Station_Status status )
{
  mStationStatus = status;
  
  return true;
}


const unsigned short int Station::getStationIdleCounter ( ) const
{
  return mStationIdleCounter;
}


bool Station::incrementStationIdleCounter ( )
{
  mStationIdleCounter++;

  return true;
}


bool Station::decrementStationIdleCounter ( )
{
  logFunction();
  bool bDecrement = false;

  if (0 < mStationIdleCounter)
  {
    mStationIdleCounter--;
    bDecrement = true;
  }
  else
  {
    clog << logger(LOG_WARNING) << "station with id " << dec << getStationId() \
         << " (0x" << setfill('0') << setw(4) << uppercase << hex << getStationId() \
         << ") is already IDLE" << dec << endl;
  }

  return bDecrement;
}


bool Station::setStationConfiguration ( StationConfiguration * p_station_configuration )
{
  logFunction();
  bool bSetConfig = false;

  if (NULL != p_station_configuration)
  {
    mpStationConfiguration = p_station_configuration;
    bSetConfig = true;
  }
  else
  {
    errno = EINVAL;
    throw Error(__PRETTY_FUNCTION__ , "Station configuration pointer is NULL", errno);
  }

  return bSetConfig;
}


StationConfiguration * Station::getStationConfiguration ( ) const
{
  if (NULL == mpStationConfiguration)
  {
    throw Error(__PRETTY_FUNCTION__ , "Station configuration pointer is NULL");
  }

  return mpStationConfiguration;
}


bool Station::setStationName ( const std::string & station_name )
{
  return getStationConfiguration()->setStationName(station_name);
}


// private methods
//  


void Station::startProcess ( const Network_Clock_Tick current_tick_value )
{
  logFunction();

  // Start the station process
  //
  if(getStationConfiguration()->getStationExecutable().empty())
  {
    throw Error(__PRETTY_FUNCTION__, "Executable not set", errno);
  }
  if(0 == (mPid = fork()))
  {
    char stationExecutable[getStationConfiguration()->getStationExecutable().size()+1];
    size_t stringLength = getStationConfiguration()->getStationExecutable().copy(stationExecutable, getStationConfiguration()->getStationExecutable().size());
    stationExecutable[stringLength] = '\0';

    char currentTickValue[32];
    sprintf(currentTickValue, "%llu", current_tick_value);

    if (-1 == execlp(stationExecutable, stationExecutable, currentTickValue, NULL))
    {
      throw Error(__PRETTY_FUNCTION__, "Cannot launch station executable", errno);
    }
    exit(1);
  }

  // Loop until pipe creation: max = STATION_WAIT_LOOP_NB * STATION_WAIT_TIMEOUT_MS ms
  //
  int loop;
  int fd_status;
  char nameBuffer[256];

  #ifdef STATION_SOCK

    struct sockaddr_un sockaddr;
    int bufsize = STATION_MAX_SOCK_BUFFER_SIZE;
    sprintf(nameBuffer, "%s/%s_sock_%d", STATION_SOCK_PATH, STATION_SOCK_PREFIX, getPid());
    // open the socket
    if((mInputFileDescriptor = socket (PF_UNIX, SOCK_STREAM, 0)) < 0)
    {
      throw Error(__FUNCTION__ , "Cannot create socket", errno);
    }

    // avoid other stations to inherit the socket 
    fd_status = fcntl(mInputFileDescriptor, F_GETFD);
    fcntl(mInputFileDescriptor, F_SETFD, fd_status | FD_CLOEXEC);

    // extend send buffer size
    if(setsockopt (mInputFileDescriptor, SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(bufsize)) < 0)
    {
    	throw Error(__FUNCTION__ , "Cannot increase buffer size", errno);
    }
    sockaddr.sun_family = AF_UNIX;
    strcpy (sockaddr.sun_path, nameBuffer);

    for(loop = 0; loop < STATION_WAIT_LOOP_NB; loop++)
    {
      // Connect to server
      //
    	if((connect(mInputFileDescriptor, (struct sockaddr *)&sockaddr, sizeof(sockaddr))) >= 0)
      {
        break;
      }
      usleep(STATION_WAIT_TIMEOUT_MS * 1000);
    }

    if(loop >= STATION_WAIT_LOOP_NB)
    {
  	  stopProcess();
      throw Error(__FUNCTION__ , "Cannot connect to station", errno);
    }
    else
    {
      setOutputFileDescriptor(mInputFileDescriptor);
    }

  #else /* !STATION_SOCK */

    // Open input pipe
    sprintf(nameBuffer, "%s/%s_out_%d", STATION_PIPE_PATH, STATION_PIPE_PREFIX, getPid());
    for(loop = 0; loop < STATION_WAIT_LOOP_NB; loop++)
    {
      // Connect to server
      //
      if((mInputFileDescriptor = open(nameBuffer, O_RDONLY | O_NONBLOCK)) >= 0)
      {
        break;
      }
      usleep(STATION_WAIT_TIMEOUT_MS * 1000);
    }
    if(loop >= STATION_WAIT_LOOP_NB)
    {
      stopProcess();
  	  throw Error(__FUNCTION__ , "Cannot connect to station", errno);
    }

    // avoid other stations to inherit the pipe 
    fd_status = fcntl(mInputFileDescriptor, F_GETFD);
    fcntl(mInputFileDescriptor, F_SETFD, fd_status | FD_CLOEXEC);

    // Open output pipe
    sprintf(nameBuffer, "%s/%s_in_%d", STATION_PIPE_PATH, STATION_PIPE_PREFIX, getPid());
    if((mOutputFileDescriptor = open(nameBuffer, O_WRONLY | O_NONBLOCK)) < 0)
    {
      stopProcess();
      throw Error(__PRETTY_FUNCTION__, "Cannot open output pipe", errno);
    }
    // avoid other stations to inherit the pipe 
    fd_status = fcntl(mOutputFileDescriptor, F_GETFD);
    fcntl(mOutputFileDescriptor, F_SETFD, fd_status | FD_CLOEXEC);

  #endif /* STATION_SOCK */

  // Open log pipe
  //
  sprintf(nameBuffer, "%s/%s_log_%d", STATION_PIPE_PATH, STATION_PIPE_PREFIX, getPid());
  if((mLogPipe = open(nameBuffer, O_RDONLY | O_NONBLOCK)) < 0)
  {
    stopProcess();
    throw Error(__PRETTY_FUNCTION__, "Cannot open log pipe", errno);
  }

  // avoid other stations to inherit the pipe 
  fd_status = fcntl(mLogPipe, F_GETFD);
  fcntl(mLogPipe, F_SETFD, fd_status | FD_CLOEXEC);
}


void Station::stopProcess ( )
{
  logFunction();
  if(mInputFileDescriptor >= 0)
  {
    close(mInputFileDescriptor);
  }
  if(mOutputFileDescriptor >= 0)
  {
    close(mOutputFileDescriptor);
  }
  if(mLogPipe >= 0)
  {
    close(mLogPipe);
  }
  if(mPid > 0)
  {
    kill(mPid, SIGTERM);
    waitpid(mPid, NULL, 0);
  }
}


void Station::displayStationStatus ( ) const
{
  logFunction();
  
  switch (getStationStatus())
  {
    case 0:
      clog << logger(LOG_INFO) << "MAXIMUS_STATION_STATUS_NONE" << endl;
      break;
    case 1:
      clog << logger(LOG_INFO) << "MAXIMUS_STATION_STATUS_IDLE" << endl;
      break;
    case 2:
      clog << logger(LOG_INFO) << "MAXIMUS_STATION_STATUS_BUSY" << endl;
      break;
    case 3:
      clog << logger(LOG_INFO) << "MAXIMUS_STATION_STATUS_DEACTIVATED" << endl;
      break;
    default:      
      clog << logger(LOG_INFO) << "unknown!" << endl;
      break;
  }
}


// protected methods
//