ProcessForker.cpp 32.8 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/******************************************************************************
 *
 * This file is part of the Castor project.
 * See http://castor.web.cern.ch/castor
 *
 * Copyright (C) 2003  CERN
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 *
 *
21
 * @author Castor Dev team, castor-dev@cern.ch
22
23
 *****************************************************************************/

24
#include "castor/exception/Exception.hpp"
25
#include "castor/legacymsg/NsProxy_TapeAlwaysEmpty.hpp"
26
#include "castor/legacymsg/RmcProxyTcpIp.hpp"
27
#include "castor/messages/Constants.hpp"
28
29
30
#include "castor/messages/ForkCleaner.pb.h"
#include "castor/messages/ForkDataTransfer.pb.h"
#include "castor/messages/ForkLabel.pb.h"
31
#include "castor/messages/ForkSucceeded.pb.h"
32
33
#include "castor/messages/ProcessCrashed.pb.h"
#include "castor/messages/ProcessExited.pb.h"
34
#include "castor/messages/ReturnValue.pb.h"
35
#include "castor/messages/StopProcessForker.pb.h"
36
37
#include "castor/messages/TapeserverProxyZmq.hpp"
#include "castor/tape/tapeserver/daemon/Constants.hpp"
38
#include "castor/tape/tapeserver/daemon/LabelSession.hpp"
39
#include "castor/tape/tapeserver/daemon/ProcessForker.hpp"
40
#include "castor/tape/tapeserver/daemon/ProcessForkerUtils.hpp"
41
#include "castor/tape/utils/DriveConfig.hpp"
42
#include "castor/messages/SmartZmqContext.hpp"
43
#include "castor/utils/SmartArrayPtr.hpp"
44
#include "castor/utils/utils.hpp"
45
#include "h/serrno.h"
46

47
#include <errno.h>
48
#include <memory>
49
50
51
52
#include <poll.h>
#include <sstream>
#include <sys/types.h>
#include <sys/wait.h>
53
54

//------------------------------------------------------------------------------
55
// constructor
56
//------------------------------------------------------------------------------
57
58
59
60
61
62
63
64
65
castor::tape::tapeserver::daemon::ProcessForker::ProcessForker(
  log::Logger &log,
  const int cmdSocket,
  const int reaperSocket,
  const std::string &hostName) throw():
  m_log(log),
  m_cmdSocket(cmdSocket),
  m_reaperSocket(reaperSocket),
  m_hostName(hostName) {
66
67
68
}

//------------------------------------------------------------------------------
69
// destructor
70
//------------------------------------------------------------------------------
71
castor::tape::tapeserver::daemon::ProcessForker::~ProcessForker() throw() {
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
  closeCmdReceiverSocket();
}

//------------------------------------------------------------------------------
// closeCmdReceiverSocket
//------------------------------------------------------------------------------
void castor::tape::tapeserver::daemon::ProcessForker::closeCmdReceiverSocket()
  throw() {
  if(-1 != m_cmdSocket) {
    std::list<log::Param> params;
    params.push_back(log::Param("cmdSocket", m_cmdSocket));
    if(-1 == close(m_cmdSocket)) {
      char message[100];
      sstrerror_r(errno, message, sizeof(message));
      params.push_back(log::Param("message", message));
      m_log(LOG_ERR, "Failed to close command receiver socket",
        params);
    } else {
      m_log(LOG_INFO, "Closed command receiver socket", params);
    }
92
  }
93
}
94
95
96
97

//------------------------------------------------------------------------------
// execute
//------------------------------------------------------------------------------
98
99
100
void castor::tape::tapeserver::daemon::ProcessForker::execute() throw() {
  // The main event loop
  while(handleEvents()) {
101
102
103
104
105
106
  }
}

//------------------------------------------------------------------------------
// handleEvents
//------------------------------------------------------------------------------
107
108
109
110
111
112
113
114
115
116
117
118
119
120
bool castor::tape::tapeserver::daemon::ProcessForker::handleEvents() throw() {
  try {
    return handlePendingMsgs() && handlePendingSignals();
  } catch(castor::exception::Exception &ex) {
    log::Param params[] = {log::Param("message", ex.getMessage().str())};
    m_log(LOG_ERR, "ProcessForker failed to handle events", params);
  } catch(std::exception &se) {
    log::Param params[] = {log::Param("message", se.what())};
    m_log(LOG_ERR, "ProcessForker failed to handle events", params);
  } catch(...) {
    log::Param params[] =
      {log::Param("message", "Caught an unknown exception")};
    m_log(LOG_ERR, "ProcessForker failed to handle events", params);
  }
121
122
123
124
125
126
127
128
129

  // If program execution reached here then an exception was thrown

  // Sleep for a second in order to prevent a tight loop in the case of the
  // perpetual raising of exceptions
  sleep(1);

  // An exception should not stop the main event loop
  return true; // The main event loop should continue
130
131
132
133
134
135
}

//------------------------------------------------------------------------------
// handlePendingMsgs
//------------------------------------------------------------------------------
bool castor::tape::tapeserver::daemon::ProcessForker::handlePendingMsgs() {
136
137
138
139
140
  if(thereIsAPendingMsg()) {
    return handleMsg();
  } else {
    return true; // The main event loop should continue
  }
141
142
143
}

//------------------------------------------------------------------------------
144
// thereIsAPendingMsg
145
//------------------------------------------------------------------------------
146
bool castor::tape::tapeserver::daemon::ProcessForker::thereIsAPendingMsg() {
147

148
149
  // Call poll() in orer to see if there is any data to be read
  struct pollfd fds;
150
  fds.fd = m_cmdSocket;
151
152
153
154
  fds.events = POLLIN;
  fds.revents = 0;
  const int timeout = 100; // Timeout in milliseconds
  const int pollRc = poll(&fds, 1, timeout);
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
  // Return true of false depending on the result from poll()
  switch(pollRc) {
  case 0: // Timeout
    return false;
  case -1: // Error
    {
      char message[100];
      sstrerror_r(errno, message, sizeof(message));
      log::Param params[] = {log::Param("message", message)};
      m_log(LOG_ERR,
        "Error detected when checking for a pending ProcessForker message",
        params);
      return false;
    }
  case 1: // There is a possibility of a pending message
    return fds.revents & POLLIN ? true : false;
  default: // Unexpected return value
    {
      std::ostringstream message;
      message << "poll returned an unexpected value"
        ": expected=0 or 1 actual=" << pollRc;
      log::Param params[] = {log::Param("message", message.str())};
      m_log(LOG_ERR,
        "Error detected when checking for a pending ProcessForker message",
        params);
      return false;
    }
  }
184
185
186
}

//------------------------------------------------------------------------------
187
// handleMsg
188
//------------------------------------------------------------------------------
189
190
191
bool castor::tape::tapeserver::daemon::ProcessForker::handleMsg() {
  ProcessForkerFrame frame;
  try {
192
    frame = ProcessForkerUtils::readFrame(m_cmdSocket);
193
194
195
196
197
198
  } catch(castor::exception::Exception &ne) {
    log::Param params[] = {log::Param("message", ne.getMessage().str())};
    m_log(LOG_ERR, "Failed to handle message", params);
    sleep(1); // Sleep a moment to avoid going into a tight error loop
    return true; // The main event loop should continue
    /*
199
    castor::exception::Exception ex;
200
    ex.getMessage() << "Failed to handle message: " << ne.getMessage().str();
201
    throw ex;
202
    */
203
204
  }

205
  log::Param params[] = {
206
    log::Param("type", messages::msgTypeToString(frame.type)),
207
208
209
210
211
212
213
214
215
216
    log::Param("len", frame.payload.length())};
  m_log(LOG_INFO, "ProcessForker handling a ProcessForker message", params);

  MsgHandlerResult result;
  try {
    result = dispatchMsgHandler(frame);
  } catch(castor::exception::Exception &ex) {
    log::Param("message", ex.getMessage().str());
    m_log(LOG_ERR, "ProcessForker::dispatchMsgHandler() threw an exception",
      params);
217
218
    messages::Exception msg;
    msg.set_code(ex.code());
219
    msg.set_message(ex.getMessage().str());
220
    ProcessForkerUtils::writeFrame(m_cmdSocket, msg);
221
222
223
224
225
    return true; // The main event loop should continue
  } catch(std::exception &se) {
    log::Param("message", se.what());
    m_log(LOG_ERR, "ProcessForker::dispatchMsgHandler() threw an exception",
      params);
226
227
    messages::Exception msg;
    msg.set_code(SEINTERNAL);
228
    msg.set_message(se.what());
229
    ProcessForkerUtils::writeFrame(m_cmdSocket, msg);
230
231
232
233
    return true; // The main event loop should continue
  } catch(...) {
    m_log(LOG_ERR,
      "ProcessForker::dispatchMsgHandler() threw an unknown exception");
234
235
    messages::Exception msg;
    msg.set_code(SEINTERNAL);
236
    msg.set_message("Caught and unknown and unexpected exception");
237
    ProcessForkerUtils::writeFrame(m_cmdSocket, msg);
238
    return true; // The main event loop should continue
239
240
  }

241
  ProcessForkerUtils::writeFrame(m_cmdSocket, result.reply);
242
243
244
  {
    log::Param params[] = {
      log::Param("payloadType",
245
        messages::msgTypeToString(result.reply.type)),
246
247
248
249
      log::Param("payloadLen", result.reply.payload.length())};
    m_log(LOG_DEBUG, "ProcessForker wrote reply", params);
  }
  return result.continueMainEventLoop;
250
251
252
253
254
}

//------------------------------------------------------------------------------
// dispatchMsgHandler
//------------------------------------------------------------------------------
255
256
257
258
castor::tape::tapeserver::daemon::ProcessForker::MsgHandlerResult
  castor::tape::tapeserver::daemon::ProcessForker::dispatchMsgHandler(
  const ProcessForkerFrame &frame) {
  switch(frame.type) {
259
  case messages::MSG_TYPE_FORKCLEANER:
260
    return handleForkCleanerMsg(frame);
261
  case messages::MSG_TYPE_FORKDATATRANSFER:
262
    return handleForkDataTransferMsg(frame);
263
  case messages::MSG_TYPE_FORKLABEL:
264
    return handleForkLabelMsg(frame);
265
  case messages::MSG_TYPE_STOPPROCESSFORKER:
266
    return handleStopProcessForkerMsg(frame);
267
268
269
270
  default:
    {
      castor::exception::Exception ex;
      ex.getMessage() << "Failed to dispatch message handler"
271
        ": Unknown message type: type=" << frame.type;
272
273
274
275
276
277
      throw ex;
    }
  }
}

//------------------------------------------------------------------------------
278
// handleForkCleanerMsg
279
//------------------------------------------------------------------------------
280
281
282
castor::tape::tapeserver::daemon::ProcessForker::MsgHandlerResult 
  castor::tape::tapeserver::daemon::ProcessForker::handleForkCleanerMsg(
  const ProcessForkerFrame &frame) {
283

284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
  // Parse the incoming request
  messages::ForkCleaner rqst;
  ProcessForkerUtils::parsePayload(frame, rqst);

  // Log the contents of the incomming request
  std::list<log::Param> params;
  params.push_back(log::Param("unitName", rqst.unitname()));
  params.push_back(log::Param("vid", rqst.vid()));
  m_log(LOG_INFO, "ProcessForker handling ForkCleaner message", params);

  // Fork a label session
  const pid_t forkRc = fork();

  // If fork failed
  if(0 > forkRc) {
299
300
301
    const std::string& errorMsg = "Failed to fork cleaner session for tape drive";
    logForkError(errorMsg,params);
    
302
    return createExceptionResult(SEINTERNAL, errorMsg, true);
303
304
305
306
307
308
309
310
311

  // Else if this is the parent process
  } else if(0 < forkRc) {
    log::Param params[] = {log::Param("pid", forkRc)};
    m_log(LOG_INFO, "ProcessForker forked cleaner session", params);

    // TO BE DONE
    waitpid(forkRc, NULL, 0);

312
    return createForkSucceededResult(forkRc, true);
313
314
315

  // Else this is the child process
  } else {
316
    closeCmdReceiverSocket();
317
318
    // TO BE DONE
    exit(0);
319
320
321
322
  }
}

//------------------------------------------------------------------------------
323
// handleForkDataTransferMsg
324
//------------------------------------------------------------------------------
325
326
327
328
329
330
331
332
333
334
335
castor::tape::tapeserver::daemon::ProcessForker::MsgHandlerResult 
  castor::tape::tapeserver::daemon::ProcessForker::handleForkDataTransferMsg(
  const ProcessForkerFrame &frame) {

  // Parse the incoming request
  messages::ForkDataTransfer rqst;
  ProcessForkerUtils::parsePayload(frame, rqst);

  // Log the contents of the incomming request
  std::list<log::Param> params;
  params.push_back(log::Param("unitName", rqst.unitname()));
336
337
  m_log(LOG_INFO, "ProcessForker handling ForkDataTransfer message", params);

338
339
340
341
342
  // Fork a data-transfer session
  const pid_t forkRc = fork();

  // If fork failed
  if(0 > forkRc) {
343
344
    const std::string& errorMsg = "Failed to fork data-transfer session for tape drive";
    logForkError(errorMsg,params);
345
    return createExceptionResult(SEINTERNAL, errorMsg, true);
346
347
348
349
350
  // Else if this is the parent process
  } else if(0 < forkRc) {
    log::Param params[] = {log::Param("pid", forkRc)};
    m_log(LOG_INFO, "ProcessForker forked data-transfer session", params);

351
    return createForkSucceededResult(forkRc, true);
352
353
354

  // Else this is the child process
  } else {
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
    closeCmdReceiverSocket();

    try {
      exit(runDataTransferSession(rqst));
    } catch(castor::exception::Exception &ne) {
      log::Param params[] = {log::Param("message", ne.getMessage().str())};
      m_log(LOG_ERR, "Failed to run data-transfer session", params);
    } catch(std::exception &ne) {
      log::Param params[] = {log::Param("message", ne.what())};
      m_log(LOG_ERR, "Failed to run data-transfer session", params);
    } catch(...) {
      log::Param params[] = {log::Param("message",
        "Caught an unknown exception")};
      m_log(LOG_ERR, "Failed to run data-transfer session", params);
    }
    exit(1);
371
372
373
374
  }
}

//------------------------------------------------------------------------------
375
// handleForkLabelMsg
376
//------------------------------------------------------------------------------
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
castor::tape::tapeserver::daemon::ProcessForker::MsgHandlerResult 
  castor::tape::tapeserver::daemon::ProcessForker::handleForkLabelMsg(
  const ProcessForkerFrame &frame) {
  // Parse the incoming request
  messages::ForkLabel rqst;
  ProcessForkerUtils::parsePayload(frame, rqst);

  // Log the contents of the incomming request
  std::list<log::Param> params;
  params.push_back(log::Param("unitName", rqst.unitname()));
  params.push_back(log::Param("vid", rqst.vid()));
  m_log(LOG_INFO, "ProcessForker handling ForkLabel message", params);

  // Fork a label session
  const pid_t forkRc = fork();
392

393
394
395
  // If fork failed
  if(0 > forkRc) {
    // Log an error message and return
396
397
398
    const std::string& errorMsg = "Failed to fork label session for tape drive";
    logForkError(errorMsg,params);
    
399
    return createExceptionResult(SEINTERNAL, errorMsg, true);
400
401
402
403
404
405

  // Else if this is the parent process
  } else if(0 < forkRc) {
    log::Param params[] = {log::Param("pid", forkRc)};
    m_log(LOG_INFO, "ProcessForker forked label session", params);

406
    return createForkSucceededResult(forkRc, true);
407
408
409

  // Else this is the child process
  } else {
410
411
    closeCmdReceiverSocket();

412
413
414
415
416
417
418
419
420
421
422
423
424
425
    try {
      exit(runLabelSession(rqst));
    } catch(castor::exception::Exception &ne) {
      log::Param params[] = {log::Param("message", ne.getMessage().str())};
      m_log(LOG_ERR, "Failed to run label session", params);
    } catch(std::exception &ne) {
      log::Param params[] = {log::Param("message", ne.what())};
      m_log(LOG_ERR, "Failed to run label session", params);
    } catch(...) {
      log::Param params[] = {log::Param("message",
        "Caught an unknown exception")};
      m_log(LOG_ERR, "Failed to run label session", params);
    }
    exit(1);
426
  }
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
}

//------------------------------------------------------------------------------
// handleStopProcessForkerMsg
//------------------------------------------------------------------------------
castor::tape::tapeserver::daemon::ProcessForker::MsgHandlerResult 
  castor::tape::tapeserver::daemon::ProcessForker::
  handleStopProcessForkerMsg(const ProcessForkerFrame &frame) {

  // Parse the incoming request
  messages::StopProcessForker rqst;
  ProcessForkerUtils::parsePayload(frame, rqst);

  // Log the fact that the ProcessForker will not gracefully stop
  log::Param params[] = {log::Param("reason", rqst.reason())};
  m_log(LOG_INFO, "Gracefully stopping ProcessForker", params);
443

444
  return createReturnValueResult(0, false);
445
}
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464

//------------------------------------------------------------------------------
// runDataTransferSession
//------------------------------------------------------------------------------
int castor::tape::tapeserver::daemon::ProcessForker::runDataTransferSession(
  const messages::ForkDataTransfer &rqst) {
  const utils::DriveConfig driveConfig = getDriveConfig(rqst);

  std::list<log::Param> params;
  params.push_back(log::Param("unitName", driveConfig.unitName));
  m_log(LOG_INFO, "Data-transfer child-process started", params);

  const legacymsg::RtcpJobRqstMsgBody vdqmJob = getVdqmJob(rqst);

  castor::server::ProcessCap capUtils;
  const DataTransferSession::CastorConf dataTransferConfig =
    getDataTransferConfig(rqst);

  const int netTimeout = 10; // Timeout in seconds
465
  legacymsg::RmcProxyTcpIp rmc(m_log, rqst.rmcport(), netTimeout);
466
467

  const int sizeOfIOThreadPoolForZMQ = 1;
468
  messages::SmartZmqContext
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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
    zmqContext(instantiateZmqContext(sizeOfIOThreadPoolForZMQ));

  messages::TapeserverProxyZmq tapeserver(m_log,
    TAPE_SERVER_INTERNAL_LISTENING_PORT, netTimeout, zmqContext.get());

  castor::tape::System::realWrapper sysWrapper;

  // This try bloc will allow us to send a failure notification to the client
  // if we fail before the DataTransferSession has an opportunity to do so.
  std::auto_ptr<DataTransferSession> dataTransferSession;
  try {
    dataTransferSession.reset(new DataTransferSession (
      m_hostName,
      vdqmJob,
      m_log,
      sysWrapper,
      driveConfig,
      rmc,
      tapeserver,
      capUtils,
      dataTransferConfig));
  } catch (castor::exception::Exception & ex) {
    try {
      client::ClientProxy cl(vdqmJob);
      client::ClientInterface::RequestReport rep;
      cl.reportEndOfSessionWithError(ex.getMessageValue(), ex.code(), rep);
    } catch (...) {
      params.push_back(log::Param("errorMessage", ex.getMessageValue()));
      params.push_back(log::Param("errorCode", ex.code()));
      m_log(LOG_ERR, "Failed to notify the client of the failed session"
        " when setting up the data-transfer session", params);
    }
    throw;
  } catch (...) {
    try {
      m_log(LOG_ERR, "Got non castor exception error while constructing"
        " data-transfer session", params);
      client::ClientProxy cl(vdqmJob);
      client::ClientInterface::RequestReport rep;
      cl.reportEndOfSessionWithError(
       "Non-Castor exception when setting up the data-transfer session",
         SEINTERNAL, rep);
    } catch (...) {
      params.push_back(log::Param("errorMessage",
        "Non-Castor exception when setting up the data-transfer session"));
      m_log(LOG_ERR, "Failed to notify the client of the failed session"
        " when setting up the data-transfer session", params);
    }
    throw;
  }
  m_log(LOG_INFO, "Going to execute data-transfer session");
  return dataTransferSession->execute();
}

//------------------------------------------------------------------------------
// getDataTransferConfig
//------------------------------------------------------------------------------
castor::tape::tapeserver::daemon::DataTransferSession::CastorConf
  castor::tape::tapeserver::daemon::ProcessForker::getDataTransferConfig(
  const messages::ForkDataTransfer &msg) {
  DataTransferSession::CastorConf config;
  config.rtcopydBufsz = msg.memblocksize();
  config.rtcopydNbBufs = msg.nbmemblocks();
  config.tapeBadMIRHandlingRepair = msg.badmirhandling();
  config.tapebridgeBulkRequestMigrationMaxBytes =
    msg.bulkrequestmigrationmaxbytes();
  config.tapebridgeBulkRequestMigrationMaxFiles =
    msg.bulkrequestmigrationmaxfiles();
  config.tapebridgeBulkRequestRecallMaxBytes = msg.bulkrequestrecallmaxbytes();
  config.tapebridgeBulkRequestRecallMaxFiles = msg.bulkrequestrecallmaxfiles();
  config.tapebridgeMaxBytesBeforeFlush = msg.maxbytesbeforeflush();
  config.tapebridgeMaxFilesBeforeFlush = msg.maxfilesbeforeflush();
  config.tapeserverdDiskThreads = msg.diskthreadpoolsize();

  return config;
}

//------------------------------------------------------------------------------
// getVdqmJob
//------------------------------------------------------------------------------
castor::legacymsg::RtcpJobRqstMsgBody
  castor::tape::tapeserver::daemon::ProcessForker::getVdqmJob(
  const messages::ForkDataTransfer &msg) {
  castor::legacymsg::RtcpJobRqstMsgBody job;
  job.volReqId = msg.mounttransactionid();
  job.clientPort = msg.clientport();
  job.clientEuid = msg.clienteuid();
  job.clientEgid = msg.clientegid();
  castor::utils::copyString(job.clientHost, msg.clienthost());
  castor::utils::copyString(job.dgn, msg.dgn());
  castor::utils::copyString(job.driveUnit, msg.unitname());
  castor::utils::copyString(job.clientUserName, msg.clientusername());

  return job;
}

//------------------------------------------------------------------------------
// instantiateZmqContext
//------------------------------------------------------------------------------
void *castor::tape::tapeserver::daemon::ProcessForker::instantiateZmqContext(
  const int sizeOfIOThreadPoolForZMQ) {
  void *const zmqContext = zmq_init(sizeOfIOThreadPoolForZMQ);
  if(NULL == zmqContext) {
    char message[100];
    sstrerror_r(errno, message, sizeof(message));
    castor::exception::Exception ex;
575
576
    ex.getMessage() << "Child of ProcessForker failed to instantiate ZMQ"
      " context: " << message;
577
578
579
580
581
    throw ex;
  }
  std::ostringstream contextAddr;
  contextAddr << std::hex << zmqContext;
  log::Param params[] = {log::Param("contextAddr", contextAddr.str())};
582
  m_log(LOG_INFO, "Child of ProcessForker instantiated a ZMQ context", params);
583
584
585
586

  return zmqContext;
}

587
588
589
590
591
//------------------------------------------------------------------------------
// handlePendingSignals
//------------------------------------------------------------------------------
bool castor::tape::tapeserver::daemon::ProcessForker::handlePendingSignals() {
  try {
592
    // Handle a pending SIGCHLD by reaping the associated zombie(s)
593
594
    reapZombies();

595
596
    // For now there are no signals that require a gracefully shutdown of the
    // main loop of the ProcessForker
597
598
599
600
601
602
603
604
605
    return true; // The main event loop should continue
  } catch(castor::exception::Exception &ne) {
    castor::exception::Exception ex;
    ex.getMessage() << "Failed to handle pending signals: " <<
      ne.getMessage().str();
    throw ex;
  }
}

606
607
608
//------------------------------------------------------------------------------
// reapZombies
//------------------------------------------------------------------------------
609
void castor::tape::tapeserver::daemon::ProcessForker::reapZombies() {
610
611
612
613
614
615
616
617
618
619
620
  pid_t pid = 0;
  int waitpidStat = 0;
  while (0 < (pid = waitpid(-1, &waitpidStat, WNOHANG))) {
    handleReapedZombie(pid, waitpidStat);
  }
}

//------------------------------------------------------------------------------
// handleReapedZombie
//------------------------------------------------------------------------------
void castor::tape::tapeserver::daemon::ProcessForker::handleReapedZombie(
621
  const pid_t pid, const int waitpidStat) {
622
623
624
  try {
    logChildProcessTerminated(pid, waitpidStat);
    notifyTapeDaemonOfTerminatedProcess(pid, waitpidStat);
625
626
627
628
629
630
631
632
633
634
  } catch(castor::exception::Exception &ne) {
    castor::exception::Exception ex;
    ex.getMessage() << "Failed to handle reaped zombie: pid=" << pid <<
      ne.getMessage().str();
    throw ex;
  } catch(std::exception &ne) {
    castor::exception::Exception ex;
    ex.getMessage() << "Failed to handle reaped zombie: pid=" << pid <<
      ne.what();
    throw ex;
635
  } catch(...) {
636
637
638
639
    castor::exception::Exception ex;
    ex.getMessage() << "Failed to handle reaped zombie: pid=" << pid <<
      ": Caught an unknown exception";
    throw ex;
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
  }
} 

//------------------------------------------------------------------------------
// logChildProcessTerminated
//------------------------------------------------------------------------------
void castor::tape::tapeserver::daemon::ProcessForker::logChildProcessTerminated(
  const pid_t pid, const int waitpidStat) throw() {
  std::list<log::Param> params;
  params.push_back(log::Param("terminatedPid", pid));

  if(WIFEXITED(waitpidStat)) {
    params.push_back(log::Param("WEXITSTATUS", WEXITSTATUS(waitpidStat)));
  }

  if(WIFSIGNALED(waitpidStat)) {
    params.push_back(log::Param("WTERMSIG", WTERMSIG(waitpidStat)));
  }

  if(WCOREDUMP(waitpidStat)) {
    params.push_back(log::Param("WCOREDUMP", "true"));
  } else {
    params.push_back(log::Param("WCOREDUMP", "false"));
  }

  if(WIFSTOPPED(waitpidStat)) {
    params.push_back(log::Param("WSTOPSIG", WSTOPSIG(waitpidStat)));
  }

  if(WIFCONTINUED(waitpidStat)) {
    params.push_back(log::Param("WIFCONTINUED", "true"));
  } else {
    params.push_back(log::Param("WIFCONTINUED", "false"));
  }

  m_log(LOG_INFO, "ProcessForker child process terminated", params);
}

//------------------------------------------------------------------------------
// notifyTapeDaemonOfTerminatedProcess
//------------------------------------------------------------------------------
void castor::tape::tapeserver::daemon::ProcessForker::
  notifyTapeDaemonOfTerminatedProcess(const pid_t pid, const int waitpidStat) {
  try {
    if(WIFEXITED(waitpidStat)) {
      notifyTapeDaemonOfExitedProcess(pid, waitpidStat);
    } else if(WIFSIGNALED(waitpidStat)) {
      notifyTapeDaemonOfCrashedProcess(pid, waitpidStat);
    } else {
      castor::exception::Exception ex;
      ex.getMessage() << "Process died of unknown causes" << pid;
      throw ex;
    }
  } catch(castor::exception::Exception &ne) {
    castor::exception::Exception ex;
    ex.getMessage() << "Failed to notify TapeDaemon of process termination"
      ": pid=" << pid << ": " << ne.getMessage().str();
    throw ex;
  }
}

//------------------------------------------------------------------------------
// notifyTapeDaemonOfExitedProcess
//------------------------------------------------------------------------------
void castor::tape::tapeserver::daemon::ProcessForker::
  notifyTapeDaemonOfExitedProcess(const pid_t pid, const int waitpidStat) {
  try {
    messages::ProcessExited msg;
    msg.set_pid(pid);
    msg.set_exitcode(WEXITSTATUS(waitpidStat));

    log::Param params[] = {log::Param("pid", msg.pid()),
      log::Param("exitCode", msg.exitcode())};
    m_log(LOG_INFO, "Notifying TapeDaemon of process exit", params);

    ProcessForkerUtils::writeFrame(m_reaperSocket, msg);
  } catch(castor::exception::Exception &ne) {
    castor::exception::Exception ex;
    ex.getMessage() << "Failed to notify TapeDaemon of process exit: " <<
      ne.getMessage().str();
    throw ex;
  } catch(std::exception &se) {
    castor::exception::Exception ex;
    ex.getMessage() << "Failed to notify TapeDaemon of process exit: " <<
      se.what();
    throw ex;
  } catch(...) {
    castor::exception::Exception ex;
    ex.getMessage() << "Failed to notify TapeDaemon of process exit: "
      "Caught an unknown exception";
    throw ex;
  }
}

//------------------------------------------------------------------------------
// notifyTapeDaemonOfCrashedProcess
//------------------------------------------------------------------------------
void castor::tape::tapeserver::daemon::ProcessForker::
  notifyTapeDaemonOfCrashedProcess(const pid_t pid, const int waitpidStat) {
  try {
    messages::ProcessCrashed msg;
    msg.set_pid(pid);
    msg.set_signal(WTERMSIG(waitpidStat));

    log::Param params[] = {log::Param("pid", msg.pid()),
      log::Param("signal", msg.signal())};
    m_log(LOG_INFO, "Notifying TapeDaemon of process crash", params);

    ProcessForkerUtils::writeFrame(m_reaperSocket, msg);
  } catch(castor::exception::Exception &ne) {
    castor::exception::Exception ex;
    ex.getMessage() << "Failed to notify TapeDaemon of process crash: " <<
      ne.getMessage().str();
    throw ex;
  } catch(std::exception &se) {
    castor::exception::Exception ex;
    ex.getMessage() << "Failed to notify TapeDaemon of process crash: " <<
      se.what();
    throw ex;
  } catch(...) {
    castor::exception::Exception ex;
    ex.getMessage() << "Failed to notify TapeDaemon of process crash: "
      "Caught an unknown exception";
    throw ex;
  }
}
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781

//------------------------------------------------------------------------------
// runLabelSession
//------------------------------------------------------------------------------
int castor::tape::tapeserver::daemon::ProcessForker::runLabelSession(
  const messages::ForkLabel &rqst) {
  try {
    const utils::DriveConfig &driveConfig = getDriveConfig(rqst);
    const legacymsg::TapeLabelRqstMsgBody labelJob = getLabelJob(rqst);

    std::list<log::Param> params;
    params.push_back(log::Param("unitName", driveConfig.unitName));
    params.push_back(log::Param("vid", labelJob.vid));
    m_log(LOG_INFO, "Label-session child-process started", params);

    const int netTimeout = 10; // Timeout in seconds
782
    legacymsg::RmcProxyTcpIp rmc(m_log, rqst.rmcport(), netTimeout);
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
    legacymsg::NsProxy_TapeAlwaysEmpty ns;
    castor::tape::System::realWrapper sWrapper;
    LabelSession labelsession(
      rmc,
      ns,
      labelJob,
      m_log,
      sWrapper,
      driveConfig,
      rqst.force());
    labelsession.execute();
    return 0;
  } catch(castor::exception::Exception &ne) {
    castor::exception::Exception ex;
    ex.getMessage() << "Failed to run label session: " << ne.getMessage().str();
    throw ex;
  } catch(std::exception &se) {
    castor::exception::Exception ex;
    ex.getMessage() << "Failed to run label session: " << se.what();
    throw ex;
  } catch(...) {
        castor::exception::Exception ex;
    ex.getMessage() << "Failed to run label session"
      ": Caught an unknown exception";
    throw ex;
  }
}

//------------------------------------------------------------------------------
// getLabelJob
//------------------------------------------------------------------------------
castor::legacymsg::TapeLabelRqstMsgBody
  castor::tape::tapeserver::daemon::ProcessForker::getLabelJob(
  const messages::ForkLabel &msg) {
  castor::legacymsg::TapeLabelRqstMsgBody job;
  job.force = msg.force() ? 1 : 0;
  job.uid = msg.uid();
  job.gid = msg.gid();
  castor::utils::copyString(job.vid,msg.vid());
  castor::utils::copyString(job.drive, msg.unitname());
  castor::utils::copyString(job.dgn, msg.dgn());
  return job;
}
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900

//------------------------------------------------------------------------------
// createForkSucceededResult
//------------------------------------------------------------------------------
castor::tape::tapeserver::daemon::ProcessForker::MsgHandlerResult 
  castor::tape::tapeserver::daemon::ProcessForker::createForkSucceededResult(
  const pid_t pid, const bool continueMainEventLoop) {
  try {
    messages::ForkSucceeded reply;
    reply.set_pid(pid);

    MsgHandlerResult result;
    result.continueMainEventLoop = continueMainEventLoop;
    ProcessForkerUtils::serializePayload(result.reply, reply);
    
    return result;
  } catch(castor::exception::Exception &ne) {
    castor::exception::Exception ex;
    ex.getMessage() <<
      "Failed to create MsgHandlerResult containing a ForkSucceeded message:"
      << ne.getMessage().str();
    throw ex;
  }
}

//------------------------------------------------------------------------------
// createExceptionResult
//------------------------------------------------------------------------------
castor::tape::tapeserver::daemon::ProcessForker::MsgHandlerResult 
  castor::tape::tapeserver::daemon::ProcessForker::
  createExceptionResult(const uint32_t code, const std::string& message,
    const bool continueMainEventLoop) {
  try {
    messages::Exception reply;
    reply.set_code(code);
    reply.set_message(message);

    MsgHandlerResult result;
    result.continueMainEventLoop = continueMainEventLoop;
    ProcessForkerUtils::serializePayload(result.reply, reply);

    return result;
  } catch(castor::exception::Exception &ne) {
    castor::exception::Exception ex;
    ex.getMessage() <<
      "Failed to create MsgHandlerResult containing an Exception message:"
      << ne.getMessage().str();
    throw ex;
  }
}

//------------------------------------------------------------------------------
// createReturnValueResult
//------------------------------------------------------------------------------
castor::tape::tapeserver::daemon::ProcessForker::MsgHandlerResult
  castor::tape::tapeserver::daemon::ProcessForker::
  createReturnValueResult(const uint32_t value,
    const bool continueMainEventLoop) {
  try {
    messages::ReturnValue reply;
    reply.set_value(value);

    MsgHandlerResult result;
    result.continueMainEventLoop = continueMainEventLoop;
    ProcessForkerUtils::serializePayload(result.reply, reply);

    return result;
  } catch(castor::exception::Exception &ne) {
    castor::exception::Exception ex;
    ex.getMessage() <<
      "Failed to create MsgHandlerResult containing ReturnValue message:"
      << ne.getMessage().str();
    throw ex;
  }
}