virkeepalive.c 11.8 KB
Newer Older
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
/*
 * virkeepalive.c: keepalive handling
 *
 * Copyright (C) 2011 Red Hat, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
 *
 * Author: Jiri Denemark <jdenemar@redhat.com>
 */

#include <config.h>

#include "memory.h"
#include "threads.h"
#include "virfile.h"
#include "logging.h"
#include "util.h"
#include "virterror_internal.h"
#include "virnetsocket.h"
#include "virkeepaliveprotocol.h"
#include "virkeepalive.h"

#define VIR_FROM_THIS VIR_FROM_RPC
#define virNetError(code, ...)                                    \
    virReportErrorHelper(VIR_FROM_THIS, code, __FILE__,           \
                         __FUNCTION__, __LINE__, __VA_ARGS__)

struct _virKeepAlive {
    int refs;
    virMutex lock;

    int interval;
    unsigned int count;
    unsigned int countToDeath;
    time_t lastPacketReceived;
48
    time_t intervalStart;
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
    int timer;

    virNetMessagePtr response;
    int responseTimer;

    virKeepAliveSendFunc sendCB;
    virKeepAliveDeadFunc deadCB;
    virKeepAliveFreeFunc freeCB;
    void *client;
};


static void
virKeepAliveLock(virKeepAlivePtr ka)
{
    virMutexLock(&ka->lock);
}

static void
virKeepAliveUnlock(virKeepAlivePtr ka)
{
    virMutexUnlock(&ka->lock);
}


static virNetMessagePtr
virKeepAliveMessage(int proc)
{
    virNetMessagePtr msg;

    if (!(msg = virNetMessageNew(false)))
        return NULL;

    msg->header.prog = KEEPALIVE_PROGRAM;
    msg->header.vers = KEEPALIVE_PROTOCOL_VERSION;
    msg->header.type = VIR_NET_MESSAGE;
    msg->header.proc = proc;

    if (virNetMessageEncodeHeader(msg) < 0 ||
        virNetMessageEncodePayloadEmpty(msg) < 0) {
        virNetMessageFree(msg);
        return NULL;
    }

    return msg;
}


static void
virKeepAliveSend(virKeepAlivePtr ka, virNetMessagePtr msg)
{
    const char *proc = NULL;
    void *client = ka->client;
    virKeepAliveSendFunc sendCB = ka->sendCB;

    switch (msg->header.proc) {
    case KEEPALIVE_PROC_PING:
        proc = "request";
        break;
    case KEEPALIVE_PROC_PONG:
        proc = "response";
        break;
    }

    if (!proc) {
        VIR_WARN("Refusing to send unknown keepalive message: %d",
                 msg->header.proc);
        virNetMessageFree(msg);
        return;
    }

    VIR_DEBUG("Sending keepalive %s to client %p", proc, ka->client);
    PROBE(RPC_KEEPALIVE_SEND,
          "ka=%p client=%p prog=%d vers=%d proc=%d",
          ka, ka->client, msg->header.prog, msg->header.vers, msg->header.proc);

    ka->refs++;
    virKeepAliveUnlock(ka);

    if (sendCB(client, msg) < 0) {
        VIR_WARN("Failed to send keepalive %s to client %p", proc, client);
        virNetMessageFree(msg);
    }

    virKeepAliveLock(ka);
    ka->refs--;
}


static void
virKeepAliveScheduleResponse(virKeepAlivePtr ka)
{
    if (ka->responseTimer == -1)
        return;

    VIR_DEBUG("Scheduling keepalive response to client %p", ka->client);

    if (!ka->response &&
        !(ka->response = virKeepAliveMessage(KEEPALIVE_PROC_PONG))) {
        VIR_WARN("Failed to generate keepalive response");
        return;
    }

    virEventUpdateTimeout(ka->responseTimer, 0);
}


156 157 158
static bool
virKeepAliveTimerInternal(virKeepAlivePtr ka,
                          virNetMessagePtr *msg)
159 160 161
{
    time_t now = time(NULL);

162 163 164 165 166
    if (ka->interval <= 0 || ka->intervalStart == 0)
        return false;

    if (now - ka->intervalStart < ka->interval) {
        int timeout = ka->interval - (now - ka->intervalStart);
167 168 169
        virEventUpdateTimeout(ka->timer, timeout * 1000);
        return false;
    }
170 171 172 173 174 175 176 177 178 179 180 181 182

    PROBE(RPC_KEEPALIVE_TIMEOUT,
          "ka=%p client=%p countToDeath=%d idle=%d",
          ka, ka->client, ka->countToDeath,
          (int) (now - ka->lastPacketReceived));


    if (ka->countToDeath == 0) {
        VIR_WARN("No response from client %p after %d keepalive messages in"
                 " %d seconds",
                 ka->client,
                 ka->count,
                 (int) (now - ka->lastPacketReceived));
183 184 185
        return true;
    } else {
        ka->countToDeath--;
186
        ka->intervalStart = now;
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
        *msg = virKeepAliveMessage(KEEPALIVE_PROC_PING);
        virEventUpdateTimeout(ka->timer, ka->interval * 1000);
        return false;
    }
}


static void
virKeepAliveTimer(int timer ATTRIBUTE_UNUSED, void *opaque)
{
    virKeepAlivePtr ka = opaque;
    virNetMessagePtr msg = NULL;
    bool dead;

    virKeepAliveLock(ka);

    dead = virKeepAliveTimerInternal(ka, &msg);

    if (dead) {
        virKeepAliveDeadFunc deadCB = ka->deadCB;
        void *client = ka->client;

209 210 211 212 213
        ka->refs++;
        virKeepAliveUnlock(ka);
        deadCB(client);
        virKeepAliveLock(ka);
        ka->refs--;
214 215
    } else if (msg) {
        virKeepAliveSend(ka, msg);
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 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 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 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
    }

    virKeepAliveUnlock(ka);
}


static void
virKeepAliveResponseTimer(int timer ATTRIBUTE_UNUSED, void *opaque)
{
    virKeepAlivePtr ka = opaque;
    virNetMessagePtr msg;

    virKeepAliveLock(ka);

    VIR_DEBUG("ka=%p, client=%p, response=%p",
              ka, ka->client, ka->response);

    if (ka->response) {
        msg = ka->response;
        ka->response = NULL;
        virKeepAliveSend(ka, msg);
    }

    virEventUpdateTimeout(ka->responseTimer, ka->response ? 0 : -1);

    virKeepAliveUnlock(ka);
}


static void
virKeepAliveTimerFree(void *opaque)
{
    virKeepAliveFree(opaque);
}


virKeepAlivePtr
virKeepAliveNew(int interval,
                unsigned int count,
                void *client,
                virKeepAliveSendFunc sendCB,
                virKeepAliveDeadFunc deadCB,
                virKeepAliveFreeFunc freeCB)
{
    virKeepAlivePtr ka;

    VIR_DEBUG("client=%p, interval=%d, count=%u", client, interval, count);

    if (VIR_ALLOC(ka) < 0) {
        virReportOOMError();
        return NULL;
    }

    if (virMutexInit(&ka->lock) < 0) {
        VIR_FREE(ka);
        return NULL;
    }

    ka->refs = 1;
    ka->interval = interval;
    ka->count = count;
    ka->countToDeath = count;
    ka->timer = -1;
    ka->client = client;
    ka->sendCB = sendCB;
    ka->deadCB = deadCB;
    ka->freeCB = freeCB;

    ka->responseTimer = virEventAddTimeout(-1, virKeepAliveResponseTimer,
                                           ka, virKeepAliveTimerFree);
    if (ka->responseTimer < 0) {
        virKeepAliveFree(ka);
        return NULL;
    }
    /* the timer now has a reference to ka */
    ka->refs++;

    PROBE(RPC_KEEPALIVE_NEW,
          "ka=%p client=%p refs=%d",
          ka, ka->client, ka->refs);

    return ka;
}


void
virKeepAliveRef(virKeepAlivePtr ka)
{
    virKeepAliveLock(ka);
    ka->refs++;
    PROBE(RPC_KEEPALIVE_REF,
          "ka=%p client=%p refs=%d",
          ka, ka->client, ka->refs);
    virKeepAliveUnlock(ka);
}


void
virKeepAliveFree(virKeepAlivePtr ka)
{
    if (!ka)
        return;

    virKeepAliveLock(ka);
    PROBE(RPC_KEEPALIVE_FREE,
          "ka=%p client=%p refs=%d",
          ka, ka->client, ka->refs);

    if (--ka->refs > 0) {
        virKeepAliveUnlock(ka);
        return;
    }

    virMutexDestroy(&ka->lock);
    ka->freeCB(ka->client);
    VIR_FREE(ka);
}


int
virKeepAliveStart(virKeepAlivePtr ka,
                  int interval,
                  unsigned int count)
{
    int ret = -1;
    time_t delay;
    int timeout;
343
    time_t now;
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373

    virKeepAliveLock(ka);

    if (ka->timer >= 0) {
        VIR_DEBUG("Keepalive messages already enabled");
        ret = 0;
        goto cleanup;
    }

    if (interval > 0) {
        if (ka->interval > 0) {
            virNetError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("keepalive interval already set"));
            goto cleanup;
        }
        ka->interval = interval;
        ka->count = count;
        ka->countToDeath = count;
    }

    if (ka->interval <= 0) {
        VIR_DEBUG("Keepalive messages disabled by configuration");
        ret = 0;
        goto cleanup;
    }

    PROBE(RPC_KEEPALIVE_START,
          "ka=%p client=%p interval=%d count=%u",
          ka, ka->client, interval, count);

374 375
    now = time(NULL);
    delay = now - ka->lastPacketReceived;
376 377 378 379
    if (delay > ka->interval)
        timeout = 0;
    else
        timeout = ka->interval - delay;
380
    ka->intervalStart = now - (ka->interval - timeout);
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
    ka->timer = virEventAddTimeout(timeout * 1000, virKeepAliveTimer,
                                   ka, virKeepAliveTimerFree);
    if (ka->timer < 0)
        goto cleanup;

    /* the timer now has another reference to this object */
    ka->refs++;
    ret = 0;

cleanup:
    virKeepAliveUnlock(ka);
    return ret;
}


396 397
static void
virKeepAliveStopInternal(virKeepAlivePtr ka, bool all)
398 399 400 401
{
    virKeepAliveLock(ka);

    PROBE(RPC_KEEPALIVE_STOP,
402 403
          "ka=%p client=%p all=%d",
          ka, ka->client, all);
404 405 406 407 408 409

    if (ka->timer > 0) {
        virEventRemoveTimeout(ka->timer);
        ka->timer = -1;
    }

410 411 412 413 414
    if (all) {
        if (ka->responseTimer > 0) {
            virEventRemoveTimeout(ka->responseTimer);
            ka->responseTimer = -1;
        }
415

416 417 418
        virNetMessageFree(ka->response);
        ka->response = NULL;
    }
419 420 421 422 423

    virKeepAliveUnlock(ka);
}


424 425 426 427 428 429 430 431 432 433 434 435 436 437
void
virKeepAliveStop(virKeepAlivePtr ka)
{
    virKeepAliveStopInternal(ka, true);
}


void
virKeepAliveStopSending(virKeepAlivePtr ka)
{
    virKeepAliveStopInternal(ka, false);
}


438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
int
virKeepAliveTimeout(virKeepAlivePtr ka)
{
    int timeout;

    if (!ka)
        return -1;

    virKeepAliveLock(ka);

    if (ka->interval <= 0 || ka->intervalStart == 0) {
        timeout = -1;
    } else {
        timeout = ka->interval - (time(NULL) - ka->intervalStart);
        if (timeout < 0)
            timeout = 0;
    }

    virKeepAliveUnlock(ka);

    if (timeout < 0)
        return -1;
    else
        return timeout * 1000;
}


bool
virKeepAliveTrigger(virKeepAlivePtr ka,
                    virNetMessagePtr *msg)
{
    bool dead;

    *msg = NULL;
    if (!ka)
        return false;

    virKeepAliveLock(ka);
    dead = virKeepAliveTimerInternal(ka, msg);
    virKeepAliveUnlock(ka);

    return dead;
}


483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
bool
virKeepAliveCheckMessage(virKeepAlivePtr ka,
                         virNetMessagePtr msg)
{
    bool ret = false;

    VIR_DEBUG("ka=%p, client=%p, msg=%p",
              ka, ka ? ka->client : "(null)", msg);

    if (!ka)
        return false;

    virKeepAliveLock(ka);

    ka->countToDeath = ka->count;
498
    ka->lastPacketReceived = ka->intervalStart = time(NULL);
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530

    if (msg->header.prog == KEEPALIVE_PROGRAM &&
        msg->header.vers == KEEPALIVE_PROTOCOL_VERSION &&
        msg->header.type == VIR_NET_MESSAGE) {
        PROBE(RPC_KEEPALIVE_RECEIVED,
              "ka=%p client=%p prog=%d vers=%d proc=%d",
              ka, ka->client, msg->header.prog,
              msg->header.vers, msg->header.proc);
        ret = true;
        switch (msg->header.proc) {
        case KEEPALIVE_PROC_PING:
            VIR_DEBUG("Got keepalive request from client %p", ka->client);
            virKeepAliveScheduleResponse(ka);
            break;

        case KEEPALIVE_PROC_PONG:
            VIR_DEBUG("Got keepalive response from client %p", ka->client);
            break;

        default:
            VIR_DEBUG("Ignoring unknown keepalive message %d from client %p",
                      msg->header.proc, ka->client);
        }
    }

    if (ka->timer >= 0)
        virEventUpdateTimeout(ka->timer, ka->interval * 1000);

    virKeepAliveUnlock(ka);

    return ret;
}