summaryrefslogtreecommitdiffstats
path: root/src/include/utime.h
blob: 42f9b08706c2a51103627f037f51a949064f7644 (plain)
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
48
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
156
157
158
159
160
161
162
163
164
165
166
167
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
210
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
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
343
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
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
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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- 
// vim: ts=8 sw=2 smarttab
/*
 * Ceph - scalable distributed file system
 *
 * Copyright (C) 2004-2006 Sage Weil <sage@newdream.net>
 *
 * This is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1, as published by the Free Software 
 * Foundation.  See file COPYING.
 * 
 */

#ifndef CEPH_UTIME_H
#define CEPH_UTIME_H

#include <math.h>
#include <sys/time.h>
#include <time.h>
#include <errno.h>

#include "include/types.h"
#include "include/timegm.h"
#include "common/strtol.h"
#include "common/ceph_time.h"
#include "common/safe_io.h"
#include "common/SubProcess.h"
#include "include/denc.h"


// --------
// utime_t

inline __u32 cap_to_u32_max(__u64 t) {
  return std::min(t, (__u64)std::numeric_limits<uint32_t>::max());
}
/* WARNING: If add member in utime_t, please make sure the encode/decode function
 * work well. For little-endian machine, we should make sure there is no padding
 * in 32-bit machine and 64-bit machine.
 * You should also modify the padding_check function.
 */
class utime_t {
public:
  struct {
    __u32 tv_sec, tv_nsec;
  } tv;

 public:
  bool is_zero() const {
    return (tv.tv_sec == 0) && (tv.tv_nsec == 0);
  }

  void normalize() {
    if (tv.tv_nsec > 1000000000ul) {
      tv.tv_sec = cap_to_u32_max(tv.tv_sec + tv.tv_nsec / (1000000000ul));
      tv.tv_nsec %= 1000000000ul;
    }
  }

  // cons
  utime_t() { tv.tv_sec = 0; tv.tv_nsec = 0; }
  utime_t(time_t s, int n) { tv.tv_sec = s; tv.tv_nsec = n; normalize(); }
  utime_t(const struct ceph_timespec &v) {
    decode_timeval(&v);
  }
  utime_t(const struct timespec v)
  {
    // NOTE: this is used by ceph_clock_now() so should be kept
    // as thin as possible.
    tv.tv_sec = v.tv_sec;
    tv.tv_nsec = v.tv_nsec;
  }
  // conversion from ceph::real_time/coarse_real_time
  template <typename Clock, typename std::enable_if_t<
            ceph::converts_to_timespec_v<Clock>>* = nullptr>
  explicit utime_t(const std::chrono::time_point<Clock>& t)
    : utime_t(Clock::to_timespec(t)) {} // forward to timespec ctor

  utime_t(const struct timeval &v) {
    set_from_timeval(&v);
  }
  utime_t(const struct timeval *v) {
    set_from_timeval(v);
  }
  void to_timespec(struct timespec *ts) const {
    ts->tv_sec = tv.tv_sec;
    ts->tv_nsec = tv.tv_nsec;
  }
  void set_from_double(double d) { 
    tv.tv_sec = (__u32)trunc(d);
    tv.tv_nsec = (__u32)((d - (double)tv.tv_sec) * 1000000000.0);
  }

  real_time to_real_time() const {
    ceph_timespec ts;
    encode_timeval(&ts);
    return ceph::real_clock::from_ceph_timespec(ts);
  }

  // accessors
  time_t        sec()  const { return tv.tv_sec; } 
  long          usec() const { return tv.tv_nsec/1000; }
  int           nsec() const { return tv.tv_nsec; }

  // ref accessors/modifiers
  __u32&         sec_ref()  { return tv.tv_sec; }
  __u32&         nsec_ref() { return tv.tv_nsec; }

  uint64_t to_nsec() const {
    return (uint64_t)tv.tv_nsec + (uint64_t)tv.tv_sec * 1000000000ull;
  }
  uint64_t to_msec() const {
    return (uint64_t)tv.tv_nsec / 1000000ull + (uint64_t)tv.tv_sec * 1000ull;
  }

  void copy_to_timeval(struct timeval *v) const {
    v->tv_sec = tv.tv_sec;
    v->tv_usec = tv.tv_nsec/1000;
  }
  void set_from_timeval(const struct timeval *v) {
    tv.tv_sec = v->tv_sec;
    tv.tv_nsec = v->tv_usec*1000;
  }
  void padding_check() {
    static_assert(
      sizeof(utime_t) ==
        sizeof(tv.tv_sec) +
        sizeof(tv.tv_nsec)
      ,
      "utime_t have padding");
  }
  void encode(bufferlist &bl) const {
#if defined(CEPH_LITTLE_ENDIAN)
    bl.append((char *)(this), sizeof(__u32) + sizeof(__u32));
#else
    using ceph::encode;
    encode(tv.tv_sec, bl);
    encode(tv.tv_nsec, bl);
#endif
  }
  void decode(bufferlist::const_iterator &p) {
#if defined(CEPH_LITTLE_ENDIAN)
    p.copy(sizeof(__u32) + sizeof(__u32), (char *)(this));
#else
    using ceph::decode;
    decode(tv.tv_sec, p);
    decode(tv.tv_nsec, p);
#endif
  }

  DENC(utime_t, v, p) {
    denc(v.tv.tv_sec, p);
    denc(v.tv.tv_nsec, p);
  }


  void encode_timeval(struct ceph_timespec *t) const {
    t->tv_sec = tv.tv_sec;
    t->tv_nsec = tv.tv_nsec;
  }
  void decode_timeval(const struct ceph_timespec *t) {
    tv.tv_sec = t->tv_sec;
    tv.tv_nsec = t->tv_nsec;
  }

  utime_t round_to_minute() {
    struct tm bdt;
    time_t tt = sec();
    localtime_r(&tt, &bdt);
    bdt.tm_sec = 0;
    tt = mktime(&bdt);
    return utime_t(tt, 0);
  }

  utime_t round_to_hour() {
    struct tm bdt;
    time_t tt = sec();
    localtime_r(&tt, &bdt);
    bdt.tm_sec = 0;
    bdt.tm_min = 0;
    tt = mktime(&bdt);
    return utime_t(tt, 0);
  }

  utime_t round_to_day() {
    struct tm bdt;
    time_t tt = sec();
    localtime_r(&tt, &bdt);
    bdt.tm_sec = 0;
    bdt.tm_min = 0;
    bdt.tm_hour = 0;
    tt = mktime(&bdt);
    return utime_t(tt, 0);
  }

  // cast to double
  operator double() const {
    return (double)sec() + ((double)nsec() / 1000000000.0L);
  }
  operator ceph_timespec() const {
    ceph_timespec ts;
    ts.tv_sec = sec();
    ts.tv_nsec = nsec();
    return ts;
  }

  void sleep() const {
    struct timespec ts;
    to_timespec(&ts);
    nanosleep(&ts, NULL);
  }

  // output
  ostream& gmtime(ostream& out) const {
    out.setf(std::ios::right);
    char oldfill = out.fill();
    out.fill('0');
    if (sec() < ((time_t)(60*60*24*365*10))) {
      // raw seconds.  this looks like a relative time.
      out << (long)sec() << "." << std::setw(6) << usec();
    } else {
      // this looks like an absolute time.
      //  aim for http://en.wikipedia.org/wiki/ISO_8601
      struct tm bdt;
      time_t tt = sec();
      gmtime_r(&tt, &bdt);
      out << std::setw(4) << (bdt.tm_year+1900)  // 2007 -> '07'
	  << '-' << std::setw(2) << (bdt.tm_mon+1)
	  << '-' << std::setw(2) << bdt.tm_mday
	  << ' '
	  << std::setw(2) << bdt.tm_hour
	  << ':' << std::setw(2) << bdt.tm_min
	  << ':' << std::setw(2) << bdt.tm_sec;
      out << "." << std::setw(6) << usec();
      out << "Z";
    }
    out.fill(oldfill);
    out.unsetf(std::ios::right);
    return out;
  }

  // output
  ostream& gmtime_nsec(ostream& out) const {
    out.setf(std::ios::right);
    char oldfill = out.fill();
    out.fill('0');
    if (sec() < ((time_t)(60*60*24*365*10))) {
      // raw seconds.  this looks like a relative time.
      out << (long)sec() << "." << std::setw(6) << usec();
    } else {
      // this looks like an absolute time.
      //  aim for http://en.wikipedia.org/wiki/ISO_8601
      struct tm bdt;
      time_t tt = sec();
      gmtime_r(&tt, &bdt);
      out << std::setw(4) << (bdt.tm_year+1900)  // 2007 -> '07'
	  << '-' << std::setw(2) << (bdt.tm_mon+1)
	  << '-' << std::setw(2) << bdt.tm_mday
	  << ' '
	  << std::setw(2) << bdt.tm_hour
	  << ':' << std::setw(2) << bdt.tm_min
	  << ':' << std::setw(2) << bdt.tm_sec;
      out << "." << std::setw(9) << nsec();
      out << "Z";
    }
    out.fill(oldfill);
    out.unsetf(std::ios::right);
    return out;
  }

  // output
  ostream& asctime(ostream& out) const {
    out.setf(std::ios::right);
    char oldfill = out.fill();
    out.fill('0');
    if (sec() < ((time_t)(60*60*24*365*10))) {
      // raw seconds.  this looks like a relative time.
      out << (long)sec() << "." << std::setw(6) << usec();
    } else {
      // this looks like an absolute time.
      //  aim for http://en.wikipedia.org/wiki/ISO_8601
      struct tm bdt;
      time_t tt = sec();
      gmtime_r(&tt, &bdt);

      char buf[128];
      asctime_r(&bdt, buf);
      int len = strlen(buf);
      if (buf[len - 1] == '\n')
        buf[len - 1] = '\0';
      out << buf;
    }
    out.fill(oldfill);
    out.unsetf(std::ios::right);
    return out;
  }
  
  ostream& localtime(ostream& out) const {
    out.setf(std::ios::right);
    char oldfill = out.fill();
    out.fill('0');
    if (sec() < ((time_t)(60*60*24*365*10))) {
      // raw seconds.  this looks like a relative time.
      out << (long)sec() << "." << std::setw(6) << usec();
    } else {
      // this looks like an absolute time.
      //  aim for http://en.wikipedia.org/wiki/ISO_8601
      struct tm bdt;
      time_t tt = sec();
      localtime_r(&tt, &bdt);
      out << std::setw(4) << (bdt.tm_year+1900)  // 2007 -> '07'
	  << '-' << std::setw(2) << (bdt.tm_mon+1)
	  << '-' << std::setw(2) << bdt.tm_mday
	  << ' '
	  << std::setw(2) << bdt.tm_hour
	  << ':' << std::setw(2) << bdt.tm_min
	  << ':' << std::setw(2) << bdt.tm_sec;
      out << "." << std::setw(6) << usec();
      //out << '_' << bdt.tm_zone;
    }
    out.fill(oldfill);
    out.unsetf(std::ios::right);
    return out;
  }

  int sprintf(char *out, int outlen) const {
    struct tm bdt;
    time_t tt = sec();
    localtime_r(&tt, &bdt);

    return ::snprintf(out, outlen,
		    "%04d-%02d-%02d %02d:%02d:%02d.%06ld",
		    bdt.tm_year + 1900, bdt.tm_mon + 1, bdt.tm_mday,
		    bdt.tm_hour, bdt.tm_min, bdt.tm_sec, usec());
  }

  static int snprintf(char *out, int outlen, time_t tt) {
    struct tm bdt;
    localtime_r(&tt, &bdt);

    return ::snprintf(out, outlen,
        "%04d-%02d-%02d %02d:%02d:%02d",
        bdt.tm_year + 1900, bdt.tm_mon + 1, bdt.tm_mday,
        bdt.tm_hour, bdt.tm_min, bdt.tm_sec);
  }

  static int invoke_date(const std::string& date_str, utime_t *result) {
     char buf[256];

     SubProcess bin_date("/bin/date", SubProcess::CLOSE, SubProcess::PIPE,
			 SubProcess::KEEP);
     bin_date.add_cmd_args("-d", date_str.c_str(), "+%s %N", NULL);

     int r = bin_date.spawn();
     if (r < 0) return r;

     ssize_t n = safe_read(bin_date.get_stdout(), buf, sizeof(buf));

     r = bin_date.join();
     if (r || n <= 0) return -EINVAL;

     uint64_t epoch, nsec;
     std::istringstream iss(buf);

     iss >> epoch;
     iss >> nsec;

     *result = utime_t(epoch, nsec);

     return 0;
  }


  static int parse_date(const string& date, uint64_t *epoch, uint64_t *nsec,
                        string *out_date=NULL, string *out_time=NULL) {
    struct tm tm;
    memset(&tm, 0, sizeof(tm));

    if (nsec)
      *nsec = 0;

    const char *p = strptime(date.c_str(), "%Y-%m-%d", &tm);
    if (p) {
      if (*p == ' ' || *p == 'T') {
	p++;
	// strptime doesn't understand fractional/decimal seconds, and
	// it also only takes format chars or literals, so we have to
	// get creative.
	char fmt[32] = {0};
	strncpy(fmt, p, sizeof(fmt) - 1);
	fmt[0] = '%';
	fmt[1] = 'H';
	fmt[2] = ':';
	fmt[3] = '%';
	fmt[4] = 'M';
	fmt[6] = '%';
	fmt[7] = 'S';
	const char *subsec = 0;
	char *q = fmt + 8;
	if (*q == '.') {
	  ++q;
	  subsec = p + 9;
	  q = fmt + 9;
	  while (*q && isdigit(*q)) {
	    ++q;
	  }
	}
	// look for tz...
	if (*q == '-' || *q == '+') {
	  *q = '%';
	  *(q+1) = 'z';
	  *(q+2) = 0;
	}
	p = strptime(p, fmt, &tm);
	if (!p) {
	  return -EINVAL;
	}
        if (nsec && subsec) {
          unsigned i;
          char buf[10]; /* 9 digit + null termination */
          for (i = 0; (i < sizeof(buf) - 1) && isdigit(*subsec); ++i, ++subsec) {
            buf[i] = *subsec;
          }
          for (; i < sizeof(buf) - 1; ++i) {
            buf[i] = '0';
          }
          buf[i] = '\0';
          string err;
          *nsec = (uint64_t)strict_strtol(buf, 10, &err);
          if (!err.empty()) {
            return -EINVAL;
          }
        }
      }
    } else {
      int sec, usec;
      int r = sscanf(date.c_str(), "%d.%d", &sec, &usec);
      if (r != 2) {
        return -EINVAL;
      }

      time_t tt = sec;
      gmtime_r(&tt, &tm);

      if (nsec) {
        *nsec = (uint64_t)usec * 1000;
      }
    }

    // apply the tm_gmtoff manually below, since none of mktime,
    // gmtime, and localtime seem to do it.  zero it out here just in
    // case some other libc *does* apply it.  :(
    auto gmtoff = tm.tm_gmtoff;
    tm.tm_gmtoff = 0;

    time_t t = internal_timegm(&tm);
    if (epoch)
      *epoch = (uint64_t)t;

    *epoch -= gmtoff;

    if (out_date) {
      char buf[32];
      strftime(buf, sizeof(buf), "%F", &tm);
      *out_date = buf;
    }
    if (out_time) {
      char buf[32];
      strftime(buf, sizeof(buf), "%T", &tm);
      *out_time = buf;
    }

    return 0;
  }

  bool parse(const string& s) {
    uint64_t epoch, nsec;
    int r = parse_date(s, &epoch, &nsec);
    if (r < 0) {
      return false;
    }
    *this = utime_t(epoch, nsec);
    return true;
  }
};
WRITE_CLASS_ENCODER(utime_t)
WRITE_CLASS_DENC(utime_t)

// arithmetic operators
inline utime_t operator+(const utime_t& l, const utime_t& r) {
  __u64 sec = (__u64)l.sec() + r.sec();
  return utime_t(cap_to_u32_max(sec), l.nsec() + r.nsec());
}
inline utime_t& operator+=(utime_t& l, const utime_t& r) {
  l.sec_ref() = cap_to_u32_max((__u64)l.sec() + r.sec());
  l.nsec_ref() += r.nsec();
  l.normalize();
  return l;
}
inline utime_t& operator+=(utime_t& l, double f) {
  double fs = trunc(f);
  double ns = (f - fs) * 1000000000.0;
  l.sec_ref() = cap_to_u32_max(l.sec() + (__u64)fs);
  l.nsec_ref() += (long)ns;
  l.normalize();
  return l;
}

inline utime_t operator-(const utime_t& l, const utime_t& r) {
  return utime_t( l.sec() - r.sec() - (l.nsec()<r.nsec() ? 1:0),
                  l.nsec() - r.nsec() + (l.nsec()<r.nsec() ? 1000000000:0) );
}
inline utime_t& operator-=(utime_t& l, const utime_t& r) {
  l.sec_ref() -= r.sec();
  if (l.nsec() >= r.nsec())
    l.nsec_ref() -= r.nsec();
  else {
    l.nsec_ref() += 1000000000L - r.nsec();
    l.sec_ref()--;
  }
  return l;
}
inline utime_t& operator-=(utime_t& l, double f) {
  double fs = trunc(f);
  double ns = (f - fs) * 1000000000.0;
  l.sec_ref() -= (long)fs;
  long nsl = (long)ns;
  if (nsl) {
    l.sec_ref()--;
    l.nsec_ref() = 1000000000L + l.nsec_ref() - nsl;
  }
  l.normalize();
  return l;
}


// comparators
inline bool operator>(const utime_t& a, const utime_t& b)
{
  return (a.sec() > b.sec()) || (a.sec() == b.sec() && a.nsec() > b.nsec());
}
inline bool operator<=(const utime_t& a, const utime_t& b)
{
  return !(operator>(a, b));
}
inline bool operator<(const utime_t& a, const utime_t& b)
{
  return (a.sec() < b.sec()) || (a.sec() == b.sec() && a.nsec() < b.nsec());
}
inline bool operator>=(const utime_t& a, const utime_t& b)
{
  return !(operator<(a, b));
}

inline bool operator==(const utime_t& a, const utime_t& b)
{
  return a.sec() == b.sec() && a.nsec() == b.nsec();
}
inline bool operator!=(const utime_t& a, const utime_t& b)
{
  return a.sec() != b.sec() || a.nsec() != b.nsec();
}


// output

// ostream
inline std::ostream& operator<<(std::ostream& out, const utime_t& t)
{
  return t.localtime(out);
}

inline std::string utimespan_str(const utime_t& age) {
  auto age_ts = ceph::timespan(age.nsec()) + std::chrono::seconds(age.sec());
  return timespan_str(age_ts);
}

#endif