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

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

   Copyright (C) 2020-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.
*/

#include "include/bareos.h"
#include "cats/cats.h"
#include "cats/cats_backends.h"
#include "cats/sql_pooling.h"
#include "dird/dbcopy/database_connection.h"
#include "dird/dbcopy/database_export.h"
#include "dird/dbcopy/database_export_postgresql.h"
#include "dird/dbcopy/database_import.h"
#include "dird/dird_conf.h"
#include "dird/dird_globals.h"
#include "dird/get_database_connection.h"
#include "dird/director_jcr_impl.h"
#include "dird/job.h"
#include "lib/parse_conf.h"
#include "lib/util.h"

#include <array>
#include <iostream>

#if !defined HAVE_DYNAMIC_CATS_BACKENDS
#  error "NOT DEFINED: HAVE_DYNAMIC_CATS_BACKENDS"
#endif

class DbCopy {
 public:
  explicit DbCopy(int argc, char** argv)
  {
    InitMsg(nullptr, nullptr);
    SetWorkingDir();
    cl.ParseCommandLine(argc, argv);

    ParseConfig();
    std::cout << "Copying tables from \"" << cl.source_db_resource_name
              << "\" to \"" << cl.destination_db_resource_name << "\""
              << std::endl;
    ConnectToDatabases();
  }

  void DoDatabaseCopy()
  {
    std::cout << "gathering information about source catalog \""
              << cl.source_db_resource_name << "\"..." << std::endl;
    std::unique_ptr<DatabaseImport> imp(
        DatabaseImport::Create(*source_db_, cl.maximum_number_of_rows));

    std::cout << "gathering information about destination catalog \""
              << cl.destination_db_resource_name << "\"..." << std::endl;
    std::unique_ptr<DatabaseExport> exp(
        DatabaseExport::Create(*destination_db_,
                               cl.use_sql_insert_statements_instead_of_copy
                                   ? DatabaseExport::InsertMode::kSqlInsert
                                   : DatabaseExport::InsertMode::kSqlCopy,
                               cl.empty_destination_tables));

    std::cout << "copying tables..." << std::endl;
    imp->ExportTo(*exp);
  }

 private:
  void SetWorkingDir()
  {
    if (getcwd(current_working_directory_.data(),
               current_working_directory_.size())
        == nullptr) {
      throw std::runtime_error(
          "Could not determine current working directory.");
    }
    SetWorkingDirectory(current_working_directory_.data());
  }

  void ParseConfig()
  {
    directordaemon::my_config
        = directordaemon::InitDirConfig(cl.configpath_.c_str(), M_ERROR_TERM);

    my_config_.reset(directordaemon::my_config);

    if (!directordaemon::my_config->ParseConfig()) {
      throw std::runtime_error("Error when loading config.");
    }

    directordaemon::me = dynamic_cast<directordaemon::DirectorResource*>(
        my_config->GetNextRes(directordaemon::R_DIRECTOR, nullptr));

    if (directordaemon::me == nullptr) {
      throw std::runtime_error("Could not find director resource.");
    }

    DbSetBackendDirs(directordaemon::me->backend_directories);
  }

  void ConnectToDatabases()
  {
    try {
      source_db_ = std::make_unique<DatabaseConnection>(
          cl.source_db_resource_name, directordaemon::my_config);

      destination_db_ = std::make_unique<DatabaseConnection>(
          cl.destination_db_resource_name, directordaemon::my_config);

      if (source_db_->db_type != DatabaseType::Enum::kMysql) {
        throw std::runtime_error("Error: Source database is not mysql");
      }

      if (destination_db_->db_type != DatabaseType::Enum::kPostgresql) {
        throw std::runtime_error(
            "Error: Destination database is not postgresql");
      }

    } catch (const std::runtime_error& e) {
      throw e;
    }
  }

  class CommandLineParser {
    friend class DbCopy;

   public:
    void ParseCommandLine(int argc, char** argv)
    {
      int c{};
      bool options_error{false};
      int argument_count{};

      while ((c = getopt(argc, argv, "ic:l:?")) != -1 && !options_error) {
        switch (c) {
          case 'c':
            configpath_ = optarg;
            argument_count += 2;
            break;
          case 'i':
            use_sql_insert_statements_instead_of_copy = true;
            argument_count += 1;
            break;
#if 0
          case 'd':
            empty_destination_tables = true;
            ++argument_count;
            break;
#endif
          case 'l':
            try {
              maximum_number_of_rows = std::stoul(optarg);
            } catch (...) {
              throw std::runtime_error("Wrong argument for 'l'");
            }
            argument_count += 2;
            break;
          case '?':
          default:
            options_error = true;
            break;
        }
      }

      ++argument_count;  // program name
      ++argument_count;  // source catalog name
      ++argument_count;  // destination catalog name

      if (options_error || argc != argument_count) {
        usage();
        throw std::runtime_error(std::string());
      }
      source_db_resource_name = argv[argument_count - 2];
      destination_db_resource_name = argv[argument_count - 1];
    }

   private:
    std::string configpath_{"/etc/bareos"};
    std::string source_db_resource_name, destination_db_resource_name;
    bool empty_destination_tables{false};
    bool use_sql_insert_statements_instead_of_copy{false};
    std::size_t maximum_number_of_rows{};
    static constexpr std::size_t year_of_release = 2020;

    static void usage() noexcept
    {
      kBareosVersionStrings.PrintCopyright(stderr, year_of_release);

      fprintf(
          stderr,
          _("Usage: bareos-dbcopy [options] Source Destination\n"
            "        -c <path>   use <path> as configuration file or "
            "directory\n"
            "        -i          use SQL INSERT statements instead of COPY\n"
            "        -?          print this message.\n"
            "\n"));
    }
  };  // class CommandLineParser

 public:
  ~DbCopy() = default;
  DbCopy(const DbCopy& other) = delete;
  DbCopy(const DbCopy&& other) = delete;
  DbCopy& operator=(const DbCopy& rhs) = delete;
  DbCopy& operator=(const DbCopy&& rhs) = delete;

 private:
  CommandLineParser cl;
  std::unique_ptr<DatabaseConnection> source_db_;
  std::unique_ptr<DatabaseConnection> destination_db_;
  std::unique_ptr<ConfigurationParser> my_config_;
  static constexpr std::size_t sizeof_workingdir = 10 * 1024;
  std::array<char, sizeof_workingdir> current_working_directory_{};
};

class Cleanup {
 public:
  Cleanup() = default;
  ~Cleanup()
  {
    DbSqlPoolDestroy();
    DbFlushBackends();
  }
};

int main(int argc, char** argv)
{
  Cleanup c;

  try {
    DbCopy dbcopy(argc, argv);
    dbcopy.DoDatabaseCopy();
  } catch (const std::runtime_error& e) {
    std::string errstring{e.what()};
    if (!errstring.empty()) {
      std::cerr << std::endl << std::endl << e.what() << std::endl;
    }
    return 1;
  }
  std::cout << "database copy completed successfully" << std::endl;
  return 0;
}