Skip to content

Instantly share code, notes, and snippets.

@JanKoppe
Last active April 15, 2020 12:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JanKoppe/96dc92564f223e86e21e28a66523518b to your computer and use it in GitHub Desktop.
Save JanKoppe/96dc92564f223e86e21e28a66523518b to your computer and use it in GitHub Desktop.
ugly POC to get billable seconds per project for a gitlab runner from the api
import gitlab
from datetime import datetime, timedelta
import dateutil.parser
import pytz
import pprint
import os
BILLING_PERIOD_DAYS=7
pp = pprint.PrettyPrinter(indent=2)
billable_seconds = {}
utc = pytz.UTC
cutoff_day = utc.localize(datetime.today() - timedelta(days=BILLING_PERIOD_DAYS))
gl = gitlab.Gitlab('https://your.gitlab.instance', private_token=os.getenv('GITLAB_TOKEN'))
runner = gl.runners.get(13)
jobs = runner.jobs.list(sort='desc', order_by='id', as_list=False)
for job in jobs:
created_day = dateutil.parser.parse(job.created_at)
if created_day < cutoff_day:
break
if not type(job.duration) == float:
print("[!!] found job %d with invalid duration for project %d, not reflected in total." % (job.id, job.project.get('id')))
continue
billable_seconds[job.project.get('id')] = billable_seconds.get(job.project.get('id'), 0.0) + job.duration
total_billable_seconds = 0.0
for project in billable_seconds:
total_billable_seconds += billable_seconds[project]
print('[==] total billable seconds across all projects: %d' % total_billable_seconds)
print("[==] billable seconds for the past %d days per project_id:" % BILLING_PERIOD_DAYS)
for project in billable_seconds:
percentage = 100 * (billable_seconds[project] / total_billable_seconds)
print('%d;%.2fs;%.2f%%' % (project, billable_seconds[project], percentage))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment