check-services.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. import json
  2. import socket
  3. import ssl
  4. import os
  5. import time
  6. import requests
  7. import sys
  8. import zipfile
  9. from io import BytesIO
  10. from random import randbytes
  11. from urllib.parse import urlparse
  12. from collections import defaultdict
  13. MINIMUM_PURGE_AGE = 9.75 * 24 * 60 * 60 # slightly less than 10 days
  14. TIMEOUT = 10
  15. SKIPPED_SERVICES = {'YouNow', 'SHOWROOM', 'Dacast'}
  16. SERVICES_FILE = 'plugins/rtmp-services/data/services.json'
  17. PACKAGE_FILE = 'plugins/rtmp-services/data/package.json'
  18. CACHE_FILE = 'other/timestamps.json'
  19. GITHUB_OUTPUT_FILE = os.environ.get('GITHUB_OUTPUT', None)
  20. DO_NOT_PING = {'jp9000'}
  21. PR_MESSAGE = '''This is an automatically created pull request to remove unresponsive servers and services.
  22. | Service | Action Taken | Author(s) |
  23. | ------- | ------------ | --------- |
  24. {table}
  25. If you are not responsible for an affected service and want to be excluded from future pings please let us know.
  26. Created by workflow run: https://github.com/{repository}/actions/runs/{run_id}'''
  27. # GQL is great isn't it
  28. GQL_QUERY = '''{
  29. repositoryOwner(login: "obsproject") {
  30. repository(name: "obs-studio") {
  31. object(expression: "master") {
  32. ... on Commit {
  33. blame(path: "plugins/rtmp-services/data/services.json") {
  34. ranges {
  35. startingLine
  36. endingLine
  37. commit {
  38. author {
  39. user {
  40. login
  41. }
  42. }
  43. }
  44. }
  45. }
  46. }
  47. }
  48. }
  49. }
  50. }'''
  51. context = ssl.create_default_context()
  52. def check_ftl_server(hostname) -> bool:
  53. """Check if hostname resolves to a valid address - FTL handshake not implemented"""
  54. try:
  55. socket.getaddrinfo(hostname, 8084, proto=socket.IPPROTO_UDP)
  56. except socket.gaierror as e:
  57. print(f'⚠️ Could not resolve hostname for server: {hostname} (Exception: {e})')
  58. return False
  59. else:
  60. return True
  61. def check_hls_server(uri) -> bool:
  62. """Check if URL responds with status code < 500 and not 404, indicating that at least there's *something* there"""
  63. try:
  64. r = requests.post(uri, timeout=TIMEOUT)
  65. if r.status_code >= 500 or r.status_code == 404:
  66. raise Exception(f'Server responded with {r.status_code}')
  67. except Exception as e:
  68. print(f'⚠️ Could not connect to HLS server: {uri} (Exception: {e})')
  69. return False
  70. else:
  71. return True
  72. def check_rtmp_server(uri) -> bool:
  73. """Try connecting and sending a RTMP handshake (with SSL if necessary)"""
  74. parsed = urlparse(uri)
  75. hostname, port = parsed.netloc.partition(':')[::2]
  76. port = int(port) if port else 1935
  77. try:
  78. recv = b''
  79. with socket.create_connection((hostname, port), timeout=TIMEOUT) as sock:
  80. # RTMP handshake is \x03 + 4 bytes time (can be 0) + 4 zero bytes + 1528 bytes random
  81. handshake = b'\x03\x00\x00\x00\x00\x00\x00\x00\x00' + randbytes(1528)
  82. if parsed.scheme == 'rtmps':
  83. with context.wrap_socket(sock, server_hostname=hostname) as ssock:
  84. ssock.sendall(handshake)
  85. while True:
  86. _tmp = ssock.recv(4096)
  87. recv += _tmp
  88. if len(recv) >= 1536 or not _tmp:
  89. break
  90. else:
  91. sock.sendall(handshake)
  92. while True:
  93. _tmp = sock.recv(4096)
  94. recv += _tmp
  95. if len(recv) >= 1536 or not _tmp:
  96. break
  97. if len(recv) < 1536 or recv[0] != 3:
  98. raise ValueError('Invalid RTMP handshake received from server')
  99. except Exception as e:
  100. print(f'⚠️ Connection to server failed: {uri} (Exception: {e})')
  101. return False
  102. else:
  103. return True
  104. def get_last_artifact():
  105. s = requests.session()
  106. s.headers['Authorization'] = f'Bearer {os.environ["GITHUB_TOKEN"]}'
  107. run_id = os.environ['WORKFLOW_RUN_ID']
  108. repo = os.environ['REPOSITORY']
  109. # fetch run first, get workflow id from there to get workflow runs
  110. r = s.get(f'https://api.github.com/repos/{repo}/actions/runs/{run_id}')
  111. r.raise_for_status()
  112. workflow_id = r.json()['workflow_id']
  113. r = s.get(
  114. f'https://api.github.com/repos/{repo}/actions/workflows/{workflow_id}/runs',
  115. params=dict(per_page=1, status='completed', branch='master', conclusion='success', event='schedule'),
  116. )
  117. r.raise_for_status()
  118. runs = r.json()
  119. if not runs['workflow_runs']:
  120. raise ValueError('No completed workflow runs found')
  121. r = s.get(runs['workflow_runs'][0]['artifacts_url'])
  122. r.raise_for_status()
  123. for artifact in r.json()['artifacts']:
  124. if artifact['name'] == 'timestamps':
  125. artifact_url = artifact['archive_download_url']
  126. break
  127. else:
  128. raise ValueError('No previous artifact found.')
  129. r = s.get(artifact_url)
  130. r.raise_for_status()
  131. zip_data = BytesIO()
  132. zip_data.write(r.content)
  133. with zipfile.ZipFile(zip_data) as zip_ref:
  134. for info in zip_ref.infolist():
  135. if info.filename == 'timestamps.json':
  136. return json.loads(zip_ref.read(info.filename))
  137. def find_people_to_blame(raw_services: str, servers: list[tuple[str, str]]) -> dict:
  138. if not servers:
  139. return dict()
  140. # Fetch Blame data from github
  141. s = requests.session()
  142. s.headers['Authorization'] = f'Bearer {os.environ["GITHUB_TOKEN"]}'
  143. r = s.post('https://api.github.com/graphql', json=dict(query=GQL_QUERY, variables=dict()))
  144. r.raise_for_status()
  145. j = r.json()
  146. # The file is only ~2600 lines so this isn't too crazy and makes the lookup very easy
  147. line_author = dict()
  148. for blame in j['data']['repositoryOwner']['repository']['object']['blame']['ranges']:
  149. for i in range(blame['startingLine'] - 1, blame['endingLine']):
  150. if user := blame['commit']['author']['user']:
  151. line_author[i] = user['login']
  152. service_authors = defaultdict(set)
  153. for i, line in enumerate(raw_services.splitlines()):
  154. if '"url":' not in line:
  155. continue
  156. for server, service in servers:
  157. if server in line and (author := line_author.get(i)):
  158. if author not in DO_NOT_PING:
  159. service_authors[service].add(author)
  160. return service_authors
  161. def set_output(name, value):
  162. if not GITHUB_OUTPUT_FILE:
  163. return
  164. try:
  165. with open(GITHUB_OUTPUT_FILE, 'a', encoding='utf-8', newline='\n') as f:
  166. f.write(f'{name}={value}\n')
  167. except Exception as e:
  168. print(f'Writing to github output files failed: {e!r}')
  169. def main():
  170. try:
  171. with open(SERVICES_FILE, encoding='utf-8') as services_file:
  172. raw_services = services_file.read()
  173. services = json.loads(raw_services)
  174. with open(PACKAGE_FILE, encoding='utf-8') as package_file:
  175. package = json.load(package_file)
  176. except OSError as e:
  177. print(f'❌ Could not open services/package file: {e}')
  178. return 1
  179. # attempt to load last check result cache
  180. try:
  181. with open(CACHE_FILE, encoding='utf-8') as check_file:
  182. fail_timestamps = json.load(check_file)
  183. except OSError as e:
  184. # cache might be evicted or not exist yet, so this is non-fatal
  185. print(f'⚠️ Could not read cache file, trying to get last artifact (Exception: {e})')
  186. try:
  187. fail_timestamps = get_last_artifact()
  188. except Exception as e:
  189. print(f'⚠️ Could not fetch cache file, starting fresh. (Exception: {e})')
  190. fail_timestamps = dict()
  191. else:
  192. print('Fetched cache file from last run artifact.')
  193. else:
  194. print('Successfully loaded cache file:', CACHE_FILE)
  195. start_time = int(time.time())
  196. affected_services = dict()
  197. removed_servers = list()
  198. # create temporary new list
  199. new_services = services.copy()
  200. new_services['services'] = []
  201. for service in services['services']:
  202. # skip services that do custom stuff that we can't easily check
  203. if service['name'] in SKIPPED_SERVICES:
  204. new_services['services'].append(service)
  205. continue
  206. service_type = service.get('recommended', {}).get('output', 'rtmp_output')
  207. if service_type not in {'rtmp_output', 'ffmpeg_hls_muxer', 'ftl_output'}:
  208. print('Unknown service type:', service_type)
  209. new_services['services'].append(service)
  210. continue
  211. # create a copy to mess with
  212. new_service = service.copy()
  213. new_service['servers'] = []
  214. # run checks for all the servers, and store results in timestamp cache
  215. for server in service['servers']:
  216. if service_type == 'ftl_output':
  217. is_ok = check_ftl_server(server['url'])
  218. elif service_type == 'ffmpeg_hls_muxer':
  219. is_ok = check_hls_server(server['url'])
  220. else: # rtmp
  221. is_ok = check_rtmp_server(server['url'])
  222. if not is_ok:
  223. if ts := fail_timestamps.get(server['url'], None):
  224. if (delta := start_time - ts) >= MINIMUM_PURGE_AGE:
  225. print(
  226. f'🗑️ Purging server "{server["url"]}", it has been '
  227. f'unresponsive for {round(delta/60/60/24)} days.'
  228. )
  229. removed_servers.append((server['url'], service['name']))
  230. # continuing here means not adding it to the new list, thus dropping it
  231. continue
  232. else:
  233. fail_timestamps[server['url']] = start_time
  234. elif is_ok and server['url'] in fail_timestamps:
  235. # remove timestamp of failed check if server is back
  236. delta = start_time - fail_timestamps[server['url']]
  237. print(f'💡 Server "{server["url"]}" is back after {round(delta/60/60/24)} days!')
  238. del fail_timestamps[server['url']]
  239. new_service['servers'].append(server)
  240. if (diff := len(service['servers']) - len(new_service['servers'])) > 0:
  241. print(f'ℹ️ Removed {diff} server(s) from {service["name"]}')
  242. affected_services[service['name']] = f'{diff} servers removed'
  243. # remove services with no valid servers
  244. if not new_service['servers']:
  245. print(f'💀 Service "{service["name"]}" has no valid servers left, removing!')
  246. affected_services[service['name']] = f'Service removed'
  247. continue
  248. new_services['services'].append(new_service)
  249. # write cache file
  250. try:
  251. os.makedirs('other', exist_ok=True)
  252. with open(CACHE_FILE, 'w', encoding='utf-8') as cache_file:
  253. json.dump(fail_timestamps, cache_file)
  254. except OSError as e:
  255. print(f'❌ Could not write cache file: {e}')
  256. return 1
  257. else:
  258. print('Successfully wrote cache file:', CACHE_FILE)
  259. if removed_servers:
  260. # increment package version and save that as well
  261. package['version'] += 1
  262. package['files'][0]['version'] += 1
  263. try:
  264. with open(SERVICES_FILE, 'w', encoding='utf-8') as services_file:
  265. json.dump(new_services, services_file, indent=4, ensure_ascii=False)
  266. services_file.write('\n')
  267. with open(PACKAGE_FILE, 'w', encoding='utf-8') as package_file:
  268. json.dump(package, package_file, indent=4)
  269. package_file.write('\n')
  270. except OSError as e:
  271. print(f'❌ Could not write services/package file: {e}')
  272. return 1
  273. else:
  274. print(f'Successfully wrote services/package files:\n- {SERVICES_FILE}\n- {PACKAGE_FILE}')
  275. # try to find authors to ping, this is optional and is allowed to fail
  276. try:
  277. service_authors = find_people_to_blame(raw_services, removed_servers)
  278. except Exception as e:
  279. print(f'⚠ Could not fetch blame for some reason: {e}')
  280. service_authors = dict()
  281. # set GitHub outputs
  282. set_output('make_pr', 'true')
  283. msg = PR_MESSAGE.format(
  284. repository=os.environ['REPOSITORY'],
  285. run_id=os.environ['WORKFLOW_RUN_ID'],
  286. table='\n'.join(
  287. '| {name} | {action} | {authors} |'.format(
  288. name=name.replace('|', '\\|'),
  289. action=action,
  290. authors=', '.join(f'@{author}' for author in sorted(service_authors.get(name, []))),
  291. )
  292. for name, action in sorted(affected_services.items())
  293. ),
  294. )
  295. set_output('pr_message', json.dumps(msg))
  296. else:
  297. set_output('make_pr', 'false')
  298. if __name__ == '__main__':
  299. sys.exit(main())