virtime.c 11.2 KB
Newer Older
1 2 3
/*
 * virtime.c: Time handling functions
 *
4
 * Copyright (C) 2006-2014 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16
 *
 * 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
17
 * License along with this library.  If not, see
O
Osier Yang 已提交
18
 * <http://www.gnu.org/licenses/>.
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
 *
 * Author: Daniel P. Berrange <berrange@redhat.com>
 *
 * The intent is that this file provides a set of time APIs which
 * are async signal safe, to allow use in between fork/exec eg by
 * the logging code.
 *
 * The reality is that wsnprintf is technically unsafe. We ought
 * to roll out our int -> str conversions to avoid this.
 *
 * We do *not* use regular libvirt error APIs for most of the code,
 * since those are not async signal safe, and we dont want logging
 * APIs generating timestamps to blow away real errors
 */

#include <config.h>

#include <stdio.h>
37
#include <unistd.h>
38
#include <sys/time.h>
39 40

#include "virtime.h"
41
#include "viralloc.h"
42
#include "virerror.h"
43
#include "virlog.h"
44 45 46

#define VIR_FROM_THIS VIR_FROM_NONE

47 48
VIR_LOG_INIT("util.time");

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
/* We prefer clock_gettime if available because that is officially
 * async signal safe according to POSIX. Many platforms lack it
 * though, so fallback to gettimeofday everywhere else
 */

/**
 * virTimeMillisNowRaw:
 * @now: filled with current time in milliseconds
 *
 * Retrieves the current system time, in milliseconds since the
 * epoch
 *
 * Returns 0 on success, -1 on error with errno set
 */
int virTimeMillisNowRaw(unsigned long long *now)
{
#ifdef HAVE_CLOCK_GETTIME
    struct timespec ts;

    if (clock_gettime(CLOCK_REALTIME, &ts) < 0)
        return -1;

    *now = (ts.tv_sec * 1000ull) + (ts.tv_nsec / (1000ull * 1000ull));
#else
    struct timeval tv;

    if (gettimeofday(&tv, NULL) < 0)
        return -1;

    *now = (tv.tv_sec * 1000ull) + (tv.tv_usec / 1000ull);
#endif

    return 0;
}


/**
 * virTimeFieldsNowRaw:
 * @fields: filled with current time fields
 *
 * Retrieves the current time, in broken-down field format.
 * The time is always in UTC.
 *
 * Returns 0 on success, -1 on error with errno set
 */
int virTimeFieldsNowRaw(struct tm *fields)
{
    unsigned long long now;

    if (virTimeMillisNowRaw(&now) < 0)
        return -1;

101 102 103
    virTimeFieldsThen(now, fields);

    return 0;
104 105 106 107 108 109 110 111
}


#define SECS_PER_HOUR   (60 * 60)
#define SECS_PER_DAY    (SECS_PER_HOUR * 24)
#define DIV(a, b) ((a) / (b) - ((a) % (b) < 0))
#define LEAPS_THRU_END_OF(y) (DIV (y, 4) - DIV (y, 100) + DIV (y, 400))

112
static const unsigned short int mon_yday[2][13] = {
113 114 115 116 117 118
    /* Normal years.  */
    { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 },
    /* Leap years.  */
    { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }
};

119 120 121
#define is_leap_year(y) \
    ((y) % 4 == 0 && ((y) % 100 != 0 || (y) % 400 == 0))

122
/**
123
 * virTimeFieldsThen:
124 125 126 127 128 129 130
 * @when: the time to convert in milliseconds
 * @fields: filled with time @when fields
 *
 * Converts the timestamp @when into broken-down field format.
 * Time time is always in UTC
 *
 */
131
void virTimeFieldsThen(unsigned long long when, struct tm *fields)
132 133
{
    /* This code is taken from GLibC under terms of LGPLv2+ */
J
John Ferlan 已提交
134 135 136
    /* Remove the 'offset' or GMT manipulation since we don't care. See
     * commit id '3ec12898' comments regarding localtime.
     */
137 138 139 140 141 142
    long int days, rem, y;
    const unsigned short int *ip;
    unsigned long long whenSecs = when / 1000ull;

    days = whenSecs / SECS_PER_DAY;
    rem = whenSecs % SECS_PER_DAY;
J
John Ferlan 已提交
143

144 145 146 147 148 149 150 151 152 153
    fields->tm_hour = rem / SECS_PER_HOUR;
    rem %= SECS_PER_HOUR;
    fields->tm_min = rem / 60;
    fields->tm_sec = rem % 60;
    /* January 1, 1970 was a Thursday.  */
    fields->tm_wday = (4 + days) % 7;
    if (fields->tm_wday < 0)
        fields->tm_wday += 7;
    y = 1970;

154
    while (days < 0 || days >= (is_leap_year(y) ? 366 : 365)) {
155 156 157 158 159
        /* Guess a corrected year, assuming 365 days per year.  */
        long int yg = y + days / 365 - (days % 365 < 0);

      /* Adjust DAYS and Y to match the guessed year.  */
      days -= ((yg - y) * 365
160 161
               + LEAPS_THRU_END_OF(yg - 1)
               - LEAPS_THRU_END_OF(y - 1));
162 163 164 165 166
      y = yg;
    }
    fields->tm_year = y - 1900;

    fields->tm_yday = days;
167
    ip = mon_yday[is_leap_year(y)];
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
    for (y = 11; days < (long int) ip[y]; --y)
        continue;
    days -= ip[y];
    fields->tm_mon = y;
    fields->tm_mday = days + 1;
}


/**
 * virTimeStringNowRaw:
 * @buf: a buffer at least VIR_TIME_STRING_BUFLEN in length
 *
 * Initializes @buf to contain a formatted timestamp
 * corresponding to the current time.
 *
 * Returns 0 on success, -1 on error
 */
int virTimeStringNowRaw(char *buf)
{
    unsigned long long now;

    if (virTimeMillisNowRaw(&now) < 0)
        return -1;

    return virTimeStringThenRaw(now, buf);
}


/**
 * virTimeStringThenRaw:
 * @when: the time to format in milliseconds
 * @buf: a buffer at least VIR_TIME_STRING_BUFLEN in length
 *
 * Initializes @buf to contain a formatted timestamp
 * corresponding to the time @when.
 *
 * Returns 0 on success, -1 on error
 */
int virTimeStringThenRaw(unsigned long long when, char *buf)
{
    struct tm fields;

210
    virTimeFieldsThen(when, &fields);
211 212 213 214 215 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

    fields.tm_year += 1900;
    fields.tm_mon += 1;

    if (snprintf(buf, VIR_TIME_STRING_BUFLEN,
                 "%4d-%02d-%02d %02d:%02d:%02d.%03d+0000",
                 fields.tm_year, fields.tm_mon, fields.tm_mday,
                 fields.tm_hour, fields.tm_min, fields.tm_sec,
                 (int) (when % 1000)) >= VIR_TIME_STRING_BUFLEN) {
        errno = ERANGE;
        return -1;
    }

    return 0;
}


/**
 * virTimeMillisNow:
 * @now: filled with current time in milliseconds
 *
 * Retrieves the current system time, in milliseconds since the
 * epoch
 *
 * Returns 0 on success, -1 on error with error reported
 */
int virTimeMillisNow(unsigned long long *now)
{
    if (virTimeMillisNowRaw(now) < 0) {
        virReportSystemError(errno, "%s",
                             _("Unable to get current time"));
        return -1;
    }
    return 0;
}


/**
 * virTimeFieldsNowRaw:
 * @fields: filled with current time fields
 *
 * Retrieves the current time, in broken-down field format.
 * The time is always in UTC.
 *
 * Returns 0 on success, -1 on error with errno reported
 */
int virTimeFieldsNow(struct tm *fields)
{
    unsigned long long now;

    if (virTimeMillisNow(&now) < 0)
        return -1;

264
    virTimeFieldsThen(now, fields);
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
    return 0;
}


/**
 * virTimeStringNow:
 *
 * Creates a string containing a formatted timestamp
 * corresponding to the current time.
 *
 * This function is not async signal safe
 *
 * Returns a formatted allocated string, or NULL on error
 */
char *virTimeStringNow(void)
{
    char *ret;

283
    if (VIR_ALLOC_N(ret, VIR_TIME_STRING_BUFLEN) < 0)
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
        return NULL;

    if (virTimeStringNowRaw(ret) < 0) {
        virReportSystemError(errno, "%s",
                             _("Unable to format time"));
        VIR_FREE(ret);
        return NULL;
    }

    return ret;
}


/**
 * virTimeStringThen:
 * @when: the time to format in milliseconds
 *
 * Creates a string containing a formatted timestamp
 * corresponding to the time @when.
 *
 * This function is not async signal safe
 *
 * Returns a formatted allocated string, or NULL on error
 */
char *virTimeStringThen(unsigned long long when)
{
    char *ret;

312
    if (VIR_ALLOC_N(ret, VIR_TIME_STRING_BUFLEN) < 0)
313 314 315 316 317 318 319 320 321 322 323
        return NULL;

    if (virTimeStringThenRaw(when, ret) < 0) {
        virReportSystemError(errno, "%s",
                             _("Unable to format time"));
        VIR_FREE(ret);
        return NULL;
    }

    return ret;
}
324 325 326 327 328

/**
 * virTimeLocalOffsetFromUTC:
 *
 * This function is threadsafe, but is *not* async signal safe (due to
329
 * gmtime_r() and mktime()).
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
 *
 * @offset: pointer to time_t that will be set to the difference
 *          between localtime and UTC in seconds (east of UTC is a
 *          positive number, and west of UTC is a negative number.
 *
 * Returns 0 on success, -1 on error with error reported
 */
int
virTimeLocalOffsetFromUTC(long *offset)
{
    struct tm gmtimeinfo;
    time_t current, utc;

    /* time() gives seconds since Epoch in current timezone */
    if ((current = time(NULL)) == (time_t)-1) {
        virReportSystemError(errno, "%s",
                             _("failed to get current system time"));
        return -1;
    }

    /* treat current as if it were in UTC */
    if (!gmtime_r(&current, &gmtimeinfo)) {
        virReportSystemError(errno, "%s",
                             _("gmtime_r failed"));
        return -1;
    }

357 358 359
    /* tell mktime to figure out itself whether or not DST is in effect */
    gmtimeinfo.tm_isdst = -1;

360 361 362 363 364 365 366 367 368 369
    /* mktime() also obeys current timezone rules */
    if ((utc = mktime(&gmtimeinfo)) == (time_t)-1) {
        virReportSystemError(errno, "%s",
                             _("mktime failed"));
        return -1;
    }

    *offset = current - utc;
    return 0;
}
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446

/**
 * virTimeBackOffStart:
 * @var: Timeout variable (with type virTimeBackOffVar).
 * @first: Initial time to wait (milliseconds).
 * @timeout: Timeout (milliseconds).
 *
 * Initialize the timeout variable @var and start the timer running.
 *
 * Returns 0 on success, -1 on error and raises a libvirt error.
 */
int
virTimeBackOffStart(virTimeBackOffVar *var,
                    unsigned long long first, unsigned long long timeout)
{
    if (virTimeMillisNow(&var->start_t) < 0)
        return -1;

    var->next = first;
    var->limit_t = var->start_t + timeout;
    return 0;
}

/**
 * virTimeBackOffWait
 * @var: Timeout variable (with type virTimeBackOffVar *).
 *
 * You must initialize @var first by calling the following function,
 * which also starts the timer:
 *
 * if (virTimeBackOffStart(&var, first, timeout) < 0) {
 *   // handle errors
 * }
 *
 * Then you use a while loop:
 *
 * while (virTimeBackOffWait(&var)) {
 *   //...
 * }
 *
 * The while loop that runs the body of the code repeatedly, with an
 * exponential backoff.  It first waits for first milliseconds, then
 * runs the body, then waits for 2*first ms, then runs the body again.
 * Then 4*first ms, and so on.
 *
 * When timeout milliseconds is reached, the while loop ends.
 *
 * The body should use "break" or "goto" when whatever condition it is
 * testing for succeeds (or there is an unrecoverable error).
 */
bool
virTimeBackOffWait(virTimeBackOffVar *var)
{
    unsigned long long t, next;

    ignore_value(virTimeMillisNowRaw(&t));

    VIR_DEBUG("t=%llu, limit=%llu", t, var->limit_t);

    if (t > var->limit_t)
        return 0;               /* ends the while loop */

    next = var->next;
    var->next *= 2;

    /* If sleeping would take us beyond the limit, then shorten the
     * sleep.  This is so we always run the body just before the final
     * timeout.
     */
    if (t + next > var->limit_t)
        next = var->limit_t - t;

    VIR_DEBUG("sleeping for %llu ms", next);

    usleep(next * 1000);
    return 1;
}