-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclockratchet.py
executable file
·143 lines (106 loc) · 4.35 KB
/
clockratchet.py
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
#!/usr/bin/python3
# Needed for running subprocesses
import os
import subprocess
import argparse
# File containing the ratchet state.
ratchetFileDefault="~/.clockratchet"
# Uptime file.
uptimeFileName = "/proc/uptime"
def arguments():
parser = argparse.ArgumentParser(
description="Return monotonically increasing time related information for use in identifiers")
parser.add_argument(
'--ratchet',
action='store_true',
help='Increment the ratchet value, and produce no output. This is intended for use on boot')
parser.add_argument(
'--file',
dest='ratchetFile',
default=ratchetFileDefault,
help='Indicate the file to store the ratchet data in. Default value is: %s' % (ratchetFileDefault))
parser.add_argument(
'--label',
dest='label',
default=None,
help='Add a label string to be included in the output to disambiguate if needed')
return parser.parse_args()
def getRelTime():
# Get years, weeks, days, hours, minutes, seconds since boot.
# Extract number of seconds since boot from /proc/uptime
uptimeFile = open(uptimeFileName,"r")
uptimeData = uptimeFile.read()
(secs, trash) = uptimeData.split(' ')
# Separate number of seconds of uptime into time units using the uptime format:
# Uptime format (reverse of below): seconds, minutes, hours, days, weeks, years.
uptimeParsing = [60, 60, 24, 7, 52]
curr = int(float(secs))
values = []
for increment in uptimeParsing:
values.append(curr % increment)
next = curr // increment
curr = next
values.append(curr)
values.reverse()
# Format value text into years, weeks, days,
valueText="-".join(["%02d" % val for val in values])
return valueText
def getNTPSyncTime():
# Get current time if NTPSynchronized, or return false otherwise.
timeDateOutput = subprocess.check_output(['/usr/bin/timedatectl','show'])
timeDateValues=timeDateOutput.split(b'\n')
# print(timeDateValues)
if b'NTPSynchronized=yes' in timeDateValues:
for value in timeDateValues:
if value.startswith(b'TimeUSec'):
(trash, dateTime) = value.decode('utf-8').split('=')
(trash, date, time, tz) = dateTime.split(" ")
time.replace(":"," ")
return "_".join([date, time, tz])
# Time not synchronized or unable to interpret time.
return False
def getRatchet(ratchetFileName=None):
# Get the current value of the ratchet/counter, default to zero (0)
if ratchetFileName is None:
ratchetFile = open(ratchetFileDefault,'r')
else:
ratchetFile = open(ratchetFileName,'r')
# retrieve and return current ratchet value
currentRatchet = int(ratchetFile.read())
return currentRatchet
def ratchet(ratchetFileName=None):
# Increment the locally stored counter (typically boot counter)
try:
oldRatchetValue = getRatchet(ratchetFileName)
except FileNotFoundError:
oldRatchetValue=0
newRatchetValue = oldRatchetValue+1
ratchetFile = open(ratchetFileName,'w')
ratchetFile.write(str(newRatchetValue))
if __name__ == "__main__":
args = arguments()
if args.ratchet:
try:
ratchet(args.ratchetFile)
except ValueError:
print("The ratchet file may have been corrupted. Please review the file and recover or remove it.")
exit(1)
else:
try:
ratchetValue=getRatchet(args.ratchetFile)
except FileNotFoundError:
print("The ratchet file may not have been created yet. Please ensure the file has been created using the --ratchet argument to this command")
exit(1)
except ValueError:
print("The ratchet file may have been corrupted. Please review the file and recover or remove it.")
exit(1)
if args.label is not None:
ratchetText="%s--%s" % (args.label, ratchetValue)
else:
ratchetText=ratchetValue
relTimeValue=getRelTime()
timeSyncValue=getNTPSyncTime()
if timeSyncValue != False:
print("%s+%s--%s" % (ratchetText, relTimeValue, timeSyncValue))
else:
print("%s+%s" % (ratchetValue, relTimeValue))