about summary refs log tree commit diff
path: root/src/cli/slocalc.py
blob: bc4def8239b9b7806974bad94f9943ce50b5c120 (plain) (blame)
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
#!/usr/bin/env python3
"""
A simple SLO calculator for the command line.

$ slocalc.py 99.99
daily:     0 days, 0 hours, 0 minutes, 8 seconds
weekly:    0 days, 0 hours, 1 minutes, 0 seconds
monthly:   0 days, 0 hours, 4 minutes, 19 seconds
quarterly: 0 days, 0 hours, 12 minutes, 57 seconds
yearly:    0 days, 0 hours, 52 minutes, 33 seconds
"""

import sys
from typing import Optional
from datetime import timedelta

seconds_in_hour = 60 * 60


def convert_to_float(s: str) -> Optional[float]:
    try:
        return float(s)
    except ValueError:
        print(f"error: '{s}' cannot be converted to float")
        return None


def seconds_to_human_readable(seconds: int) -> str:
    delta = timedelta(seconds=seconds)
    days = delta.days
    hours, remainder = divmod(delta.seconds, 3600)
    minutes, seconds = divmod(remainder, 60)
    return f"{days} days, {hours} hours, {minutes} minutes, {seconds} seconds"


def cli():
    if len(sys.argv) <= 1:
        print("you need at least one argument", file=sys.stderr)
        sys.exit(1)

    uptime = convert_to_float(sys.argv[1])
    if uptime is None:
        print("failed to read input")
        sys.exit(1)

    if uptime <= 0:
        uptime = 0
    if uptime >= 100:
        uptime = 100

    allowed_downtime = ((100 * 100) - (uptime * 100)) / (100 * 100)

    daily_seconds = seconds_in_hour * 24 * allowed_downtime
    week_seconds = daily_seconds * 7
    month_seconds = daily_seconds * 30
    quarter_seconds = daily_seconds * 90
    year_seconds = daily_seconds * 365

    print("daily:     {0}".format(seconds_to_human_readable(daily_seconds)))
    print("weekly:    {0}".format(seconds_to_human_readable(week_seconds)))
    print("monthly:   {0}".format(seconds_to_human_readable(month_seconds)))
    print("quarterly: {0}".format(seconds_to_human_readable(quarter_seconds)))
    print("yearly:    {0}".format(seconds_to_human_readable(year_seconds)))


if __name__ == "__main__":
    cli()