Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
337 lines (275 loc) · 11.3 KB
/
Copy pathmain.py
File metadata and controls
337 lines (275 loc) · 11.3 KB
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
"""Packagist Tracker - Monitor PHP package versions and notify via Slack."""
import logging
import os
import re
import sys
from typing import Any
import requests
import yaml
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
def resolve_log_level(value: str | None) -> int:
"""Resolve a LOG_LEVEL environment value to a logging level number.
Falls back to logging.INFO (with the caller responsible for warning) if
the value is missing or does not match a known logging level name.
"""
name = (value or "INFO").strip().upper()
return logging.getLevelNamesMapping().get(name, logging.INFO)
_raw_log_level = os.getenv("LOG_LEVEL", "INFO")
_resolved_log_level = resolve_log_level(_raw_log_level)
# Logging configuration
logging.basicConfig(
level=_resolved_log_level,
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[logging.StreamHandler(sys.stdout)],
)
logger = logging.getLogger(__name__)
if _resolved_log_level == logging.INFO and _raw_log_level.strip().upper() != "INFO":
logger.warning(
"Invalid LOG_LEVEL '%s'; falling back to INFO.",
_raw_log_level,
)
# Packagist API base URL
PACKAGIST_API_URL = "https://repo.packagist.org/p2/{}.json"
# Matches standard Composer pre-release suffixes: -alpha, -beta, -rc, -dev
# (optionally followed by a number) and their shorthand forms -a1, -b2.
_PRERELEASE_SUFFIX_RE = re.compile(
r"-(?:alpha|beta|rc|dev)(?:[.\-]?\d+)?$|-(?:a|b)\d+$",
re.IGNORECASE,
)
def is_prerelease(version: str) -> bool:
"""Return True if a Composer version string denotes a pre-release.
Recognizes the standard Composer pre-release suffixes (``-alpha``,
``-beta``, ``-rc``, ``-dev``, and their shorthand forms such as
``-a1``/``-b2``/``-RC1``, all case-insensitive) as well as the
``dev-`` branch-alias prefix (e.g. ``dev-master``).
"""
if version.lower().startswith("dev-"):
return True
return bool(_PRERELEASE_SUFFIX_RE.search(version))
def _build_session() -> requests.Session:
"""Create a requests Session with retries for transient network failures.
The retry policy only covers idempotent methods (GET/HEAD). POST is
intentionally excluded: if Slack's ``chat.postMessage`` processes a
message but the response is lost (e.g. a 500 or a response timeout), an
automatic retry would resend the same message, and the Slack API is not
idempotent, so the notification would be posted twice. Since this
session is shared between the Packagist (GET) and Slack (POST) calls,
excluding POST from ``allowed_methods`` leaves Packagist's GET requests
retried as before while Slack's POST requests are attempted exactly
once and any failure is surfaced to the caller instead of being retried
transparently.
"""
session = requests.Session()
retry = Retry(
total=3,
backoff_factor=0.5,
status_forcelist=(429, 500, 502, 503, 504),
allowed_methods=frozenset({"GET", "HEAD"}),
raise_on_status=False,
)
adapter = HTTPAdapter(max_retries=retry)
session.mount("https://", adapter)
session.mount("http://", adapter)
return session
# Shared HTTP session with retry/backoff for Packagist (GET) requests; Slack
# (POST) requests use the same session but are not auto-retried, since
# chat.postMessage is not idempotent. See _build_session() for details.
SESSION = _build_session()
# Directory to store package versions
VERSION_DIR = os.getenv("VERSION_DIR", "versions")
# File touched at the end of every completed check cycle. The Docker Compose
# healthcheck uses this file's mtime to detect a wedged process, since the
# entrypoint's outer shell loop keeps the container itself running even if
# main.py were to hang (see docker-compose.yml).
HEARTBEAT_FILE = os.getenv("HEARTBEAT_FILE", "/tmp/last_run")
# Slack credentials
SLACK_TOKEN = os.getenv("SLACK_TOKEN")
SLACK_CHANNEL = os.getenv("SLACK_CHANNEL")
def load_packages(config_path: str = "config.yml") -> list[str]:
"""Load the list of packages to track from a YAML config file."""
if not os.path.exists(config_path):
logger.warning("Config file '%s' not found. No packages to track.", config_path)
return []
with open(config_path) as f:
try:
config = yaml.safe_load(f) or {}
except yaml.YAMLError as e:
logger.error("Failed to parse config file '%s': %s", config_path, e)
return []
if not isinstance(config, dict):
logger.warning(
"Config file '%s' is not a valid mapping. No packages to track.", config_path
)
return []
raw_packages: object = config.get("packages", [])
if not isinstance(raw_packages, list):
logger.error(
"Invalid 'packages' value in '%s': expected a list, got %s. No packages to track.",
config_path,
type(raw_packages).__name__,
)
return []
packages: list[str] = []
for item in raw_packages:
if isinstance(item, str):
packages.append(item)
else:
logger.warning(
"Ignoring invalid package entry in '%s': %r (expected a string, got %s).",
config_path,
item,
type(item).__name__,
)
if not packages:
logger.warning("No packages defined in '%s'.", config_path)
return packages
def get_package_info(package_name: str) -> tuple[str, str]:
"""Fetch the latest stable version and repository URL from Packagist.
The p2 endpoint returns versions in descending order and includes
pre-releases (alpha/beta/RC/dev tags). Pre-releases are skipped so that
a package with a newer pre-release tag doesn't shadow the latest stable
release. If every available version is a pre-release, the first
(newest) one is used instead.
"""
url = PACKAGIST_API_URL.format(package_name)
response = SESSION.get(url, timeout=30)
response.raise_for_status()
data = response.json()
versions = data["packages"][package_name]
package_info = next((v for v in versions if not is_prerelease(v["version"])), None)
if package_info is None:
logger.debug(
"[%s] All available versions are pre-releases; using the latest one.",
package_name,
)
package_info = versions[0]
current_version: str = package_info["version"]
repository_url: str = package_info["source"]["url"]
return current_version, repository_url
def get_last_version(package_name: str) -> str | None:
"""Read the last known version from the local version file."""
version_file = os.path.join(VERSION_DIR, f"{package_name.replace('/', '__')}.txt")
if not os.path.exists(version_file):
return None
with open(version_file) as f:
return f.read().strip()
def save_current_version(package_name: str, version: str) -> None:
"""Save the current version to the local version file atomically."""
os.makedirs(VERSION_DIR, exist_ok=True)
version_file = os.path.join(VERSION_DIR, f"{package_name.replace('/', '__')}.txt")
tmp_file = f"{version_file}.tmp"
with open(tmp_file, "w") as f:
f.write(version)
os.replace(tmp_file, version_file)
def send_slack_message(package_name: str, current_version: str, repository_url: str) -> bool:
"""Send a Slack notification about a new package version. Returns True on success."""
url = "https://slack.com/api/chat.postMessage"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {SLACK_TOKEN}",
}
payload: dict[str, Any] = {
"channel": SLACK_CHANNEL,
"blocks": [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": f":bell: *New version detected for `{package_name}`!*",
},
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": f"The latest version is now *{current_version}*",
},
},
{
"type": "actions",
"elements": [
{
"type": "button",
"text": {
"type": "plain_text",
"text": "View repository",
},
"url": repository_url,
}
],
},
],
}
logger.info("[%s] Sending Slack notification", package_name)
response = SESSION.post(url, headers=headers, json=payload, timeout=30)
response.raise_for_status()
response_data = response.json()
if not response_data.get("ok"):
logger.error("[%s] Slack API error: %s", package_name, response_data.get("error"))
return False
return True
def _touch_heartbeat() -> None:
"""Update HEARTBEAT_FILE's mtime to mark a completed check cycle.
Best-effort only: a failure here must never crash the check loop itself.
"""
try:
with open(HEARTBEAT_FILE, "a"):
os.utime(HEARTBEAT_FILE, None)
except OSError as e:
logger.warning("Could not update heartbeat file '%s': %s", HEARTBEAT_FILE, e)
def check_package_update(package_name: str) -> bool | None:
"""Check a single package for updates.
Returns True if a new version was found and notified, False if no new
version was found, or None if a new version was found but the Slack
notification failed.
"""
current_version, repository_url = get_package_info(package_name)
last_version = get_last_version(package_name)
logger.info(
"[%s] Current version: %s | Last checked: %s",
package_name,
current_version,
last_version or "never",
)
if current_version == last_version:
return False
if not send_slack_message(package_name, current_version, repository_url):
return None
save_current_version(package_name, current_version)
return True
def main() -> None:
"""Main entry point: load packages and check each for updates."""
if not SLACK_TOKEN or not SLACK_CHANNEL:
logger.error("SLACK_TOKEN and SLACK_CHANNEL must be set.")
sys.exit(1)
packages = load_packages()
if not packages:
logger.info("No packages to track. Exiting.")
_touch_heartbeat()
return
logger.info("Checking %d package(s) for updates...", len(packages))
updated = 0
failed = 0
for package in packages:
try:
result = check_package_update(package)
if result:
updated += 1
elif result is None:
failed += 1
logger.error("[%s] Slack notification failed.", package)
except requests.exceptions.RequestException as e:
failed += 1
logger.error("[%s] HTTP error: %s", package, e)
except (KeyError, IndexError) as e:
failed += 1
logger.error("[%s] Error parsing Packagist response: %s", package, e)
logger.info("Done. %d package(s) updated.", updated)
_touch_heartbeat()
# Signal failure to monitoring when every package check failed.
if failed and failed == len(packages):
logger.error("All %d package(s) failed to check.", failed)
sys.exit(1)
if __name__ == "__main__":
main()