lfc_controller.cc 12 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Copyright (C) 2015  Internet Systems Consortium, Inc. ("ISC")
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.

15
#include <lfc/lfc_controller.h>
16
#include <lfc/lfc_log.h>
17
#include <util/pid_file.h>
18
#include <exceptions/exceptions.h>
19 20 21 22 23
#include <dhcpsrv/csv_lease_file4.h>
#include <dhcpsrv/csv_lease_file6.h>
#include <dhcpsrv/memfile_lease_storage.h>
#include <dhcpsrv/lease_mgr.h>
#include <dhcpsrv/lease_file_loader.h>
Shawn Routhier's avatar
Shawn Routhier committed
24
#include <config.h>
25

26
#include <iostream>
27 28
#include <sstream>
#include <unistd.h>
29
#include <stdlib.h>
30
#include <cerrno>
31 32

using namespace std;
33
using namespace isc::util;
34
using namespace isc::dhcp;
35
using namespace isc::log;
36

37 38 39 40 41
namespace {
/// @brief Maximum number of errors to allow when reading leases from the file.
const uint32_t MAX_LEASE_ERRORS = 100;
}; // namespace anonymous

42 43 44 45 46
namespace isc {
namespace lfc {

/// @brief Defines the application name, it may be used to locate
/// configuration data and appears in log statements.
47
const char* LFCController::lfc_app_name_ = "DhcpLFC";
48 49

/// @brief Defines the executable name.
50
const char* LFCController::lfc_bin_name_ = "kea-lfc";
51

52
LFCController::LFCController()
53
    : protocol_version_(0), verbose_(false), config_file_(""), previous_file_(""),
Shawn Routhier's avatar
Shawn Routhier committed
54
      copy_file_(""), output_file_(""), finish_file_(""), pid_file_("") {
55 56
}

57
LFCController::~LFCController() {
58 59 60
}

void
61
LFCController::launch(int argc, char* argv[], const bool test_mode) {
62
    bool do_rotate = true;
63

64 65 66 67 68
    // If we aren't running in test mode initialize the logging
    // system with the defaults.
    if (!test_mode)
        initLogger(lfc_app_name_, WARN, 0, NULL, false);

69 70 71 72 73 74 75
    try {
        parseArgs(argc, argv);
    } catch (const InvalidUsage& ex) {
        usage(ex.what());
        throw;  // rethrow it
    }

76 77
    // Now that we have parsed the arguments we can
    // update the logging level.
78
    if (verbose_) {
79
        setDefaultLoggingOutput(verbose_);
80
    }
81

82 83
    LOG_WARN(lfc_logger, LFC_START_MESSAGE);

84 85
    // verify we are the only instance
    PIDFile pid_file(pid_file_);
86 87

    try {
88
        if (pid_file.check()) {
89
            // Already running instance, bail out
90
            LOG_FATAL(lfc_logger, LFC_RUNNING_MESSAGE);
91 92
            return;
        }
93

94
        // create the pid file for this instance
95 96
        pid_file.write();
    } catch (const PIDFileError& pid_ex) {
97
        LOG_FATAL(lfc_logger, LFC_FAILURE_MESSAGE).arg(pid_ex.what());
98 99 100
        return;
    }

101 102 103 104 105
    // If we don't have a finish file do the processing.  We
    // don't know the exact type of the finish file here but
    // all we care about is if it exists so that's okay
    CSVFile lf_finish(getFinishFile());
    if (!lf_finish.exists()) {
106
        LOG_INFO(lfc_logger, LFC_PROCESSING_MESSAGE);
107 108

        try {
109
            if (getProtocolVersion() == 4) {
110 111 112 113 114 115
                processLeases<Lease4, CSVLeaseFile4, Lease4Storage>();
            } else {
                processLeases<Lease6, CSVLeaseFile6, Lease6Storage>();
            }
        } catch (const isc::Exception& proc_ex) {
            // We don't want to do the cleanup but do want to get rid of the pid
116
            do_rotate = false;
117
            LOG_FATAL(lfc_logger, LFC_FAILURE_MESSAGE).arg(proc_ex.what());
118
        }
119
    }
120

121
    // If do_rotate is true We either already had a finish file or
122 123
    // were able to create one.  We now want to do the file cleanup,
    // we don't want to return after the catch as we
124
    // still need to cleanup the pid file
125
    if (do_rotate) {
126
        LOG_INFO(lfc_logger, LFC_ROTATING_MESSAGE);
127

128
        try {
129
            fileRotate();
130
        } catch (const RunTimeFail& run_ex) {
131
          LOG_FATAL(lfc_logger, LFC_FAILURE_MESSAGE).arg(run_ex.what());
132
        }
133
    }
134 135

    // delete the pid file for this instance
136 137 138
    try {
        pid_file.deleteFile();
    } catch (const PIDFileError& pid_ex) {
139
          LOG_FATAL(lfc_logger, LFC_FAILURE_MESSAGE).arg(pid_ex.what());
140
    }
141

142
    LOG_WARN(lfc_logger, LFC_COMPLETE_MESSAGE);
143 144 145
}

void
146
LFCController::parseArgs(int argc, char* argv[]) {
147 148
    int ch;

149 150
    opterr = 0;
    optind = 1;
151
    while ((ch = getopt(argc, argv, ":46dvVp:x:i:o:c:f:")) != -1) {
152
        switch (ch) {
Shawn Routhier's avatar
Shawn Routhier committed
153
        case '4':
154
            // Process DHCPv4 lease files.
155
            protocol_version_ = 4;
156 157
            break;

Shawn Routhier's avatar
Shawn Routhier committed
158
        case '6':
159
            // Process DHCPv6 lease files.
160
            protocol_version_ = 6;
161 162
            break;

Shawn Routhier's avatar
Shawn Routhier committed
163
        case 'v':
164
            // Print just Kea vesion and exit.
Shawn Routhier's avatar
Shawn Routhier committed
165
            std::cout << getVersion(false) << std::endl;
166 167
            exit(EXIT_SUCCESS);

Shawn Routhier's avatar
Shawn Routhier committed
168
        case 'V':
169
            // Print extended  Kea vesion and exit.
Shawn Routhier's avatar
Shawn Routhier committed
170
            std::cout << getVersion(true) << std::endl;
171 172
            exit(EXIT_SUCCESS);

Shawn Routhier's avatar
Shawn Routhier committed
173 174 175 176 177 178
        case 'd':
            // Verbose output.
            verbose_ = true;
            break;

        case 'p':
179 180 181 182 183 184 185 186 187
            // PID file name.
            if (optarg == NULL) {
                isc_throw(InvalidUsage, "PID file name missing");
            }
            pid_file_ = optarg;
            break;

        case 'x':
            // Previous (or ex) file name.
Shawn Routhier's avatar
Shawn Routhier committed
188
            if (optarg == NULL) {
189
                isc_throw(InvalidUsage, "Previous (ex) file name missing");
Shawn Routhier's avatar
Shawn Routhier committed
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
            }
            previous_file_ = optarg;
            break;

        case 'i':
            // Copy file name.
            if (optarg == NULL) {
                isc_throw(InvalidUsage, "Copy file name missing");
            }
            copy_file_ = optarg;
            break;

        case 'o':
            // Output file name.
            if (optarg == NULL) {
                isc_throw(InvalidUsage, "Output file name missing");
            }
            output_file_ = optarg;
            break;

        case 'f':
211
            // Finish file name.
Shawn Routhier's avatar
Shawn Routhier committed
212 213 214 215 216 217 218
            if (optarg == NULL) {
                isc_throw(InvalidUsage, "Finish file name missing");
            }
            finish_file_ = optarg;
            break;

        case 'c':
219
            // Configuration file name
Shawn Routhier's avatar
Shawn Routhier committed
220 221 222 223 224 225
            if (optarg == NULL) {
                isc_throw(InvalidUsage, "Configuration file name missing");
            }
            config_file_ = optarg;
            break;

226
        case 'h':
Shawn Routhier's avatar
Shawn Routhier committed
227
            usage("");
228 229 230 231 232 233 234 235 236
            exit(EXIT_SUCCESS);

        case '?':
            // Unknown argument
            isc_throw(InvalidUsage, "Unknown argument");

        case ':':
            // Missing option argument
            isc_throw(InvalidUsage, "Missing option argument");
237 238

        default:
239 240 241
            // I don't think we should get here as the unknown arguments
            // and missing options cases should cover everything else
            isc_throw(InvalidUsage, "Invalid command line");
Shawn Routhier's avatar
Shawn Routhier committed
242
        }
243 244 245 246 247 248 249
    }

    // Check for extraneous parameters.
    if (argc > optind) {
        isc_throw(InvalidUsage, "Extraneous parameters.");
    }

250
    if (protocol_version_ == 0) {
251 252 253
        isc_throw(InvalidUsage, "DHCP version required");
    }

254 255 256 257
    if (pid_file_.empty()) {
        isc_throw(InvalidUsage, "PID file not specified");
    }

258
    if (previous_file_.empty()) {
Shawn Routhier's avatar
Shawn Routhier committed
259
        isc_throw(InvalidUsage, "Previous file not specified");
260 261 262
    }

    if (copy_file_.empty()) {
Shawn Routhier's avatar
Shawn Routhier committed
263
        isc_throw(InvalidUsage, "Copy file not specified");
264 265 266
    }

    if (output_file_.empty()) {
Shawn Routhier's avatar
Shawn Routhier committed
267
        isc_throw(InvalidUsage, "Output file not specified");
268 269
    }

270
    if (finish_file_.empty()) {
Shawn Routhier's avatar
Shawn Routhier committed
271
        isc_throw(InvalidUsage, "Finish file not specified");
272 273
    }

274
    if (config_file_.empty()) {
Shawn Routhier's avatar
Shawn Routhier committed
275
        isc_throw(InvalidUsage, "Config file not specified");
276 277 278
    }

    // If verbose is set echo the input information
279
    if (verbose_) {
280
        std::cout << "Protocol version:    DHCPv" << protocol_version_ << std::endl
281 282 283 284 285 286 287
                  << "Previous or ex lease file: " << previous_file_ << std::endl
                  << "Copy lease file:           " << copy_file_ << std::endl
                  << "Output lease file:         " << output_file_ << std::endl
                  << "Finish file:               " << finish_file_ << std::endl
                  << "Config file:               " << config_file_ << std::endl
                  << "PID file:                  " << pid_file_ << std::endl
                  << std::endl;
288 289 290 291
    }
}

void
292
LFCController::usage(const std::string& text) {
293
    if (!text.empty()) {
294 295 296 297
        std::cerr << "Usage error: " << text << std::endl;
    }

    std::cerr << "Usage: " << lfc_bin_name_ << std::endl
298
              << " [-4|-6] -p file -x file -i file -o file -f file -c file" << std::endl
299
              << "   -4 or -6 clean a set of v4 or v6 lease files" << std::endl
300 301
              << "   -p <file>: PID file" << std::endl
              << "   -x <file>: previous or ex lease file" << std::endl
302 303
              << "   -i <file>: copy of lease file" << std::endl
              << "   -o <file>: output lease file" << std::endl
304
              << "   -f <file>: finish file" << std::endl
305 306 307 308
              << "   -c <file>: configuration file" << std::endl
              << "   -v: print version number and exit" << std::endl
              << "   -V: print extended version inforamtion and exit" << std::endl
              << "   -d: optional, verbose output " << std::endl
309
              << "   -h: print this message " << std::endl
310 311 312
              << std::endl;
}

313
std::string
314 315
LFCController::getVersion(const bool extended) const{
    std::stringstream version_stream;
316

317
    version_stream << VERSION;
318
    if (extended) {
319
        version_stream << std::endl << EXTENDED_VERSION;
320 321
    }

322
    return (version_stream.str());
323 324
}

325
template<typename LeaseObjectType, typename LeaseFileType, typename StorageType>
326 327
void
LFCController::processLeases() const {
328 329 330
    StorageType storage;

    // If a previous file exists read the entries into storage
331
    LeaseFileType lf_prev(getPreviousFile());
332 333 334
    if (lf_prev.exists()) {
        LeaseFileLoader::load<LeaseObjectType>(lf_prev, storage,
                                               MAX_LEASE_ERRORS);
335 336
    }

337
    // Follow that with the copy of the current lease file
338
    LeaseFileType lf_copy(getCopyFile());
339 340 341
    if (lf_copy.exists()) {
        LeaseFileLoader::load<LeaseObjectType>(lf_copy, storage,
                                               MAX_LEASE_ERRORS);
342 343 344
    }

    // Write the result out to the output file
345
    LeaseFileType lf_output(getOutputFile());
346
    LeaseFileLoader::write<LeaseObjectType>(lf_output, storage);
347 348

    // Once we've finished the output file move it to the complete file
349
    if (rename(getOutputFile().c_str(), getFinishFile().c_str()) != 0) {
350 351 352
        isc_throw(RunTimeFail, "Unable to move output (" << output_file_
                  << ") to complete (" << finish_file_
                  << ") error: " << strerror(errno));
353
    }
354 355 356
}

void
357
LFCController::fileRotate() const {
358
    // Remove the old previous file
359
    if ((remove(getPreviousFile().c_str()) != 0) &&
360 361 362 363 364 365
        (errno != ENOENT)) {
        isc_throw(RunTimeFail, "Unable to delete previous file '"
                  << previous_file_ << "' error: " << strerror(errno));
    }

    // Remove the copy file
366
    if ((remove(getCopyFile().c_str()) != 0) &&
367 368 369 370 371 372
        (errno != ENOENT)) {
        isc_throw(RunTimeFail, "Unable to delete copy file '"
                  << copy_file_ << "' error: " << strerror(errno));
    }

    // Rename the finish file to be the previous file
373
    if (rename(finish_file_.c_str(), previous_file_.c_str()) != 0) {
374 375 376
        isc_throw(RunTimeFail, "Unable to move finish (" << finish_file_
                  << ") to previous (" << previous_file_
                  << ") error: " << strerror(errno));
377
    }
378
}
379 380
}; // namespace isc::lfc
}; // namespace isc