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
// Copyright (C) 2015-2024 Internet Systems Consortium, Inc. ("ISC")
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include <config.h>

#include <asiolink/io_service_signal.h>
#include <asiolink/interval_timer.h>
#include <asiolink/process_spawn.h>
#include <gtest/gtest.h><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <signal.h><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <stdint.h><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <errno.h><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <sys/types.h><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.
#include <unistd.h><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.

#include <testutils/gtest_utils.h>

namespace {

using namespace isc;
using namespace isc::asiolink;
using namespace std;
namespace ph = std::placeholders;

/// @brief Test fixture for testing the use of ProcessSpawn with IO service
/// signals.
///
/// This fixture is exercises ProcessSpawn using IO service signaling.
class ProcessSpawnTest : public ::testing::Test {
public:
    /// @brief IOService instance to process IO.
    asiolink::IOServicePtr io_service_;

    /// @brief Single instance of IOService.
    static asiolink::IOServicePtr getIOService() {
        static asiolink::IOServicePtr io_service(new asiolink::IOService());
        return (io_service);
    }

    /// @brief Failsafe timer to ensure test(s) do not hang.
    isc::asiolink::IntervalTimer test_timer_;

    /// @brief Maximum time should be allowed to run.
    int test_time_ms_;

    /// @brief IOSignalSet object.
    IOSignalSetPtr io_signal_set_;

    /// @brief Vector to record the signal values received.
    std::vector<int> processed_signals_;

    /// @brief Constructor.
    ProcessSpawnTest() :
        io_service_(getIOService()), test_timer_(io_service_),
        test_time_ms_(0), io_signal_set_(), processed_signals_() {
        ProcessSpawn::setIOService(getIOService());

        io_signal_set_.reset(new IOSignalSet(io_service_,
                                             std::bind(&ProcessSpawnTest::processSignal,
                                                       this, ph::_1)));
        io_signal_set_->add(SIGCHLD);
    }

    /// @brief Destructor.
    ~ProcessSpawnTest() {
        io_signal_set_->remove(SIGCHLD);
        io_signal_set_.reset();
        // Make sure the cancel handler for the IOSignalSet is called.
        io_service_->stopAndPoll();
    }

    /// @brief Method used as the IOSignalSet handler.
    ///
    /// Records the value of the given signal and checks if the desired
    /// number of signals have been received.  If so, the IOService is
    /// stopped which will cause IOService::run() to exit, returning control
    /// to the test.
    ///
    /// @param signum signal number.
    void processSignal(int signum) {
        // Remember the signal we got.
        processed_signals_.push_back(signum);
    }

    /// @brief Sets the failsafe timer for the test to the given time.
    ///
    /// @param  test_time_ms maximum time in milliseconds the test should
    /// be allowed to run.
    void setTestTime(int test_time_ms) {
        // Fail safe shutdown
        test_time_ms_ = test_time_ms;
        test_timer_.setup(std::bind(&ProcessSpawnTest::testTimerHandler, this),
                          test_time_ms_, asiolink::IntervalTimer::ONE_SHOT);
    }

    /// @brief Failsafe timer expiration handler.
    void testTimerHandler() {
        io_service_->stop();
        FAIL() << "Test Time: " << test_time_ms_ << " expired";
    }
};

// This test verifies that the external application can be ran with
// arguments and that the exit code is gathered.
TEST_F(ProcessSpawnTest, spawnWithArgs) {<--- syntax error
    vector<string> args;
    args.push_back("-e");
    args.push_back("64");

    ProcessSpawn process(ProcessSpawn::ASYNC, TEST_SCRIPT_SH, args);
    pid_t pid = 0;
    ASSERT_NO_THROW(pid = process.spawn());

    // Set test fail safe.
    setTestTime(1000);

    // SIGCHLD signal.
    io_service_->runOne();

    // waitForProcess handler.
    // ProcessSpawnTest::processSignal handler.
    io_service_->runOne();

    // Poll to be sure.
    io_service_->poll();

    ASSERT_EQ(1, processed_signals_.size());
    ASSERT_EQ(SIGCHLD, processed_signals_[0]);

    // Exit code 64 as requested.
    EXPECT_EQ(64, process.getExitStatus(pid));
}

// This test verifies that the external application can be ran with
// arguments and environment variables that the exit code is gathered.
TEST_F(ProcessSpawnTest, spawnWithArgsAndEnvVars) {
    vector<string> args;
    vector<string> vars;
    args.push_back("-v");
    args.push_back("TEST_VARIABLE_NAME");
    args.push_back("TEST_VARIABLE_VALUE");
    vars.push_back("TEST_VARIABLE_NAME=TEST_VARIABLE_VALUE");

    ProcessSpawn process(ProcessSpawn::ASYNC, TEST_SCRIPT_SH, args, vars);
    pid_t pid = 0;
    ASSERT_NO_THROW(pid = process.spawn());

    // Set test fail safe.
    setTestTime(1000);

    // SIGCHLD signal.
    io_service_->runOne();

    // waitForProcess handler.
    // ProcessSpawnTest::processSignal handler.
    io_service_->runOne();

    // Poll to be sure.
    io_service_->poll();

    ASSERT_EQ(1, processed_signals_.size());
    ASSERT_EQ(SIGCHLD, processed_signals_[0]);

    // 56 means successful comparison of env vars.
    EXPECT_EQ(56, process.getExitStatus(pid));
}

// This test verifies that the single ProcessSpawn object can be used
// to start two processes and that their status codes can be gathered.
// It also checks that it is possible to clear the status of the
// process.
TEST_F(ProcessSpawnTest, spawnTwoProcesses) {
    vector<string> args;
    args.push_back("-p");

    ProcessSpawn process(ProcessSpawn::ASYNC, TEST_SCRIPT_SH, args);
    pid_t pid1 = 0;
    ASSERT_NO_THROW(pid1 = process.spawn());

    // Set test fail safe.
    setTestTime(1000);

    // SIGCHLD signal.
    io_service_->runOne();

    // waitForProcess handler.
    // ProcessSpawnTest::processSignal handler.
    io_service_->runOne();

    // Poll to be sure.
    io_service_->poll();

    ASSERT_EQ(1, processed_signals_.size());
    ASSERT_EQ(SIGCHLD, processed_signals_[0]);

    pid_t pid2 = 0;
    ASSERT_NO_THROW(pid2 = process.spawn());

    // Set test fail safe.
    setTestTime(1000);

    // SIGCHLD signal.
    io_service_->runOne();

    // waitForProcess handler.
    // ProcessSpawnTest::processSignal handler.
    io_service_->runOne();

    // Poll to be sure.
    io_service_->poll();

    ASSERT_EQ(2, processed_signals_.size());
    ASSERT_EQ(SIGCHLD, processed_signals_[0]);
    ASSERT_EQ(SIGCHLD, processed_signals_[1]);

    EXPECT_NE(process.getExitStatus(pid1), process.getExitStatus(pid2));

    // Clear the status of the first process. An attempt to get the status
    // for the cleared process should result in exception. But, there should
    // be no exception for the second process.
    process.clearState(pid1);
    EXPECT_THROW(process.getExitStatus(pid1), InvalidOperation);
    EXPECT_NO_THROW(process.getExitStatus(pid2));

    process.clearState(pid2);
    EXPECT_THROW(process.getExitStatus(pid2), InvalidOperation);
}

// This test verifies that the external application can be ran without
// arguments and that the exit code is gathered.
TEST_F(ProcessSpawnTest, spawnNoArgs) {
    ProcessSpawn process(ProcessSpawn::ASYNC, TEST_SCRIPT_SH);
    pid_t pid = 0;
    ASSERT_NO_THROW(pid = process.spawn());

    // Set test fail safe.
    setTestTime(1000);

    // SIGCHLD signal.
    io_service_->runOne();

    // waitForProcess handler.
    // ProcessSpawnTest::processSignal handler.
    io_service_->runOne();

    // Poll to be sure.
    io_service_->poll();

    ASSERT_EQ(1, processed_signals_.size());
    ASSERT_EQ(SIGCHLD, processed_signals_[0]);

    // 32 means no args.
    EXPECT_EQ(32, process.getExitStatus(pid));

    ASSERT_NO_THROW(pid = process.spawn(true));

    // Set test fail safe.
    setTestTime(1000);

    // SIGCHLD signal.
    io_service_->runOne();

    // waitForProcess handler.
    // ProcessSpawnTest::processSignal handler.
    io_service_->runOne();

    // Poll to be sure.
    io_service_->poll();

    ASSERT_EQ(2, processed_signals_.size());
    ASSERT_EQ(SIGCHLD, processed_signals_[0]);
    ASSERT_EQ(SIGCHLD, processed_signals_[1]);

    EXPECT_THROW(process.getExitStatus(pid), InvalidOperation);
}

// This test verifies that the EXIT_FAILURE code is returned when
// application can't be executed.
TEST_F(ProcessSpawnTest, invalidExecutable) {
    std::string expected = "File not found: foo";
    ASSERT_THROW_MSG(ProcessSpawn process(ProcessSpawn::ASYNC, "foo"),
                     ProcessSpawnError, expected);

    std::string name = INVALID_TEST_SCRIPT_SH;

    expected = "File not executable: ";
    expected += name;
    ASSERT_THROW_MSG(ProcessSpawn process(ProcessSpawn::ASYNC, name),
                     ProcessSpawnError, expected);
}

// This test verifies that the full command line for the process is
// returned.
TEST_F(ProcessSpawnTest, getCommandLine) {
    {
        // Case 1: arguments present.
        ProcessArgs args;
        args.push_back("-x");
        args.push_back("-y");
        args.push_back("foo");
        args.push_back("bar");
        ProcessSpawn process(ProcessSpawn::ASYNC, TEST_SCRIPT_SH, args);
        std::string expected = TEST_SCRIPT_SH;
        expected += " -x -y foo bar";
        EXPECT_EQ(expected, process.getCommandLine());
    }

    {
        // Case 2: no arguments.
        ProcessSpawn process(ProcessSpawn::ASYNC, TEST_SCRIPT_SH);
        EXPECT_EQ(TEST_SCRIPT_SH, process.getCommandLine());
    }
}

// This test verifies that it is possible to check if the process is
// running.
TEST_F(ProcessSpawnTest, isRunning) {
    // Run the process which sleeps for 10 seconds, so as we have
    // enough time to check if it is running.
    vector<string> args;
    args.push_back("-s");
    args.push_back("10");

    ProcessSpawn process(ProcessSpawn::ASYNC, TEST_SCRIPT_SH, args);
    pid_t pid = 0;
    ASSERT_NO_THROW(pid = process.spawn());

    EXPECT_TRUE(process.isRunning(pid));

    // Kill the process.
    ASSERT_EQ(0, kill(pid, SIGKILL));

    // Set test fail safe.
    setTestTime(1000);

    // SIGCHLD signal.
    io_service_->runOne();

    // waitForProcess handler.
    // ProcessSpawnTest::processSignal handler.
    io_service_->runOne();

    // Poll to be sure.
    io_service_->poll();

    ASSERT_EQ(1, processed_signals_.size());
    ASSERT_EQ(SIGCHLD, processed_signals_[0]);
}

// This test verifies inheritance of environment.
TEST_F(ProcessSpawnTest, inheritEnv) {
    // Run the process which sleeps for 10 seconds, so as we have
    // enough time to check if it is running.
    vector<string> args{"-v", "VAR", "value"};

    ProcessEnvVars vars{"VAR=value"};

    ProcessSpawn process(ProcessSpawn::ASYNC, TEST_SCRIPT_SH, args, vars,
                         /* inherit_env = */ true);
    pid_t pid = 0;
    ASSERT_NO_THROW(pid = process.spawn());

    // Set test fail safe.
    setTestTime(1000);

    // SIGCHLD signal.
    io_service_->runOne();

    // waitForProcess handler.
    // ProcessSpawnTest::processSignal handler.
    io_service_->runOne();

    // Poll to be sure.
    io_service_->poll();

    ASSERT_EQ(1, processed_signals_.size());
    ASSERT_EQ(SIGCHLD, processed_signals_[0]);

    // 56 means successful comparison of env vars.
    EXPECT_EQ(56, process.getExitStatus(pid));
}

// This test verifies inheritance of environment when a variable is inherited
// from parent. It assumes PATH is set.
TEST_F(ProcessSpawnTest, inheritEnvWithParentVar) {
    // Run the process which sleeps for 10 seconds, so as we have
    // enough time to check if it is running.
    vector<string> args{"-v", "PATH", "value"};

    ProcessEnvVars vars{"VAR=value"};

    ProcessSpawn process(ProcessSpawn::ASYNC, TEST_SCRIPT_SH, args, vars,
                         /* inherit_env = */ true);
    pid_t pid = 0;
    ASSERT_NO_THROW(pid = process.spawn());

    // Set test fail safe.
    setTestTime(1000);

    // SIGCHLD signal.
    io_service_->runOne();

    // waitForProcess handler.
    // ProcessSpawnTest::processSignal handler.
    io_service_->runOne();

    // Poll to be sure.
    io_service_->poll();

    ASSERT_EQ(1, processed_signals_.size());
    ASSERT_EQ(SIGCHLD, processed_signals_[0]);

    // 34 means failed comparison of env vars.
    EXPECT_EQ(34, process.getExitStatus(pid));
}

// This test verifies that the external application can be ran synchronously
// with arguments and that the exit code is gathered.
TEST_F(ProcessSpawnTest, spawnWithArgsSync) {
    vector<string> args;
    args.push_back("-e");
    args.push_back("64");

    ProcessSpawn process(ProcessSpawn::SYNC, TEST_SCRIPT_SH, args);
    pid_t pid = 0;
    ASSERT_NO_THROW(pid = process.spawn());

    // Exit code 64 as requested.
    EXPECT_EQ(64, process.getExitStatus(pid));
}

// This test verifies that the external application can be ran synchronously
// with arguments and environment variables that the exit code is gathered.
TEST_F(ProcessSpawnTest, spawnWithArgsAndEnvVarsSync) {
    vector<string> args;
    vector<string> vars;
    args.push_back("-v");
    args.push_back("TEST_VARIABLE_NAME");
    args.push_back("TEST_VARIABLE_VALUE");
    vars.push_back("TEST_VARIABLE_NAME=TEST_VARIABLE_VALUE");

    ProcessSpawn process(ProcessSpawn::SYNC, TEST_SCRIPT_SH, args, vars);
    pid_t pid = 0;
    ASSERT_NO_THROW(pid = process.spawn());

    // 56 means successful comparison of env vars.
    EXPECT_EQ(56, process.getExitStatus(pid));
}

// This test verifies that the single ProcessSpawn object can be used
// to start two processes synchronously and that their status codes can be
// gathered. It also checks that it is possible to clear the status of the
// process.
TEST_F(ProcessSpawnTest, spawnTwoProcessesSync) {
    vector<string> args;
    args.push_back("-p");

    ProcessSpawn process(ProcessSpawn::SYNC, TEST_SCRIPT_SH, args);
    pid_t pid1 = 0;
    ASSERT_NO_THROW(pid1 = process.spawn());

    pid_t pid2 = 0;
    ASSERT_NO_THROW(pid2 = process.spawn());

    EXPECT_NE(process.getExitStatus(pid1), process.getExitStatus(pid2));

    // Clear the status of the first process. An attempt to get the status
    // for the cleared process should result in exception. But, there should
    // be no exception for the second process.
    process.clearState(pid1);
    EXPECT_THROW(process.getExitStatus(pid1), InvalidOperation);
    EXPECT_NO_THROW(process.getExitStatus(pid2));

    process.clearState(pid2);
    EXPECT_THROW(process.getExitStatus(pid2), InvalidOperation);
}

// This test verifies that the external application can be ran synchronously
// without arguments and that the exit code is gathered.
TEST_F(ProcessSpawnTest, spawnNoArgsSync) {
    ProcessSpawn process(ProcessSpawn::SYNC, TEST_SCRIPT_SH);
    pid_t pid = 0;
    ASSERT_NO_THROW(pid = process.spawn());

    // 32 means no args.
    EXPECT_EQ(32, process.getExitStatus(pid));

    ASSERT_NO_THROW(pid = process.spawn(true));

    EXPECT_THROW(process.getExitStatus(pid), InvalidOperation);
}

// This test verifies that the EXIT_FAILURE code is returned when
// application can't be executed synchronously.
TEST_F(ProcessSpawnTest, invalidExecutableSync) {
    std::string expected = "File not found: foo";
    ASSERT_THROW_MSG(ProcessSpawn process(ProcessSpawn::SYNC, "foo"),
                     ProcessSpawnError, expected);

    std::string name = INVALID_TEST_SCRIPT_SH;

    expected = "File not executable: ";
    expected += name;
    ASSERT_THROW_MSG(ProcessSpawn process(ProcessSpawn::SYNC, name),
                     ProcessSpawnError, expected);
}

// This test verifies that the full command line for the synchronous process is
// returned.
TEST_F(ProcessSpawnTest, getCommandLineSync) {
    {
        // Case 1: arguments present.
        ProcessArgs args;
        args.push_back("-x");
        args.push_back("-y");
        args.push_back("foo");
        args.push_back("bar");
        ProcessSpawn process(ProcessSpawn::SYNC, TEST_SCRIPT_SH, args);
        std::string expected = TEST_SCRIPT_SH;
        expected += " -x -y foo bar";
        EXPECT_EQ(expected, process.getCommandLine());
    }

    {
        // Case 2: no arguments.
        ProcessSpawn process(ProcessSpawn::SYNC, TEST_SCRIPT_SH);
        EXPECT_EQ(TEST_SCRIPT_SH, process.getCommandLine());
    }
}

// This test verifies that the synchronous process reports as not running after
// it was spawned.
TEST_F(ProcessSpawnTest, isRunningSync) {
    ProcessSpawn process(ProcessSpawn::SYNC, TEST_SCRIPT_SH);
    pid_t pid = 0;
    ASSERT_NO_THROW(pid = process.spawn());

    EXPECT_FALSE(process.isRunning(pid));
}

// This test verifies inheritance of environment in a synchronous context.
TEST_F(ProcessSpawnTest, inheritEnvSync) {
    // Run the process which sleeps for 10 seconds, so as we have
    // enough time to check if it is running.
    vector<string> args{"-v", "VAR", "value"};

    ProcessEnvVars vars{"VAR=value"};

    ProcessSpawn process(ProcessSpawn::SYNC, TEST_SCRIPT_SH, args, vars,
                         /* inherit_env = */ true);
    pid_t pid = 0;
    ASSERT_NO_THROW(pid = process.spawn());

    // 56 means successful comparison of env vars.
    EXPECT_EQ(56, process.getExitStatus(pid));
}

// This test verifies inheritance of environment when a variable is inherited
// from parent in a synchronous context. It assumes PATH is set.
TEST_F(ProcessSpawnTest, inheritEnvWithParentVarSync) {
    // Run the process which sleeps for 10 seconds, so as we have
    // enough time to check if it is running.
    vector<string> args{"-v", "PATH", "value"};

    ProcessEnvVars vars{"VAR=value"};

    ProcessSpawn process(ProcessSpawn::SYNC, TEST_SCRIPT_SH, args, vars,
                         /* inherit_env = */ true);
    pid_t pid = 0;
    ASSERT_NO_THROW(pid = process.spawn());

    // 34 means failed comparison of env vars.
    EXPECT_EQ(34, process.getExitStatus(pid));
}

} // end of anonymous namespace