-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathManager.cc
1213 lines (1040 loc) · 34 KB
/
Manager.cc
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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
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
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
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
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
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2019 Open Source Robotics Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "Manager.hh"
#include <csignal> // NOLINT(*)
#include <fcntl.h>
#ifndef _WIN32
#include <semaphore.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#else
#include <process.h>
/* Needed for std::min */
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#include <Processthreadsapi.h>
#endif
#include <signal.h>
#include <tinyxml2.h>
#include <condition_variable>
#include <ctime>
#include <limits>
#include <list>
#include <mutex>
#include <numeric>
#include <queue>
#include <random>
#include <string>
#include <thread>
#include <unordered_set>
#include <utility>
#include <vector>
#include <gz/common/Console.hh>
#include <gz/common/SignalHandler.hh>
#include <gz/common/SystemPaths.hh>
#include <gz/math/Rand.hh>
#include <gz/plugin/Loader.hh>
#include "gz/launch/config.hh"
#include "gz/launch/InstallationDirectories.hh"
#include "gz/launch/Plugin.hh"
#include "vendor/backward.hpp"
using namespace gz::launch;
using namespace std::chrono_literals;
#ifdef _WIN32
// Returns the last Win32 error, in string format. Returns an empty string if
// there is no error.
std::string GetLastErrorAsString()
{
// Get the error message ID, if any.
DWORD errorMessageID = ::GetLastError();
if(errorMessageID == 0) {
// No error message has been recorded
return std::string();
}
LPSTR messageBuffer = nullptr;
// Ask Win32 to give us the string version of that message ID.
// The parameters we pass in, tell Win32 to create the buffer that holds the
// message for us (because we don't yet know how long the message string.
// will be).
size_t size = FormatMessageA(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
errorMessageID,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPSTR)&messageBuffer,
0,
NULL);
// Copy the error message into a std::string.
std::string message(messageBuffer, size);
// Free the Win32's string's buffer.
LocalFree(messageBuffer);
return message;
}
#endif
/// \brief A class to encapsulate an executable (program) to run.
class Executable
{
/// \brief Default constructor
public: Executable() = default;
/// \brief Constructs a executable object with a name, process id, command,
/// and other options. This class is used primarily for internal
/// book keeping.
/// \param[in] _name Name of the executable. This is used for internal
/// book keeping, it is not (necessarily) the name of the executable that
/// will be run.
/// \param[in] _pid The pid in which the executable is run.
/// \param[in] _cmd The command and arguments that specify how to run the
/// executable.
/// \param[in] _autoRestart True if the executable should restart when it
/// is is killed.
/// \param[in] _envs Environment variables to set.
#ifndef _WIN32
public: Executable(const std::string &_name, const pid_t _pid,
const std::vector<std::string> &_cmd, bool _autoRestart,
const std::list<std::string> &_envs)
: name(_name), pid(_pid), command(_cmd), autoRestart(_autoRestart),
envs(_envs)
{}
#else
public: Executable(const std::string &_name, const HANDLE _pi,
const std::vector<std::string> &_cmd, bool _autoRestart,
const std::list<std::string> &_envs)
: name(_name), pi(_pi), command(_cmd), autoRestart(_autoRestart),
envs(_envs)
{}
#endif
/// \brief Name of the executable
public: std::string name = "";
/// \brief Process id in which the executable is run.
#ifndef _WIN32
public: pid_t pid = -1;
#else
public: HANDLE pi;
#endif
/// \brief The command to run.
public: std::vector<std::string> command;
/// \brief True will cause the command to restart on kill
public: bool autoRestart = false;
/// \brief Environment variables.
public: std::list<std::string> envs;
};
/// \brief Private data variables for the Gazebo class.
class gz::launch::ManagerPrivate
{
/// \brief Constructor.
public: ManagerPrivate();
/// \brief Destructor.
public: ~ManagerPrivate();
/// \brief Parse a configuration string.
/// \param[in] _string XML configuration string.
/// \return True on success.
public: bool ParseConfig(const std::string &_string);
/// \brief Fork a new process for a command specified by _exec. This
/// function will create a new Executable and add it to the executables
/// list.
/// \param[in] _exec An executable definition to run.
/// \return True on success.
public: bool RunExecutable(const Executable &_exec);
/// \brief Fork a new process for a command specific by _cmd.
/// \param[in] _name A unique name given to the command. This name is
/// used for book keeping and control of the process.
/// \param[in] _cmd A vector of strings where the first string is
/// expected to be the name of the executable to run, and subsequent
/// strings are arguments.
/// \param[in] _autoRestart True if the executable should auto restart on
/// death.
/// \param[in] _envs Environment variables to set.
/// \return True on success.
public: bool RunExecutable(const std::string &_name,
const std::vector<std::string> &_cmd,
const bool _autoRestart,
const std::list<std::string> &_envs);
/// \brief Stop all executables
public: void ShutdownExecutables();
/// \brief Stop running. This can be used to end a Run().
/// \return True if running, False if the state was not running.
public: bool Stop();
/// \brief Load a plugin based on data contained in an XML element.
/// \param[in] _elem Pointer to the XML element containing the plugin
/// information.
public: void LoadPlugin(const tinyxml2::XMLElement *_elem);
/// \brief Handle SIG_INT and SIG_TERM signals
/// \param[in] _sig The signal
private: void OnSigIntTerm(int _sig);
/// \brief Handle SIG_CHILD
/// \param[in] _sig The signal
private: static void OnSigChild(int _sig);
/// \brief Start the worker thread to service stopped children.
public: void StartWorkerThread();
/// \brief Thread to handle restarting stopped children.
private: void RestartLoop();
/// \brief Parse executable configurations.
/// \param[in] _elem XML element that contains an <executable>
private: void ParseExecutables(const tinyxml2::XMLElement *_elem);
/// \brief Parse <env> elements.
/// \return List of environment variable name,value pairs.
private: std::list<std::string> ParseEnvs(const tinyxml2::XMLElement *_elem);
/// \brief Set environment variables.
/// \param[in] _envs List of environment variable name,value pairs.
private: void SetEnvs(const std::list<std::string> &_envs);
/// \brief Parse executable wrappers. Executable wrappers allow a plugin
/// to run in a process.
/// \param[in] _elem XML element that contains an <executable_wrapper>
private: void ParseExecutableWrappers(const tinyxml2::XMLElement *_elem);
/// \brief A list of executables that are running, or have been run.
public: std::list<Executable> executables;
/// \brief A list of children that were stopped to attempt restarts
#ifndef _WIN32
public: std::queue<pid_t> stoppedChildren;
#else
public: std::queue<HANDLE> stoppedChildren;
#endif
/// \brief Semaphore to prevent restartThread from being a spinlock
#ifndef _WIN32
public: sem_t *stoppedChildSem;
#else
public: HANDLE stoppedChildSem;
public: HANDLE pi;
#endif
/// \brief Name of the semaphore created by stoppedChildSem.
private: std::string stoppedChildSemName;
/// \brief Thread containing the restart loop
private: std::thread restartThread;
/// \brief All the plugins
public: std::unordered_set<launch::PluginPtr> plugins;
/// \brief All the wrapped plugins
#ifndef _WIN32
public: std::list<pid_t> wrappedPlugins;
#else
public: std::list<PROCESS_INFORMATION> wrappedPlugins;
#endif
/// \brief Mutex to protect the executables list.
public: std::mutex executablesMutex;
/// \brief A condition variable used by SIG_INT and Manager::Run.
public: std::condition_variable runCondition;
/// \brief A mutex used in conjunction with runCondition.
public: std::mutex runMutex;
/// \brief True if running.
public: std::atomic<bool> running = false;
/// \brief True indicates that this process is the master (main) process.
public: bool master = false;
/// \brief Our signal handler.
public: std::unique_ptr<common::SignalHandler> sigHandler = nullptr;
/// \brief Backward signal handler
public: std::unique_ptr<backward::SignalHandling> backward = nullptr;
/// \brief Top level environment variables.
public: std::list<std::string> envs;
/// \brief Pointer to myself. This is used in the signal handlers.
/// A raw pointer is acceptable here since it is used only internally.
public: static ManagerPrivate *myself;
};
// Init the static pointer.
ManagerPrivate *ManagerPrivate::myself = nullptr;
/////////////////////////////////////////////////
Manager::Manager()
:dataPtr(new ManagerPrivate())
{
this->dataPtr->myself = this->dataPtr.get();
std::string homePath;
gz::common::env(GZ_HOMEDIR, homePath);
// Make sure to initialize logging.
gzLogInit(gz::common::joinPaths(homePath, ".gz"), "launch.log");
if (!this->dataPtr->sigHandler->Initialized())
gzerr << "signal(2) failed while setting up for SIGINT" << std::endl;
}
/////////////////////////////////////////////////
Manager::~Manager()
{
this->dataPtr->Stop();
}
/////////////////////////////////////////////////
bool Manager::RunConfig(const std::string &_config)
{
std::unique_lock<std::mutex> lock(this->dataPtr->runMutex);
// This is the master.
this->dataPtr->master = true;
// Parse the configuration string, and run all the specified commands.
if (!this->dataPtr->ParseConfig(_config))
return false;
// Child processes should exit
if (!this->dataPtr->master)
return true;
// Get whether or not we should run (block).
this->dataPtr->running = !this->dataPtr->executables.empty() ||
!this->dataPtr->plugins.empty();
// Start thread to service child signals.
this->dataPtr->StartWorkerThread();
// Wait for a shutdown event, or for all the executables to quit.
while (this->dataPtr->running && (!this->dataPtr->executables.empty() ||
!this->dataPtr->plugins.empty()))
{
this->dataPtr->runCondition.wait(lock);
}
this->dataPtr->running = false;
// Stop plugins.
this->dataPtr->plugins.clear();
// Stop executables.
this->dataPtr->ShutdownExecutables();
return true;
}
/////////////////////////////////////////////////
bool Manager::Stop()
{
return this->dataPtr->Stop();
}
/////////////////////////////////////////////////
ManagerPrivate::ManagerPrivate()
{
// Register a normal signal handler
this->sigHandler.reset(new common::SignalHandler());
this->sigHandler->AddCallback(
std::bind(&ManagerPrivate::OnSigIntTerm, this, std::placeholders::_1));
{
// The semaphore we initialize in the next section needs a unique name, so
// we need to seed a random number generator with a quality random number.
// Especially time(0) itself is not a good seed as there may be multiple
// processes launched at the same time.
const auto time_seed = static_cast<size_t>(std::time(nullptr));
const auto pid_seed = std::hash<std::thread::id>()(
std::this_thread::get_id());
std::seed_seq seed_value{time_seed, pid_seed};
std::vector<std::uint32_t> seeds(1);
seed_value.generate(seeds.begin(), seeds.end());
math::Rand::Seed(seeds[0]);
}
const auto semRandomId = math::Rand::IntUniform(0,
std::numeric_limits<int32_t>::max());
// Initialize semaphore
this->stoppedChildSemName = std::string("gz-launch-") +
std::to_string(semRandomId);
#ifndef _WIN32
this->stoppedChildSem = sem_open(this->stoppedChildSemName.c_str(), O_CREAT,
0644, 1);
if (this->stoppedChildSem == SEM_FAILED)
{
gzerr << "Error initializing semaphore " << this->stoppedChildSemName
<< ": " << strerror(errno) << std::endl;
}
#else
this->stoppedChildSem = CreateSemaphoreA(
NULL, 0, LONG_MAX, this->stoppedChildSemName.c_str());
if (this->stoppedChildSem == nullptr)
{
gzerr << "Error initializing semaphore " << this->stoppedChildSemName
<< ": " << GetLastErrorAsString() << std::endl;
}
#endif
#ifndef _WIN32
// Register a signal handler to capture child process death events.
if (signal(SIGCHLD, ManagerPrivate::OnSigChild) == SIG_ERR)
gzerr << "signal(2) failed while setting up for SIGCHLD" << std::endl;
// Register backward signal handler for other signals
std::vector<int> signals =
{
SIGABRT, // Abort signal from abort(3)
SIGBUS, // Bus error (bad memory access)
SIGFPE, // Floating point exception
SIGILL, // Illegal Instruction
SIGIOT, // IOT trap. A synonym for SIGABRT
// SIGQUIT, // Quit from keyboard
SIGSEGV, // Invalid memory reference
SIGSYS, // Bad argument to routine (SVr4)
SIGTRAP, // Trace/breakpoint trap
SIGXCPU, // CPU time limit exceeded (4.2BSD)
SIGXFSZ, // File size limit exceeded (4.2BSD)
};
this->backward = std::make_unique<backward::SignalHandling>(signals);
#else
#endif
}
/////////////////////////////////////////////////
ManagerPrivate::~ManagerPrivate()
{
if (this->master)
{
#ifndef _WIN32
if (sem_close(this->stoppedChildSem) == -1)
{
gzerr << "Failed to close semaphore " << this->stoppedChildSemName
<< ": " << strerror(errno) << std::endl;
}
if (sem_unlink(this->stoppedChildSemName.c_str()) == -1)
{
gzerr << "Failed to unlink semaphore " << this->stoppedChildSemName
<< ": " << strerror(errno) << std::endl;
}
#else
int retVal = CloseHandle(this->stoppedChildSem) ? 0 : -1;
if (retVal == -1)
{
gzerr << "Failed to close semaphore: " << strerror(errno)
<< std::endl;
}
#endif
}
}
/////////////////////////////////////////////////
bool ManagerPrivate::Stop()
{
if (this->runMutex.try_lock())
{
if (this->running)
{
this->running = false;
}
this->runMutex.unlock();
this->runCondition.notify_all();
// Signal the restart thread to stop
#ifndef _WIN32
sem_post(this->stoppedChildSem);
#else
// Wait until child process exits.
int retVal = ReleaseSemaphore(this->stoppedChildSem, 1, nullptr);
if (retVal != 0)
{
gzerr << "Error Releasing Semaphore "
<< GetLastErrorAsString() << std::endl;
}
#endif
if (this->restartThread.joinable())
this->restartThread.join();
}
return this->running;
}
/////////////////////////////////////////////////
void ManagerPrivate::OnSigIntTerm(int _sig)
{
gzdbg << "OnSigIntTerm Received signal[" << _sig << "]\n";
this->Stop();
}
/////////////////////////////////////////////////
void ManagerPrivate::OnSigChild(int _sig)
{
// Retreive the stopped child's PID, append, and signal the consumer.
#ifndef _WIN32
// This is a signal handler, so be careful not to do any operations
// that you are not allowed to do.
// Ref: http://man7.org/linux/man-pages/man7/signal-safety.7.html
(void) _sig; // Commenting _sig above confuses codecheck
pid_t p;
int status;
if ((p = waitpid(-1, &status, WNOHANG)) != -1)
{
myself->stoppedChildren.push(p);
sem_post(myself->stoppedChildSem);
}
#endif
}
/////////////////////////////////////////////////
void ManagerPrivate::StartWorkerThread()
{
// Spawn thread to monitor restarting children.
this->restartThread = std::thread(&ManagerPrivate::RestartLoop, this);
}
/////////////////////////////////////////////////
void ManagerPrivate::RestartLoop()
{
#ifndef _WIN32
sigset_t chldmask;
if ((sigemptyset(&chldmask) == -1) || (sigaddset(&chldmask, SIGCHLD) == -1))
{
gzerr << "Failed to initialize signal mask: "
<< strerror(errno) << std::endl;
return;
}
while (this->running)
{
// Wait for the signal handler to signal that a child has exited.
int s = sem_wait(this->stoppedChildSem);
if (s == -1)
{
if (errno != EINTR)
gzwarn << "sem_wait error: "
<< strerror(errno) << std::endl;
continue;
}
// Block SIGCHLD while consuming queue.
if (sigprocmask(SIG_BLOCK, &chldmask, NULL) == -1)
{
gzerr << "Failed to setup block for SIGCHLD: "
<< strerror(errno) << std::endl;
continue;
}
// Consume stopped children from the queue.
while (!this->stoppedChildren.empty())
{
std::lock_guard<std::mutex> mutex(this->executablesMutex);
// Executable to restart
Executable restartExec;
pid_t p = this->stoppedChildren.front();
this->stoppedChildren.pop();
// Find the executable
for (std::list<Executable>::iterator iter = this->executables.begin();
iter != this->executables.end(); ++iter)
{
if (iter->pid == p)
{
gzdbg << "Death of process[" << p << "] with name["
<< iter->name << "].\n";
// Restart if autoRestart is enabled
if (iter->autoRestart)
restartExec = *iter;
this->executables.erase(iter);
break;
}
}
if (!restartExec.name.empty() && !restartExec.command.empty())
{
gzdbg << "Restarting process with name[" << restartExec.name << "]\n";
this->RunExecutable(restartExec);
}
this->runCondition.notify_all();
}
// Unblock SIGCHLD
if (sigprocmask(SIG_UNBLOCK, &chldmask, NULL) == -1)
{
gzerr << "Failed to unblock SIGCHLD: " << strerror(errno) << std::endl;
continue;
}
}
#else
// Create a vector of monitor threads that wait for each process to stop.
std::vector<std::thread> monitors;
for (const Executable &exec : this->executables)
monitors.push_back(std::thread([&] {
WaitForSingleObject(exec.pi, INFINITE);
myself->stoppedChildren.push(exec.pi);
}));
while (this->running)
{
// Wait for the signal handler to signal that a child has exited.
int s = WaitForSingleObject(this->stoppedChildSem, INFINITE);
if (!this->running)
break;
// Consume stopped children from the queue.
while (!this->stoppedChildren.empty())
{
std::lock_guard<std::mutex> mutex(this->executablesMutex);
// Executable to restart
Executable restartExec;
HANDLE p = this->stoppedChildren.front();
this->stoppedChildren.pop();
// Find the executable
for (std::list<Executable>::iterator iter = this->executables.begin();
iter != this->executables.end(); ++iter)
{
if (iter->pi == p)
{
gzdbg << "Death of process[" << p << "] with name ["
<< iter->name << "].\n";
// Restart if autoRestart is enabled
if (iter->autoRestart)
restartExec = *iter;
this->executables.erase(iter);
break;
}
}
if (!restartExec.name.empty() && !restartExec.command.empty())
{
gzdbg << "Restarting process with name[" << restartExec.name << "]\n";
this->RunExecutable(restartExec);
}
this->runCondition.notify_all();
}
}
#endif
}
/////////////////////////////////////////////////
bool ManagerPrivate::ParseConfig(const std::string &_config)
{
tinyxml2::XMLDocument xmlDoc;
// Load the XML configuration file into TinyXML
if (xmlDoc.Parse(_config.c_str()) != tinyxml2::XML_SUCCESS)
{
gzerr << "Unable to parse configuration. Your XML might be invalid.\n";
return false;
}
// Get the root element.
tinyxml2::XMLElement *root = xmlDoc.FirstChildElement("gz");
if (!root)
{
gzerr << "Invalid config file, missing `<gz>` element\n";
return false;
}
// Keep the environment variables in memory. See manpage for putenv.
this->envs = this->ParseEnvs(root);
this->SetEnvs(this->envs);
// Parse and create all the <executable> elements.
this->ParseExecutables(root);
// Parse and create all the <executable_wrapper> elements.
if (this->master)
this->ParseExecutableWrappers(root);
// Parse and create all the <plugin> elements.
if (this->master)
{
// Process all the plugins.
tinyxml2::XMLElement *pluginElem = root->FirstChildElement("plugin");
while (pluginElem)
{
this->LoadPlugin(pluginElem);
pluginElem = pluginElem->NextSiblingElement("plugin");
}
}
return true;
}
/////////////////////////////////////////////////
bool ManagerPrivate::RunExecutable(const Executable &_exec)
{
return this->RunExecutable(_exec.name, _exec.command, _exec.autoRestart,
_exec.envs);
}
/////////////////////////////////////////////////
bool ManagerPrivate::RunExecutable(const std::string &_name,
const std::vector<std::string> &_cmd, bool _autoRestart,
const std::list<std::string> &_envs)
{
// Check for empty
if (_cmd.empty())
{
gzerr << "Empty command.\n";
return false;
}
#ifdef _WIN32
typedef struct MyData {
std::vector<std::string> _cmd;
HANDLE stoppedChildSem;
} MYDATA, *PMYDATA;
SetEnvs(_envs);
PMYDATA pDataArray = (PMYDATA) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
sizeof(MYDATA));
if (pDataArray == nullptr)
{
gzerr << "allocation fails " << GetLastErrorAsString() << '\n';
return false;
}
for (auto & cmd : _cmd){
pDataArray->_cmd.push_back(cmd);
}
pDataArray->stoppedChildSem = this->stoppedChildSem;
auto dontThreadOnMe = [](LPVOID lpParam) -> DWORD {
PMYDATA pDataArray;
pDataArray = (PMYDATA)lpParam;
// Create a vector of char* in the child process
std::vector<char*> cstrings;
cstrings.push_back("C:\\WINDOWS\\SYSTEM32\\CMD.EXE");
cstrings.push_back("cmd.exe ");
cstrings.push_back("/c");
for (const std::string &part : pDataArray->_cmd)
{
cstrings.push_back(const_cast<char *>(part.c_str()));
}
// Add the nullptr termination.
cstrings.push_back(nullptr);
// Run the command, replacing the current process image
if (_spawnv(_P_WAIT , cstrings[0], &cstrings[0]) < 0)
{
gzerr << "Unable to run command["
<< std::accumulate(
pDataArray->_cmd.begin(),
pDataArray->_cmd.end(),
std::string(""))
<< "] " << GetLastErrorAsString() << "\n";
return -1;
}
if (!ReleaseSemaphore(pDataArray->stoppedChildSem, 1, nullptr))
{
gzerr << "Error Releasing Semaphore "
<< GetLastErrorAsString() << std::endl;
}
if(pDataArray != NULL)
{
HeapFree(GetProcessHeap(), 0, pDataArray);
pDataArray = NULL; // Ensure address is not reused.
}
return 0;
};
auto thread = CreateThread(
nullptr, 0, dontThreadOnMe, pDataArray, 0, nullptr);
if (thread == nullptr) {
gzerr << "Error creating thread on Windows "
<< GetLastErrorAsString() << '\n';
}
else
{
std::lock_guard<std::mutex> mutex(this->executablesMutex);
this->master = true;
// Store the PID in the parent process.
this->executables.push_back(Executable(
_name, thread, _cmd, _autoRestart, _envs));
}
#else
// Fork a process for the command
pid_t pid = fork();
// If parent process...
if (pid)
{
gzdbg << "Forked a process for [" << _name << "] command["
<< std::accumulate(_cmd.begin(), _cmd.end(), std::string("")) << "]\n"
<< std::flush;
std::lock_guard<std::mutex> mutex(this->executablesMutex);
this->master = true;
// Store the PID in the parent process.
this->executables.push_back(Executable(
_name, pid, _cmd, _autoRestart, _envs));
}
// Else child process...
else
{
// A child is not the master
this->master = false;
// Create a vector of char* in the child process
std::vector<char*> cstrings;
for (const std::string &part : _cmd)
{
cstrings.push_back(const_cast<char *>(part.c_str()));
}
// Add the nullptr termination.
cstrings.push_back(nullptr);
// Remove from foreground process group.
setpgid(0, 0);
this->SetEnvs(_envs);
// Run the command, replacing the current process image
if (execvp(cstrings[0], &cstrings[0]) < 0)
{
gzerr << "Unable to run command["
<< std::accumulate(
_cmd.begin(),
_cmd.end(),
std::string("")) << "]\n";
return false;
}
}
#endif
return true;
}
/////////////////////////////////////////////////
void ManagerPrivate::ShutdownExecutables()
{
std::lock_guard<std::mutex> mutex(this->executablesMutex);
#ifndef _WIN32
// Remove the sigchld signal handler
signal(SIGCHLD, nullptr);
#endif
// Create a vector of monitor threads that wait for each process to stop.
std::vector<std::thread> monitors;
for (const Executable &exec : this->executables)
monitors.push_back(std::thread([&] {
#ifndef _WIN32
waitpid(exec.pid, nullptr, 0);
#else
WaitForSingleObject(exec.pi, INFINITE);
int retVal = ReleaseSemaphore(myself->stoppedChildSem, 1, nullptr);
if (retVal != 0)
{
gzerr << "Error Releasing Semaphore: "
<< GetLastErrorAsString() << std::endl;
}
#endif
}));
#ifndef _WIN32
for (const pid_t &wrapper : this->wrappedPlugins)
monitors.push_back(std::thread([&] {
waitpid(wrapper, nullptr, 0);
}));
#else
for (const PROCESS_INFORMATION &wrapper : this->wrappedPlugins)
monitors.push_back(std::thread([&] {
WaitForSingleObject(wrapper.hProcess, INFINITE);
int retVal = ReleaseSemaphore(myself->stoppedChildSem, 1, nullptr);
if (retVal != 0)
{
gzerr << "Error Releasing Semaphore: "
<< GetLastErrorAsString() << std::endl;
}
}));
#endif
// Shutdown the processes
for (const Executable &exec : this->executables)
{
gzdbg << "Killing the process[" << exec.name
#ifndef _WIN32
<< "] with PID[" << exec.pid << "]\n";
kill(exec.pid, SIGINT);
#else
<< "]\n";
#endif
}
#ifndef _WIN32
// Shutdown the wrapped plugins
for (const pid_t &pid : this->wrappedPlugins)
#else
for (const PROCESS_INFORMATION &pid : this->wrappedPlugins)
#endif
{
#ifndef _WIN32
gzdbg << "Killing the wrapped plugin PID[" << pid << "]\n";
kill(pid, SIGINT);
#else
gzdbg << "Killing the wrapped plugin PID[" << pid.dwProcessId << "]\n";
TerminateProcess(pid.hProcess, 0);
#endif
}
gzdbg << "Waiting for each process to end\n";
// Wait for all the monitors to stop
for (std::thread &m : monitors)
m.join();
gzdbg << "All finished\n";
}
//////////////////////////////////////////////////
void ManagerPrivate::ParseExecutables(const tinyxml2::XMLElement *_elem)
{
// Process all the executables.
const tinyxml2::XMLElement *execElem = _elem->FirstChildElement("executable");
// This "i" variable is just used for output messages.
for (int i = 0; execElem && this->master; ++i)
{
bool autoRestart = false;
bool valid = true;
std::vector<std::string> cmdParts;
// Get the executable's name
std::string nameStr = execElem->Attribute("name");
if (nameStr.empty())
{
valid = false;
gzerr << "Invalid configuration file, "
<< "missing name attribute for the " << i << " <executable> element."
<< std::endl;
}
// Get the command
const tinyxml2::XMLElement *cmdElem =
execElem->FirstChildElement("command");
if (!cmdElem)
{
valid = false;
gzerr << "Invalid configuration file, "
<< "missing <command> child element "
<< " of <executable name=\"" << nameStr << "\">\n";
}
else
{
std::vector<std::string> parts =
gz::common::split(cmdElem->GetText(), " ");
std::move(parts.begin(), parts.end(), std::back_inserter(cmdParts));
}
// Get the <auto_restart> element. It is okay if the <auto_restart> element
// is not present
const tinyxml2::XMLElement *restartElem = execElem->FirstChildElement(
"auto_restart");
if (restartElem && restartElem->GetText())
{
std::string txt = gz::common::lowercase(restartElem->GetText());
autoRestart = txt == "true" || txt == "1" || txt == "t";
}
std::list<std::string> localEnvs = this->ParseEnvs(execElem);
if (valid)
{
if (!this->RunExecutable(nameStr, cmdParts, autoRestart, localEnvs))