Debian Codegraph @

installation-birthday

raw
1 #!/usr/bin/env python3
2
3 """
4 installation-birthday
5 Receive congratulations on system installation anniversary.
6
7 Copyright © 2017-2020 Chris Lamb <[email protected]>
8
9 This program is free software: you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation, either version 3 of the License, or
12 (at your option) any later version.
13
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with this program. If not, see <http://www.gnu.org/licenses/>.
21 """
22
23 import os
24 import sys
25 import logging
26 import argparse
27 import datetime
28 import distro
29 import socket
30 import subprocess
31
32 DESCRIPTION = "Receive congratulations on system installation anniversaries."
33
34 TEMPLATE = r"""
35 0 0
36 | |
37 ____|___|____
38 0 |~ ~ ~ ~ ~ ~| 0
39 | | | |
40 ___|__|___________|___|__
41 |/\/\/\/\/\/\/\/\/\/\/\/|
42 0 | H a p p y | 0
43 | |/\/\/\/\/\/\/\/\/\/\/\/| |
44 _|___|_______________________|___|__
45 |/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/|
46 | |
47 | B i r t h d a y ! ! ! |
48 | ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ |
49 |___________________________________|
50
51
52 Congratulations, your {distname} system "{node}" was installed
53 {age} year(s) ago today!
54
55
56 Best wishes,
57
58 Your local system administrator
59 """
60
61
62 class Birthday:
63 def main(self):
64 self.args = self.parse_arguments()
65 self.setup_logging()
66
67 now = datetime.datetime.now(datetime.UTC)
68 install = self.get_installation_datetime()
69
70 if install is None:
71 self.log.debug("Could not determine installation date")
72 return 1
73
74 if self.args.puppet:
75 print("installation_date={}".format(install.date()))
76 return 0 # Don't do anything else
77
78 self.log.debug("Today's date: %s", now.date())
79 self.log.info("Installation date: %s", install.date())
80
81 age = now.year - install.year
82
83 if not self.args.force:
84 if age == 0:
85 self.log.debug("Not reporting for today's year")
86 return 0
87
88 if (install.month, install.day) != (now.month, now.day):
89 self.log.debug("Dates do not match")
90 return 0
91
92 print(
93 TEMPLATE.format(
94 age=age,
95 node=socket.gethostname(),
96 distname=distro.id().title(),
97 )
98 )
99
100 return 0
101
102 def parse_arguments(self):
103 parser = argparse.ArgumentParser(description=DESCRIPTION)
104
105 parser.add_argument(
106 "--verbosity",
107 dest="verbosity",
108 type=int,
109 default=1,
110 choices=(0, 1, 2),
111 help="set log level",
112 )
113
114 parser.add_argument(
115 "-p",
116 "--puppet",
117 dest="puppet",
118 action="store_true",
119 default=False,
120 help="output result in Puppet 'fact' format",
121 )
122
123 parser.add_argument(
124 "--force",
125 dest="force",
126 action="store_true",
127 default=False,
128 help="celebrate regardless of today's date",
129 )
130
131 return parser.parse_args()
132
133 def setup_logging(self):
134 self.log = logging.getLogger()
135
136 self.log.setLevel(
137 {0: logging.WARNING, 1: logging.INFO, 2: logging.DEBUG}[
138 self.args.verbosity
139 ]
140 )
141
142 handler = logging.StreamHandler(sys.stderr)
143 handler.setFormatter(logging.Formatter("%(levelname).1s: %(message)s"))
144 self.log.addHandler(handler)
145
146 def check_output(self, *args, **kwargs):
147 kwargs.setdefault("stderr", subprocess.DEVNULL)
148 kwargs.setdefault("env", {"TZ": "UTC"})
149
150 output = subprocess.check_output(*args, **kwargs).decode("utf-8")
151
152 return output.splitlines()
153
154 def get_block_device(self, path):
155 self.log.debug("Determining block device for %s", path)
156
157 lines = self.check_output(
158 (
159 "df",
160 "--portability",
161 "--local",
162 "--type=ext2",
163 "--type=ext3",
164 "--type=ext4",
165 path,
166 )
167 )
168
169 return lines[1].split(" ")[0]
170
171 def get_installation_datetime(self):
172 dt = None
173
174 for candidate in self.gen_installation_datetimes():
175 # Use the oldest mtime we can find
176 if dt is None or candidate < dt:
177 self.log.debug("Preferring %s over %s", candidate, dt)
178 dt = candidate
179
180 return dt
181
182 def gen_installation_datetimes(self):
183 try:
184 device = self.get_block_device("/")
185
186 self.log.debug("Determining creation time for %s", device)
187 lines = self.check_output(("/sbin/tune2fs", "-l", device))
188 except (OSError, subprocess.CalledProcessError):
189 pass
190 else:
191 lookup = {}
192 for x in lines:
193 if ":" in x:
194 k, v = x.split(":", 1)
195 lookup[k] = v.strip()
196
197 try:
198 dt = datetime.datetime.strptime(
199 lookup["Filesystem created"].strip(),
200 "%a %b %d %H:%M:%S %Y",
201 ).replace(tzinfo=datetime.UTC)
202 self.log.debug("Found mtime of %s -> %s", device, dt)
203 yield dt
204 except (KeyError, ValueError):
205 self.log.debug("Could not get creation time of %s", device)
206
207 for x in (
208 "/var/log/installer",
209 "/var/log/bootstrap.log",
210 "/var/lib/vim",
211 "/lost+found",
212 "/root",
213 "/etc/machine-id",
214 "/etc/hostname",
215 ):
216
217 try:
218 dt = datetime.datetime.fromtimestamp(os.stat(x).st_mtime, datetime.UTC)
219 self.log.debug("Found mtime of %s -> %s", x, dt)
220 yield dt
221 except Exception:
222 self.log.debug("Failed to get mtime of %s", x)
223
224
225 if __name__ == "__main__":
226 sys.exit(Birthday().main())