lfc_controller.cc 11.7 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 <util/pid_file.h>
17
#include <exceptions/exceptions.h>
18 19 20 21 22
#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
23
#include <config.h>
24

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

using namespace std;
32
using namespace isc::util;
33
using namespace isc::dhcp;
34

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

40 41 42 43 44
namespace isc {
namespace lfc {

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

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

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

55
LFCController::~LFCController() {
56 57 58
}

void
59
LFCController::launch(int argc, char* argv[]) {
60
    bool do_rotate = true;
61

62 63 64 65 66 67 68
    try {
        parseArgs(argc, argv);
    } catch (const InvalidUsage& ex) {
        usage(ex.what());
        throw;  // rethrow it
    }

69
    if (verbose_) {
70
        std::cerr << "Starting lease file cleanup" << std::endl;
71
    }
72 73 74

    // verify we are the only instance
    PIDFile pid_file(pid_file_);
75 76

    try {
77
        if (pid_file.check()) {
78 79 80 81
            // Already running instance, bail out
            std::cerr << "LFC instance already running" <<  std::endl;
            return;
        }
82

83
        // create the pid file for this instance
84 85 86 87 88 89
        pid_file.write();
    } catch (const PIDFileError& pid_ex) {
        std::cerr << pid_ex.what() << std::endl;
        return;
    }

90 91 92 93 94 95
    // 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()) {
        if (verbose_) {
96
            std::cerr << "LFC Processing files" << std::endl;
97
        }
98 99

        try {
100
            if (getProtocolVersion() == 4) {
101 102 103 104 105 106
                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
107
            do_rotate = false;
108 109
            std::cerr << "Processing failed: " << proc_ex.what() << std::endl;
        }
110
    }
111

112
    // If do_rotate is true We either already had a finish file or
113 114
    // were able to create one.  We now want to do the file cleanup,
    // we don't want to return after the catch as we
115
    // still need to cleanup the pid file
116 117
    if (do_rotate) {
        if (verbose_) {
118
            std::cerr << "LFC cleaning files" << std::endl;
119 120
        }

121
        try {
122
            fileRotate();
123 124 125
        } catch (const RunTimeFail& run_ex) {
            std::cerr << run_ex.what() << std::endl;
        }
126
    }
127 128

    // delete the pid file for this instance
129 130 131 132 133
    try {
        pid_file.deleteFile();
    } catch (const PIDFileError& pid_ex) {
        std::cerr << pid_ex.what() << std::endl;
    }
134

135
    if (verbose_) {
136
        std::cerr << "LFC complete" << std::endl;
137
    }
138 139 140
}

void
141
LFCController::parseArgs(int argc, char* argv[]) {
142 143
    int ch;

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

Shawn Routhier's avatar
Shawn Routhier committed
153
        case '6':
154
            // Process DHCPv6 lease files.
155
            protocol_version_ = 6;
156 157
            break;

Shawn Routhier's avatar
Shawn Routhier committed
158
        case 'v':
159
            // Print just Kea vesion and exit.
Shawn Routhier's avatar
Shawn Routhier committed
160
            std::cout << getVersion(false) << std::endl;
161 162
            exit(EXIT_SUCCESS);

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

Shawn Routhier's avatar
Shawn Routhier committed
168 169 170 171 172 173
        case 'd':
            // Verbose output.
            verbose_ = true;
            break;

        case 'p':
174 175 176 177 178 179 180 181 182
            // 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
183
            if (optarg == NULL) {
184
                isc_throw(InvalidUsage, "Previous (ex) file name missing");
Shawn Routhier's avatar
Shawn Routhier committed
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
            }
            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':
206
            // Finish file name.
Shawn Routhier's avatar
Shawn Routhier committed
207 208 209 210 211 212 213
            if (optarg == NULL) {
                isc_throw(InvalidUsage, "Finish file name missing");
            }
            finish_file_ = optarg;
            break;

        case 'c':
214
            // Configuration file name
Shawn Routhier's avatar
Shawn Routhier committed
215 216 217 218 219 220
            if (optarg == NULL) {
                isc_throw(InvalidUsage, "Configuration file name missing");
            }
            config_file_ = optarg;
            break;

221
        case 'h':
Shawn Routhier's avatar
Shawn Routhier committed
222
            usage("");
223 224 225 226 227 228 229 230 231
            exit(EXIT_SUCCESS);

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

        case ':':
            // Missing option argument
            isc_throw(InvalidUsage, "Missing option argument");
232 233

        default:
234 235 236
            // 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
237
        }
238 239 240 241 242 243 244
    }

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

245
    if (protocol_version_ == 0) {
246 247 248
        isc_throw(InvalidUsage, "DHCP version required");
    }

249 250 251 252
    if (pid_file_.empty()) {
        isc_throw(InvalidUsage, "PID file not specified");
    }

253
    if (previous_file_.empty()) {
Shawn Routhier's avatar
Shawn Routhier committed
254
        isc_throw(InvalidUsage, "Previous file not specified");
255 256 257
    }

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

    if (output_file_.empty()) {
Shawn Routhier's avatar
Shawn Routhier committed
262
        isc_throw(InvalidUsage, "Output file not specified");
263 264
    }

265
    if (finish_file_.empty()) {
Shawn Routhier's avatar
Shawn Routhier committed
266
        isc_throw(InvalidUsage, "Finish file not specified");
267 268
    }

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

    // If verbose is set echo the input information
274
    if (verbose_) {
275 276 277 278 279 280 281 282
        std::cerr << "Protocol version:    DHCPv" << protocol_version_ << std::endl
                  << "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;
283 284 285 286
    }
}

void
287
LFCController::usage(const std::string& text) {
288
    if (!text.empty()) {
289 290 291 292
        std::cerr << "Usage error: " << text << std::endl;
    }

    std::cerr << "Usage: " << lfc_bin_name_ << std::endl
293
              << " [-4|-6] -p file -x file -i file -o file -f file -c file" << std::endl
294
              << "   -4 or -6 clean a set of v4 or v6 lease files" << std::endl
295 296
              << "   -p <file>: PID file" << std::endl
              << "   -x <file>: previous or ex lease file" << std::endl
297 298
              << "   -i <file>: copy of lease file" << std::endl
              << "   -o <file>: output lease file" << std::endl
299
              << "   -f <file>: finish file" << std::endl
300 301 302 303
              << "   -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
304
              << "   -h: print this message " << std::endl
305 306 307
              << std::endl;
}

308
std::string
309 310
LFCController::getVersion(const bool extended) const{
    std::stringstream version_stream;
311

312
    version_stream << VERSION;
313
    if (extended) {
314
        version_stream << std::endl << EXTENDED_VERSION;
315 316
    }

317
    return (version_stream.str());
318 319
}

320
template<typename LeaseObjectType, typename LeaseFileType, typename StorageType>
321 322
void
LFCController::processLeases() const {
323 324 325
    StorageType storage;

    // If a previous file exists read the entries into storage
326
    LeaseFileType lf_prev(getPreviousFile());
327 328 329
    if (lf_prev.exists()) {
        LeaseFileLoader::load<LeaseObjectType>(lf_prev, storage,
                                               MAX_LEASE_ERRORS);
330 331
    }

332
    // Follow that with the copy of the current lease file
333
    LeaseFileType lf_copy(getCopyFile());
334 335 336
    if (lf_copy.exists()) {
        LeaseFileLoader::load<LeaseObjectType>(lf_copy, storage,
                                               MAX_LEASE_ERRORS);
337 338 339
    }

    // Write the result out to the output file
340
    LeaseFileType lf_output(getOutputFile());
341
    LeaseFileLoader::write<LeaseObjectType>(lf_output, storage);
342 343

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

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

    // Remove the copy file
361
    if ((remove(getCopyFile().c_str()) != 0) &&
362 363 364 365 366 367
        (errno != ENOENT)) {
        isc_throw(RunTimeFail, "Unable to delete copy file '"
                  << copy_file_ << "' error: " << strerror(errno));
    }

    // Rename the finish file to be the previous file
368
    if (rename(finish_file_.c_str(), previous_file_.c_str()) != 0) {
369 370 371
        isc_throw(RunTimeFail, "Unable to move finish (" << finish_file_
                  << ") to previous (" << previous_file_
                  << ") error: " << strerror(errno));
372
    }
373
}
374 375
}; // namespace isc::lfc
}; // namespace isc