d_test_stubs.cc 14.2 KB
Newer Older
1
// Copyright (C) 2013-2015 Internet Systems Consortium, Inc. ("ISC")
2 3 4 5 6 7 8 9 10 11 12 13 14
//
// 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 <config.h>
16
#include <asiolink/io_service.h>
17
#include <d2/d2_log.h>
18 19 20 21 22 23 24 25
#include <d2/spec_config.h>
#include <d2/tests/d_test_stubs.h>

using namespace asio;

namespace isc {
namespace d2 {

26
const char* valid_d2_config = "{ "
27 28
                        "\"ip_address\" : \"127.0.0.1\" , "
                        "\"port\" : 5031, "
29 30
                        "\"tsig_keys\": ["
                        "{ \"name\": \"d2_key.tmark.org\" , "
31
                        "   \"algorithm\": \"HMAC-MD5\" ,"
32
                        "   \"secret\": \"LSWXnfkKZjdPJI5QxlpnfQ==\" "
33
                        "} ],"
34 35
                        "\"forward_ddns\" : {"
                        "\"ddns_domains\": [ "
36
                        "{ \"name\": \"tmark.org.\" , "
37 38
                        "  \"key_name\": \"d2_key.tmark.org\" , "
                        "  \"dns_servers\" : [ "
39
                        "  { \"ip_address\": \"127.0.0.101\" } "
40
                        "] } ] }, "
41 42 43 44 45 46 47 48 49
                        "\"reverse_ddns\" : {"
                        "\"ddns_domains\": [ "
                        "{ \"name\": \" 0.168.192.in.addr.arpa.\" , "
                        "  \"key_name\": \"d2_key.tmark.org\" , "
                        "  \"dns_servers\" : [ "
                        "  { \"ip_address\": \"127.0.0.101\" , "
                        "    \"port\": 100 } ] } "
                        "] } }";

50
// Initialize the static failure flag.
51 52
SimFailure::FailureType SimFailure::failure_type_ = SimFailure::ftNoFailure;

53
// Define custom process command supported by DStubProcess.
54
const char*  DStubProcess::stub_proc_command_("cool_proc_cmd");
55

56
DStubProcess::DStubProcess(const char* name, asiolink::IOServicePtr io_service)
57
    : DProcessBase(name, io_service, DCfgMgrBasePtr(new DStubCfgMgr())) {
58 59
};

60

61 62 63
void
DStubProcess::init() {
    if (SimFailure::shouldFailOn(SimFailure::ftProcessInit)) {
64 65
        // Simulates a failure to instantiate the process.
        isc_throw(DProcessBaseError, "DStubProcess simulated init() failure");
66 67 68
    }
};

69
void
70 71 72 73
DStubProcess::run() {
    // Until shut down or an fatal error occurs, wait for and
    // execute a single callback. This is a preliminary implementation
    // that is likely to evolve as development progresses.
74
    // To use run(), the "managing" layer must issue an io_service::stop
75 76
    // or the call to run will continue to block, and shutdown will not
    // occur.
77
    asiolink::IOServicePtr& io_service = getIoService();
78 79 80 81
    while (!shouldShutdown()) {
        try {
            io_service->run_one();
        } catch (const std::exception& ex) {
82 83
            isc_throw (DProcessBaseError,
                std::string("Process run method failed:") + ex.what());
84 85 86 87
        }
    }
};

88 89
isc::data::ConstElementPtr
DStubProcess::shutdown(isc::data::ConstElementPtr /* args */) {
90 91 92 93
    if (SimFailure::shouldFailOn(SimFailure::ftProcessShutdown)) {
        // Simulates a failure during shutdown process.
        isc_throw(DProcessBaseError, "DStubProcess simulated shutdown failure");
    }
94

95 96 97
    setShutdownFlag(true);
    stopIOService();
    return (isc::config::createAnswer(0, "Shutdown inititiated."));
98
}
99

100
isc::data::ConstElementPtr
101
DStubProcess::configure(isc::data::ConstElementPtr config_set) {
102
    if (SimFailure::shouldFailOn(SimFailure::ftProcessConfigure)) {
103
        // Simulates a process configure failure.
104 105 106 107
        return (isc::config::createAnswer(1,
                "Simulated process configuration error."));
    }

108
    return (getCfgMgr()->parseConfig(config_set));
109 110
}

111 112
isc::data::ConstElementPtr
DStubProcess::command(const std::string& command,
113
                      isc::data::ConstElementPtr /* args */) {
114 115
    isc::data::ConstElementPtr answer;
    if (SimFailure::shouldFailOn(SimFailure::ftProcessCommand)) {
116
        // Simulates a process command execution failure.
117 118
        answer = isc::config::createAnswer(COMMAND_ERROR,
                                          "SimFailure::ftProcessCommand");
119
    } else if (command.compare(stub_proc_command_) == 0) {
120 121 122 123 124 125 126 127 128 129 130 131 132 133
        answer = isc::config::createAnswer(COMMAND_SUCCESS, "Command accepted");
    } else {
        answer = isc::config::createAnswer(COMMAND_INVALID,
                                           "Unrecognized command:" + command);
    }

    return (answer);
}

DStubProcess::~DStubProcess() {
};

//************************** DStubController *************************

134
// Define custom controller command supported by DStubController.
135
const char* DStubController::stub_ctl_command_("spiffy");
136 137 138

// Define custom command line option command supported by DStubController.
const char* DStubController::stub_option_x_ = "x";
139

140 141 142 143 144 145
/// @brief Defines the app name used to construct the controller
const char* DStubController::stub_app_name_ = "TestService";

/// @brief Defines the bin name used to construct the controller
const char* DStubController::stub_bin_name_ = "TestBin";

146

147 148
DControllerBasePtr&
DStubController::instance() {
149
    // If the singleton hasn't been created, do it now.
150
    if (!getController()) {
151 152
        DControllerBasePtr p(new DStubController());
        setController(p);
153 154 155 156 157 158
    }

    return (getController());
}

DStubController::DStubController()
159 160
    : DControllerBase(stub_app_name_, stub_bin_name_),
      processed_signals_(), record_signal_only_(false) {
161

Tomek Mrugalski's avatar
Tomek Mrugalski committed
162 163
    if (getenv("KEA_FROM_BUILD")) {
        setSpecFileName(std::string(getenv("KEA_FROM_BUILD")) +
164
            "/src/bin/d2/dhcp-ddns.spec");
165 166 167 168 169 170 171 172
    } else {
        setSpecFileName(D2_SPECFILE_LOCATION);
    }
}

bool
DStubController::customOption(int option, char* /* optarg */)
{
173
    // Check for the custom option supported by DStubController.
174
    if (static_cast<char>(option) == *stub_option_x_) {
175
        return (true);
176
    }
177

178 179 180 181 182
    return (false);
}

DProcessBase* DStubController::createProcess() {
    if (SimFailure::shouldFailOn(SimFailure::ftCreateProcessException)) {
183
        // Simulates a failure to instantiate the process due to exception.
184 185 186 187
        throw std::runtime_error("SimFailure::ftCreateProcess");
    }

    if (SimFailure::shouldFailOn(SimFailure::ftCreateProcessNull)) {
188
        // Simulates a failure to instantiate the process.
189 190 191 192
        return (NULL);
    }

    // This should be a successful instantiation.
193
    return (new DStubProcess(getAppName().c_str(), getIOService()));
194 195 196 197 198 199 200
}

isc::data::ConstElementPtr
DStubController::customControllerCommand(const std::string& command,
                                     isc::data::ConstElementPtr /* args */) {
    isc::data::ConstElementPtr answer;
    if (SimFailure::shouldFailOn(SimFailure::ftControllerCommand)) {
201
        // Simulates command failing to execute.
202 203
        answer = isc::config::createAnswer(COMMAND_ERROR,
                                          "SimFailure::ftControllerCommand");
204
    } else if (command.compare(stub_ctl_command_) == 0) {
205 206 207 208 209 210 211 212 213
        answer = isc::config::createAnswer(COMMAND_SUCCESS, "Command accepted");
    } else {
        answer = isc::config::createAnswer(COMMAND_INVALID,
                                           "Unrecognized command:" + command);
    }

    return (answer);
}

214
const std::string DStubController::getCustomOpts() const {
215 216
    // Return the "list" of custom options supported by DStubController.
    return (std::string(stub_option_x_));
217 218
}

219 220 221 222 223 224 225 226 227 228
void
DStubController::processSignal(int signum){
    processed_signals_.push_back(signum);
    if (record_signal_only_) {
        return;
    }

    DControllerBase::processSignal(signum);
}

229 230 231
DStubController::~DStubController() {
}

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
//************************** DControllerTest *************************

void
DControllerTest::writeFile(const std::string& content,
                           const std::string& module_name) {
    std::ofstream out(CFG_TEST_FILE, std::ios::trunc);
    ASSERT_TRUE(out.is_open());

    out << "{ \"" << (!module_name.empty() ? module_name
                      : getController()->getAppName())
        << "\": " << std::endl;

    out << content;
    out << " } " << std::endl;
    out.close();
}

void
DControllerTest::timedWriteCallback() {
    writeFile(new_cfg_content_);
}

void
DControllerTest::scheduleTimedWrite(const std::string& config,
                                    int write_time_ms) {
    new_cfg_content_ = config;
    write_timer_.reset(new asiolink::IntervalTimer(*getIOService()));
    write_timer_->setup(boost::bind(&DControllerTest::timedWriteCallback, this),
                        write_time_ms, asiolink::IntervalTimer::ONE_SHOT);
}

void
DControllerTest::runWithConfig(const std::string& config, int run_time_ms,
                               time_duration& elapsed_time) {
    // Create the config file.
    writeFile(config);

    // Shutdown (without error) after runtime.
    isc::asiolink::IntervalTimer timer(*getIOService());
    timer.setup(genShutdownCallback, run_time_ms);

    // Record start time, and invoke launch().
    // We catch and rethrow to allow testing error scenarios.
    ptime start = microsec_clock::universal_time();
    try  {
277 278 279 280
        // Set up valid command line arguments
        char* argv[] = { const_cast<char*>("progName"),
                         const_cast<char*>("-c"),
                         const_cast<char*>(DControllerTest::CFG_TEST_FILE),
281
                         const_cast<char*>("-d") };
282
        launch(4, argv);
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
    } catch (...) {
        // calculate elasped time, then rethrow it
        elapsed_time = microsec_clock::universal_time() - start;
        throw;
    }

    elapsed_time = microsec_clock::universal_time() - start;
}

DProcessBasePtr
DControllerTest:: getProcess() {
    DProcessBasePtr p;
    if (getController()) {
        p = getController()->getProcess();
    }
    return (p);
}

DCfgMgrBasePtr
DControllerTest::getCfgMgr() {
    DCfgMgrBasePtr p;
    if (getProcess()) {
        p = getProcess()->getCfgMgr();
    }

    return (p);
}

DCfgContextBasePtr
DControllerTest::getContext() {
    DCfgContextBasePtr p;
    if (getCfgMgr()) {
        p = getCfgMgr()->getContext();
    }

    return (p);
}

321
// Initialize controller wrapper's static instance getter member.
322 323
DControllerTest::InstanceGetter DControllerTest::instanceGetter_ = NULL;

324 325 326
/// @brief Defines the name of the configuration file to use
const char* DControllerTest::CFG_TEST_FILE = "d2-test-config.json";

327
//************************** ObjectParser *************************
328

329 330 331
ObjectParser::ObjectParser(const std::string& param_name,
                       ObjectStoragePtr& object_values)
    : param_name_(param_name), object_values_(object_values) {
332 333
}

334
ObjectParser::~ObjectParser(){
335 336 337
}

void
338
ObjectParser::build(isc::data::ConstElementPtr new_config) {
339 340 341 342 343 344 345 346 347
    if (SimFailure::shouldFailOn(SimFailure::ftElementBuild)) {
        // Simulates an error during element data parsing.
        isc_throw (DCfgMgrBaseError, "Simulated build exception");
    }

    value_ = new_config;
}

void
348
ObjectParser::commit() {
349 350 351 352
    if (SimFailure::shouldFailOn(SimFailure::ftElementCommit)) {
        // Simulates an error while committing the parsed element data.
        throw std::runtime_error("Simulated commit exception");
    }
353 354 355

    object_values_->setParam(param_name_, value_,
                             isc::data::Element::Position());
356 357 358 359
}

//************************** DStubContext *************************

360
DStubContext::DStubContext(): object_values_(new ObjectStorage()) {
361 362 363 364 365 366
}

DStubContext::~DStubContext() {
}

void
367 368 369
DStubContext::getObjectParam(const std::string& name,
                             isc::data::ConstElementPtr& value) {
    value = object_values_->getParam(name);
370 371
}

372 373 374
ObjectStoragePtr&
DStubContext::getObjectStorage() {
    return (object_values_);
375 376
}

377
DCfgContextBasePtr
378
DStubContext::clone() {
379
    return (DCfgContextBasePtr(new DStubContext(*this)));
380 381 382
}

DStubContext::DStubContext(const DStubContext& rhs): DCfgContextBase(rhs),
383
    object_values_(new ObjectStorage(*(rhs.object_values_))) {
384 385 386 387 388 389 390 391 392 393 394
}

//************************** DStubCfgMgr *************************

DStubCfgMgr::DStubCfgMgr()
    : DCfgMgrBase(DCfgContextBasePtr(new DStubContext())) {
}

DStubCfgMgr::~DStubCfgMgr() {
}

395
DCfgContextBasePtr
396 397 398 399
DStubCfgMgr::createNewContext() {
    return (DCfgContextBasePtr (new DStubContext()));
}

400
isc::dhcp::ParserPtr
401 402
DStubCfgMgr::createConfigParser(const std::string& element_id,
                                const isc::data::Element::Position& pos) {
403 404 405
    isc::dhcp::ParserPtr parser;
    DStubContextPtr context
        = boost::dynamic_pointer_cast<DStubContext>(getContext());
406
    if (element_id == "bool_test") {
407 408 409
        parser.reset(new isc::dhcp::
                         BooleanParser(element_id,
                                       context->getBooleanStorage()));
410
    } else if (element_id == "uint32_test") {
411 412
        parser.reset(new isc::dhcp::Uint32Parser(element_id,
                                                 context->getUint32Storage()));
413
    } else if (element_id == "string_test") {
414 415
        parser.reset(new isc::dhcp::StringParser(element_id,
                                                 context->getStringStorage()));
416 417 418 419 420
    } else {
        // Fail only if SimFailure dictates we should.  This makes it easier
        // to test parse ordering, by permitting a wide range of element ids
        // to "succeed" without specifically supporting them.
        if (SimFailure::shouldFailOn(SimFailure::ftElementUnknown)) {
421
            isc_throw(DCfgMgrBaseError,
422 423
                      "Configuration parameter not supported: " << element_id
                      << pos);
424 425
        }

426 427
        // Going to assume anything else is an object element.
        parser.reset(new ObjectParser(element_id, context->getObjectStorage()));
428 429
    }

430 431
    parsed_order_.push_back(element_id);
    return (parser);
432 433
}

434
}; // namespace isc::d2
435
}; // namespace isc