check-services.py 12 KB

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