lfc_controller.cc 11 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 26

#include <boost/shared_ptr.hpp>

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

using namespace std;
34
using namespace isc::util;
35
using namespace isc::dhcp;
36 37 38 39 40 41

namespace isc {
namespace lfc {

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

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

47 48 49
/// @brief Maximum number of errors to read the leases from the lease file.
const uint32_t MAX_LEASE_ERRORS = 100;

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 61 62 63 64 65 66 67 68 69 70
    try {
        parseArgs(argc, argv);
    } catch (const InvalidUsage& ex) {
        usage(ex.what());
        throw;  // rethrow it
    }

    std::cerr << "Starting lease file cleanup" << std::endl;

    // verify we are the only instance
    PIDFile pid_file(pid_file_);
71 72 73 74 75 76 77 78 79

    try {
        if (pid_file.check() == true) {
            // Already running instance, bail out
            std::cerr << "LFC instance already running" <<  std::endl;
            return;
        }
    } catch (const PIDFileError& pid_ex) {
        std::cerr << pid_ex.what() << std::endl;
80 81 82 83 84 85 86 87 88 89 90 91
        return;
    }

    // create the pid file for this instance
    try {
        pid_file.write();
    } catch (const PIDFileError& pid_ex) {
        std::cerr << pid_ex.what() << std::endl;
        return;
    }

    // do other work (TBD)
92
    // If we don't have a finish file do the processing
93 94 95 96 97 98 99 100 101
    if (access(finish_file_.c_str(), F_OK) == -1) {
        std::cerr << "LFC Processing files" << std::endl;

	if (protocol_version_ == 4) {
	    processLeases<Lease4, CSVLeaseFile4, Lease4Storage>();
	} else {
	    processLeases<Lease6, CSVLeaseFile6, Lease6Storage>();
	}
    }
102 103 104 105 106

    // We either already had a finish file or just created one, do the
    // file cleanup, we don't want to return after the catch as we
    // still need to cleanup the pid file
    try {
107
        std::cerr << "LFC cleaning files" << std::endl;
108 109 110 111
        fileCleanup();
    } catch (const RunTimeFail& run_ex) {
        std::cerr << run_ex.what() << std::endl;
    }
112 113

    // delete the pid file for this instance
114 115 116 117 118 119
    try {
        pid_file.deleteFile();
    } catch (const PIDFileError& pid_ex) {
        std::cerr << pid_ex.what() << std::endl;
        return;
    }
120 121

    std::cerr << "LFC complete" << std::endl;
122 123 124
}

void
125
LFCController::parseArgs(int argc, char* argv[]) {
126 127
    int ch;

128 129
    opterr = 0;
    optind = 1;
130
    while ((ch = getopt(argc, argv, ":46dvVp:x:i:o:c:f:")) != -1) {
131
        switch (ch) {
Shawn Routhier's avatar
Shawn Routhier committed
132
        case '4':
133
            // Process DHCPv4 lease files.
134
            protocol_version_ = 4;
135 136
            break;

Shawn Routhier's avatar
Shawn Routhier committed
137
        case '6':
138
            // Process DHCPv6 lease files.
139
            protocol_version_ = 6;
140 141
            break;

Shawn Routhier's avatar
Shawn Routhier committed
142
        case 'v':
143
            // Print just Kea vesion and exit.
Shawn Routhier's avatar
Shawn Routhier committed
144
            std::cout << getVersion(false) << std::endl;
145 146
            exit(EXIT_SUCCESS);

Shawn Routhier's avatar
Shawn Routhier committed
147
        case 'V':
148
            // Print extended  Kea vesion and exit.
Shawn Routhier's avatar
Shawn Routhier committed
149
            std::cout << getVersion(true) << std::endl;
150 151
            exit(EXIT_SUCCESS);

Shawn Routhier's avatar
Shawn Routhier committed
152 153 154 155 156 157
        case 'd':
            // Verbose output.
            verbose_ = true;
            break;

        case 'p':
158 159 160 161 162 163 164 165 166
            // 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
167
            if (optarg == NULL) {
168
                isc_throw(InvalidUsage, "Previous (ex) file name missing");
Shawn Routhier's avatar
Shawn Routhier committed
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
            }
            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':
190
            // Finish file name.
Shawn Routhier's avatar
Shawn Routhier committed
191 192 193 194 195 196 197
            if (optarg == NULL) {
                isc_throw(InvalidUsage, "Finish file name missing");
            }
            finish_file_ = optarg;
            break;

        case 'c':
198
            // Configuration file name
Shawn Routhier's avatar
Shawn Routhier committed
199 200 201 202 203 204
            if (optarg == NULL) {
                isc_throw(InvalidUsage, "Configuration file name missing");
            }
            config_file_ = optarg;
            break;

205
        case 'h':
Shawn Routhier's avatar
Shawn Routhier committed
206
            usage("");
207 208 209 210 211 212 213 214 215
            exit(EXIT_SUCCESS);

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

        case ':':
            // Missing option argument
            isc_throw(InvalidUsage, "Missing option argument");
216 217

        default:
218 219 220
            // 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
221
        }
222 223 224 225 226 227 228
    }

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

229
    if (protocol_version_ == 0) {
230 231 232
        isc_throw(InvalidUsage, "DHCP version required");
    }

233 234 235 236
    if (pid_file_.empty()) {
        isc_throw(InvalidUsage, "PID file not specified");
    }

237
    if (previous_file_.empty()) {
Shawn Routhier's avatar
Shawn Routhier committed
238
        isc_throw(InvalidUsage, "Previous file not specified");
239 240 241
    }

    if (copy_file_.empty()) {
Shawn Routhier's avatar
Shawn Routhier committed
242
        isc_throw(InvalidUsage, "Copy file not specified");
243 244 245
    }

    if (output_file_.empty()) {
Shawn Routhier's avatar
Shawn Routhier committed
246
        isc_throw(InvalidUsage, "Output file not specified");
247 248
    }

249
    if (finish_file_.empty()) {
Shawn Routhier's avatar
Shawn Routhier committed
250
        isc_throw(InvalidUsage, "Finish file not specified");
251 252
    }

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

    // If verbose is set echo the input information
    if (verbose_ == true) {
259
      std::cerr << "Protocol version:    DHCPv" << protocol_version_ << std::endl
260 261 262
                << "Previous or ex lease file: " << previous_file_ << std::endl
                << "Copy lease file:           " << copy_file_ << std::endl
                << "Output lease file:         " << output_file_ << std::endl
263
                << "Finish file:               " << finish_file_ << std::endl
264 265
                << "Config file:               " << config_file_ << std::endl
                << "PID file:                  " << pid_file_ << std::endl;
266 267 268 269
    }
}

void
270
LFCController::usage(const std::string& text) {
271 272 273 274 275
    if (text != "") {
        std::cerr << "Usage error: " << text << std::endl;
    }

    std::cerr << "Usage: " << lfc_bin_name_ << std::endl
276
              << " [-4|-6] -p file -x file -i file -o file -f file -c file" << std::endl
277
              << "   -4 or -6 clean a set of v4 or v6 lease files" << std::endl
278 279
              << "   -p <file>: PID file" << std::endl
              << "   -x <file>: previous or ex lease file" << std::endl
280 281
              << "   -i <file>: copy of lease file" << std::endl
              << "   -o <file>: output lease file" << std::endl
282
              << "   -f <file>: finish file" << std::endl
283 284 285 286
              << "   -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
287
              << "   -h: print this message " << std::endl
288 289 290
              << std::endl;
}

291
std::string
292 293
LFCController::getVersion(const bool extended) const{
    std::stringstream version_stream;
294

295
    version_stream << VERSION;
296
    if (extended) {
297
        version_stream << std::endl << EXTENDED_VERSION;
298 299
    }

300
    return (version_stream.str());
301 302
}

303
template<typename LeaseObjectType, typename LeaseFileType, typename StorageType>
304 305
void
LFCController::processLeases() const {
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
    LeaseFileType lfPrev(previous_file_.c_str());
    LeaseFileType lfCopy(copy_file_.c_str());
    LeaseFileType lfOutput(output_file_.c_str());
    StorageType storage;
    storage.clear();

    // If a previous file exists read the entries into storage
    if (lfPrev.exists()) {
        LeaseFileLoader::load<LeaseObjectType>(lfPrev, storage,
					       MAX_LEASE_ERRORS);
    }

    // Follow that with the copy of the current lease file 
    if (lfCopy.exists()) {
        LeaseFileLoader::load<LeaseObjectType>(lfCopy, storage,
					       MAX_LEASE_ERRORS);
    }

    // Write the result out to the output file
    LeaseFileLoader::write<LeaseObjectType>(lfOutput, storage);

    // Once we've finished the output file move it to the complete file
    if (rename(output_file_.c_str(), finish_file_.c_str()) != 0)
        isc_throw(RunTimeFail, "Unable to move output (" << output_file_
                  << ") to complete (" << finish_file_
                  << ") error: " << strerror(errno));
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
}

void
LFCController::fileCleanup() const {
    // Remove the old previous file
    if ((remove(previous_file_.c_str()) != 0) &&
        (errno != ENOENT)) {
        isc_throw(RunTimeFail, "Unable to delete previous file '"
                  << previous_file_ << "' error: " << strerror(errno));
    }

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

    // Rename the finish file to be the previous file
    if (rename(finish_file_.c_str(), previous_file_.c_str()) != 0)
        isc_throw(RunTimeFail, "Unable to move finish (" << finish_file_
                  << ") to previous (" << previous_file_
                  << ") error: " << strerror(errno));
}
356 357
}; // namespace isc::lfc
}; // namespace isc