The little things give you away... A collection of various small helper stuff
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

172 lines
6.8 KiB

  1. #!/usr/bin/env python3
  2. import argparse
  3. import datetime
  4. import json
  5. import re
  6. import sys
  7. import time
  8. import urllib.request
  9. # Column definitions
  10. columns = {
  11. 'jobid': (lambda job, pipelines: job["job_data"]["ident"], ()),
  12. 'url': (lambda job, pipelines: job["job_data"]["url"], ()),
  13. 'user': (lambda job, pipelines: job["job_data"]["started_by"], ()),
  14. 'pipenick': (lambda job, pipelines: pipelines[job["job_data"]["pipeline_id"]] if job["job_data"]["pipeline_id"] in pipelines else "unknown", ()),
  15. 'queued': (lambda job, pipelines: job["job_data"]["queued_at"], ('date',)),
  16. 'started': (lambda job, pipelines: job["job_data"]["started_at"], ('date',)),
  17. 'last active': (lambda job, pipelines: int(job["ts"]), ('date', 'coloured')),
  18. }
  19. defaultSort = 'jobid'
  20. # Parse arguments
  21. class FilterAction(argparse.Action):
  22. def __call__(self, parser, namespace, values, optionString = None):
  23. global columns
  24. match = re.match(r"^(?P<column>[A-Za-z ]+)(?P<op>[=<>^*$~])(?P<value>.*)$", values[0])
  25. if not match:
  26. raise argparse.ArgumentError('Invalid filter')
  27. filterDict = match.groupdict()
  28. filterDict["column"] = filterDict["column"].lower()
  29. assert filterDict["column"] in columns
  30. transform = (lambda x: x.lower() if isinstance(x, str) else x) if optionString in ('--ifilter', '-i') else (lambda x: x)
  31. setattr(namespace, self.dest, (filterDict, transform))
  32. def parse_sort(value):
  33. global columns
  34. sortDesc = value.startswith('-')
  35. if sortDesc:
  36. value = value[1:]
  37. value = value.lower()
  38. if value not in columns:
  39. raise argparse.ArgumentError('Invalid column name')
  40. return (value, sortDesc)
  41. class SortAction(argparse.Action):
  42. def __call__(self, parser, namespace, values, optionString = None):
  43. result = parse_sort(values[0])
  44. if getattr(namespace, self.dest, None) is None:
  45. setattr(namespace, self.dest, [])
  46. getattr(namespace, self.dest).append(result)
  47. parser = argparse.ArgumentParser(formatter_class = argparse.RawTextHelpFormatter)
  48. parser.add_argument('--sort', '-s', nargs = 1, type = str, action = SortAction, help = "Sort the table by a COLUMN (descending if preceded by '-'). This can be used multiple times to refine the sorting.")
  49. parser.add_argument('--filter', '-f', nargs = 1, type = str, action = FilterAction, help = '\n'.join([
  50. 'Filter the table for rows where a COLUMN has a certain VALUE. If specified multiple times, only the last value is used.',
  51. 'FILTER has the format COLUMN{=|<|>|^|*|$|~}VALUE',
  52. ' = means the value must be exactly as specified.',
  53. ' < and > mean it must be less/greater than the specified.',
  54. ' ^ and $ mean it must start/end with the specified.',
  55. ' * means it must contain the specified.',
  56. ' ~ means it must match the specified regex.',
  57. ]))
  58. parser.add_argument('--ifilter', '-i', nargs = 1, type = str, action = FilterAction, dest = 'filter', help = 'Like --filter but case-insensitive')
  59. parser.add_argument('--no-colours', '--no-colors', action = 'store_true', help = "Don't colourise the last activity column if it's been a while.")
  60. parser.add_argument('--no-table', action = 'store_true', help = 'Raw output without feeding through column(1); columns are separated by tabs.')
  61. parser.add_argument('--dates', action = 'store_true', help = 'Print dates instead of elapsed times for queued/started/last active columns.')
  62. args = parser.parse_args()
  63. if not args.sort:
  64. args.sort = [parse_sort(defaultSort)]
  65. # Retrieve
  66. def fetch(url):
  67. req = urllib.request.Request(url)
  68. req.add_header('Accept', 'application/json')
  69. with urllib.request.urlopen(req) as f:
  70. if f.getcode() != 200:
  71. raise RuntimeError('Could not fetch job data')
  72. return json.load(f)
  73. jobdata = fetch('http://dashboard.at.ninjawedding.org/logs/recent?count=1')
  74. pipelinedata = fetch('http://dashboard.at.ninjawedding.org/pipelines')
  75. currentTime = time.time()
  76. # Process
  77. pipelines = {p["id"]: p["nickname"] for p in pipelinedata["pipelines"]}
  78. jobs = []
  79. for job in jobdata:
  80. jobs.append({column: columnFunc(job, pipelines) for column, (columnFunc, _) in columns.items()})
  81. if not jobs:
  82. # Nothing to do
  83. sys.exit(0)
  84. # Filter
  85. if args.filter:
  86. filterDict, transform = args.filter
  87. compFunc = {
  88. "=": lambda a, b: a == b,
  89. "<": lambda a, b: a < b,
  90. ">": lambda a, b: a > b,
  91. "^": lambda a, b: a.startswith(b),
  92. "*": lambda a, b: b in a,
  93. "$": lambda a, b: a.endswith(b),
  94. "~": lambda a, b: re.search(b, a) is not None,
  95. }[filterDict["op"]]
  96. if isinstance(jobs[0][filterDict["column"]], (int, float)):
  97. filterDict["value"] = float(filterDict["value"])
  98. jobs = [job for job in jobs if compFunc(transform(job[filterDict["column"]]), transform(filterDict["value"]))]
  99. if not jobs:
  100. sys.exit(0)
  101. # Sort
  102. class reversor: # https://stackoverflow.com/a/56842689
  103. def __init__(self, obj):
  104. self.obj = obj
  105. def __eq__(self, other):
  106. return other.obj == self.obj
  107. def __lt__(self, other):
  108. return other.obj < self.obj
  109. sortColumns = tuple((column, descending, columns[column]) for column, descending in args.sort)
  110. if not args.dates:
  111. # Reverse sorting order for columns which have a date attribute since the column will have elapsed time
  112. sortColumns = tuple((column, not descending if 'date' in columnInfo[1] else descending, columnInfo) for column, descending, columnInfo in sortColumns)
  113. jobs = sorted(jobs, key = lambda job: tuple(job[column] if not descending else reversor(job[column]) for column, descending, _ in sortColumns))
  114. # Renderers
  115. def render_date(ts, coloured = False):
  116. global args, currentTime
  117. diff = currentTime - ts
  118. colourStr = f"\x1b[{0 if diff < 6 * 3600 else 7};31m" if coloured and diff >= 300 else ""
  119. colourEndStr = "\x1b[0m" if colourStr else ""
  120. if args.dates:
  121. return (colourStr, datetime.datetime.fromtimestamp(ts).isoformat(sep = " "), colourEndStr)
  122. if diff <= 0:
  123. return "now"
  124. elif diff < 60:
  125. return "<1 min ago"
  126. elif diff < 86400:
  127. return (colourStr, (f"{diff // 3600:.0f}h " if diff >= 3600 else "") + f"{(diff % 3600) // 60:.0f}mn ago", colourEndStr)
  128. else:
  129. return (colourStr, f"{diff // 86400:.0f}d {(diff % 86400) // 3600:.0f}h ago", colourEndStr)
  130. renderers = {}
  131. for column, (_, columnAttr) in columns.items():
  132. if "date" in columnAttr:
  133. if "coloured" in columnAttr:
  134. renderers[column] = lambda x: render_date(x, coloured = not args.no_colours)
  135. else:
  136. renderers[column] = render_date
  137. # Print
  138. output = []
  139. output.append(tuple(column.upper() for column in columns))
  140. for job in jobs:
  141. for column in renderers:
  142. job[column] = renderers[column](job[column])
  143. output.append(tuple(job[column] for column in columns))
  144. if not args.no_table:
  145. widths = tuple(max(len(field) if isinstance(field, str) else len(field[1]) for field in column) for column in zip(*output))
  146. for row in output:
  147. print(' '.join((value.ljust(width) if isinstance(value, str) else ''.join((value[0], value[1], value[2], ' ' * (width - len(value[1]))))) for value, width in zip(row, widths)))
  148. else:
  149. for row in output:
  150. print('\t'.join(field if isinstance(field, str) else ''.join(field) for field in row))