Welcome to mirror list, hosted at ThFree Co, Russian Federation.

run_on_incoming_connect_interval.cc « tests « src « core - github.com/bareos/bareos.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: fa41fa5e612f69c1b40a91de50f72063445aa3e3 (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
/*
   BAREOS® - Backup Archiving REcovery Open Sourced

   Copyright (C) 2019-2022 Bareos GmbH & Co. KG

   This program is Free Software; you can redistribute it and/or
   modify it under the terms of version three of the GNU Affero General Public
   License as published by the Free Software Foundation, which is
   listed in the file LICENSE.

   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
   Affero General Public License for more details.

   You should have received a copy of the GNU Affero General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
   02110-1301, USA.
*/


#if defined(HAVE_MINGW)
#  include "include/bareos.h"
#  include "gtest/gtest.h"
#  include "gmock/gmock.h"
#else
#  include "gtest/gtest.h"
#  include "gmock/gmock.h"
#  include "include/bareos.h"
#endif

#include "cats/cats.h"
#include "dird/dird_conf.h"
#include "dird/dird_globals.h"
#include "dird/director_jcr_impl.h"
#include "dird/job.h"
#include "dird/run_on_incoming_connect_interval.h"
#include "dird/scheduler.h"
#include "dird/scheduler_time_adapter.h"
#include "include/bareos.h"
#include "include/jcr.h"
#include "lib/parse_conf.h"

#include <algorithm>
#include <chrono>
#include <cstdlib>
#include <string>
#include <thread>
#include <vector>

using directordaemon::GetAllJobResourcesByClientName;
using directordaemon::InitDirConfig;
using directordaemon::JobResource;
using directordaemon::my_config;
using directordaemon::RunOnIncomingConnectInterval;
using directordaemon::Scheduler;
using directordaemon::SchedulerTimeAdapter;
using directordaemon::TimeSource;
using std::chrono::hours;
using std::chrono::seconds;
using std::chrono::system_clock;

class RunOnIncomingConnectIntervalTest : public ::testing::Test {
  void SetUp() override;
  void TearDown() override;
};

void RunOnIncomingConnectIntervalTest::SetUp()
{
  OSDependentInit();

  std::string path_to_config_file = std::string(
      RELATIVE_PROJECT_SOURCE_DIR "/configs/run-on-incoming-connect-interval/");
  my_config = InitDirConfig(path_to_config_file.c_str(), M_ERROR_TERM);
  my_config->ParseConfig();
}

void RunOnIncomingConnectIntervalTest::TearDown() { delete my_config; }

static bool find(std::vector<JobResource*> jobs, std::string jobname)
{
  return jobs.end()
         != std::find_if(jobs.begin(), jobs.end(),
                         [&jobname](JobResource* job) {
                           return std::string{job->resource_name_} == jobname;
                         });
}

TEST_F(RunOnIncomingConnectIntervalTest, find_all_jobs_for_client)
{
  std::vector<JobResource*> jobs{GetAllJobResourcesByClientName("bareos-fd")};

  EXPECT_EQ(jobs.size(), 4);

  EXPECT_TRUE(find(jobs, "backup-bareos-fd"));
  EXPECT_TRUE(find(jobs, "backup-bareos-fd-connect"));
  EXPECT_TRUE(find(jobs, "backup-bareos-fd-connect-2"));
  EXPECT_TRUE(find(jobs, "RestoreFiles"));
}

TEST_F(RunOnIncomingConnectIntervalTest,
       find_all_connect_interval_jobs_for_client)
{
  std::vector<JobResource*> jobs{GetAllJobResourcesByClientName("bareos-fd")};

  auto end = std::remove_if(jobs.begin(), jobs.end(), [](JobResource* job) {
    return job->RunOnIncomingConnectInterval == 0;
  });
  jobs.erase(end, jobs.end());
  EXPECT_EQ(jobs.size(), 2);

  EXPECT_TRUE(find(jobs, "backup-bareos-fd-connect"));
  EXPECT_TRUE(find(jobs, "backup-bareos-fd-connect-2"));
}

static struct TestResults {
  int job_counter{};
  int scheduler_sleep_count{};
  int timeout{};
  std::map<std::string, int> job_names;
} test_results;

class TestTimeSource : public TimeSource {
 public:
  int counter{};
  time_t SystemTime() override { return ++counter; }
  void SleepFor(std::chrono::seconds /*wait_interval*/) override
  {
    ++test_results.scheduler_sleep_count;
  }
  void Terminate() override {}
};

class TimeAdapter : public SchedulerTimeAdapter {
 public:
  explicit TimeAdapter(std::unique_ptr<TestTimeSource> t)
      : SchedulerTimeAdapter(std::move(t))
  {
  }
};

static void SchedulerJobCallback(JobControlRecord* jcr)
{
  ++test_results.job_counter;

  // add job-name to map
  test_results.job_names[jcr->dir_impl->res.job->resource_name_]++;
  FreeJcr(jcr);
}

class MockDatabase : public BareosDb {
 public:
  enum class Mode
  {
    kFindNoStartTime,
    kFindStartTime,
    kFindStartTimeWrongString
  };
  explicit MockDatabase(Mode mode) : mode_(mode) {}
  SqlFindResult FindLastJobStartTimeForJobAndClient(
      JobControlRecord* /*jcr*/,
      std::string /*job_basename*/,
      std::string /*client_name*/,
      std::vector<char>& stime_out) override
  {
    switch (mode_) {
      case Mode::kFindNoStartTime:
        return SqlFindResult::kEmptyResultSet;

      case Mode::kFindStartTime: {
        auto now = system_clock::now();
        auto more_than_three_hours = seconds(hours(3) + seconds(1));

        utime_t fake_start_time_of_previous_job
            = system_clock::to_time_t(now - more_than_three_hours);

        stime_out.resize(MAX_NAME_LENGTH);
        bstrutime(stime_out.data(), MAX_NAME_LENGTH,
                  fake_start_time_of_previous_job);
        return SqlFindResult::kSuccess;
      }

      case Mode::kFindStartTimeWrongString: {
        auto now = system_clock::now();
        stime_out.resize(MAX_NAME_LENGTH);
        bstrutime(stime_out.data(), MAX_NAME_LENGTH,
                  system_clock::to_time_t(now));
        stime_out[5] = 0;  // truncate string
        return SqlFindResult::kSuccess;
      }

      default:
        std::abort();

    }  // switch(mode)
  }

  bool OpenDatabase(JobControlRecord* /*jcr*/) override { return false; }
  void CloseDatabase(JobControlRecord* /*jcr*/) override {}
  bool ValidateConnection() override { return false; }
  void StartTransaction(JobControlRecord* /*jcr*/) override {}
  void EndTransaction(JobControlRecord* /*jcr*/) override {}
  bool SqlCopyStart(const std::string&,
                    const std::vector<std::string>&) override
  {
    return false;
  }
  bool SqlCopyInsert(const std::vector<DatabaseField>&) override
  {
    return false;
  }
  bool SqlCopyEnd() override { return false; }

 private:
  Mode mode_{};
};

static void scheduler_loop(Scheduler* scheduler) { scheduler->Run(); }

static void SimulateClientConnect(std::string client_name,
                                  Scheduler& scheduler,
                                  BareosDb& db)
{
  RunOnIncomingConnectInterval(client_name, scheduler, &db).Run();
}

static void RunSchedulerAndSimulateClientConnect(BareosDb& db)
{
  Scheduler scheduler(
      std::make_unique<TimeAdapter>(std::make_unique<TestTimeSource>()),
      SchedulerJobCallback);

  test_results = TestResults();

  SimulateClientConnect("bareos-fd", scheduler, db);

  std::thread scheduler_thread(scheduler_loop, &scheduler);

  int timeout{};
  while (test_results.scheduler_sleep_count < 3 && timeout < 500) {
    std::this_thread::sleep_for(std::chrono::milliseconds(1));
    ++timeout;
  }

  scheduler.Terminate();
  scheduler_thread.join();
}

TEST_F(RunOnIncomingConnectIntervalTest, no_start_time_found_in_database)
{
  MockDatabase db(MockDatabase::Mode::kFindNoStartTime);
  RunSchedulerAndSimulateClientConnect(db);

  EXPECT_TRUE(test_results.scheduler_sleep_count > 0)
      << "The scheduler did not sleep";

  ASSERT_EQ(test_results.job_counter, 2) << "Not all jobs did run";

  EXPECT_NE(test_results.job_names.find("backup-bareos-fd-connect"),
            test_results.job_names.end())
      << "Job backup-bareos-fd-connect did not run";

  EXPECT_NE(test_results.job_names.find("backup-bareos-fd-connect-2"),
            test_results.job_names.end())
      << "Job backup-bareos-fd-connect2 did not run";
}

TEST_F(RunOnIncomingConnectIntervalTest, start_time_found_in_database)
{
  MockDatabase db(MockDatabase::Mode::kFindStartTime);
  RunSchedulerAndSimulateClientConnect(db);

  EXPECT_TRUE(test_results.scheduler_sleep_count > 0)
      << "The scheduler did not sleep";

  ASSERT_EQ(test_results.job_counter, 1)
      << "backup-bareos-fd-connect did not run";

  EXPECT_NE(test_results.job_names.find("backup-bareos-fd-connect"),
            test_results.job_names.end())
      << "Job backup-bareos-fd-connect did not run";
}

TEST_F(RunOnIncomingConnectIntervalTest, start_time_found_wrong_time_string)
{
  MockDatabase db(MockDatabase::Mode::kFindStartTimeWrongString);
  RunSchedulerAndSimulateClientConnect(db);

  EXPECT_TRUE(test_results.scheduler_sleep_count > 0)
      << "The scheduler did not sleep";

  ASSERT_EQ(test_results.job_counter, 0)
      << "backup-bareos-fd-connect did not run";
}