summaryrefslogtreecommitdiff
path: root/draw-timestamp-chart.py
blob: c5068e57635ba593ab34deeb3192ec6a4d730a13 (plain)
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
#!/usr/bin/python3

import gspread
import os
import argparse
import json
import time
import sys

colors = {"main":               {"backgroundColor": {"red": 1,   "green": 0,   "blue": 0}},
          "windows":            {"backgroundColor": {"red": 0,   "green": 1,   "blue": 0}},
          "container-host":     {"backgroundColor": {"red": 0,   "green": 0,   "blue": 1}},
          "container-host-A":     {"backgroundColor": {"red": 0.29,   "green": 0.53,   "blue": 0.9}},
          "container-host-B":     {"backgroundColor": {"red": 0.6,   "green": 0,   "blue": 1}},
          "container-host-C":     {"backgroundColor": {"red": 0,   "green": 1,   "blue": 1}},
          "container-host-D":     {"backgroundColor": {"red": 0.85,   "green": 0.82,   "blue": 0.91}},
          "freebsd":            {"backgroundColor": {"red": 0.8,   "green": 0.25,   "blue": 0.15}},
          "dockerfile-builder": {"backgroundColor": {"red": 0.27, "green": 0.5, "blue": 0.55}}}

inner_colors = {"main":               {"backgroundColor": {"red": 0.63, "green": 0.77,  "blue": 0.79}},
                "windows":            {"backgroundColor": {"red": 1, "green": 0.6,   "blue": 0}},
                "container-host":     {"backgroundColor": {"red": 1, "green": 0,  "blue": 1}},
                "container-host-A":     {"backgroundColor": {"red": 1, "green": 0,  "blue": 1}},
                "container-host-B":     {"backgroundColor": {"red": 1, "green": 0,  "blue": 1}},
                "container-host-C":     {"backgroundColor": {"red": 1, "green": 0,  "blue": 1}},
                "container-host-D":     {"backgroundColor": {"red": 1, "green": 0,  "blue": 1}},
                "freebsd":            {"backgroundColor": {"red": 0, "green": 1,  "blue": 1}},
                "dockerfile-builder": {"backgroundColor": {"red": 0.27, "green": 0.5, "blue": 0.55}}}

subtask_mapping = {"windows": "Windows",
                   "container-host": "Linux",
                   "freebsd": "FreeBSD"}

min_block = 3 # Minute per block
ms_block  = (min_block * 60 * 1000) # milli second per block
task_rows = []
row_formats = []

def create_worksheet(spreadsheet, job_name):
    # Add a new worksheet
    try:
        worksheet = spreadsheet.add_worksheet(job_name, 190, 500)
    except:
        print(f"worksheet {job_name} is already exist")
        sys.exit(1)
    worksheet.freeze(rows=1, cols=1)
    # Resize column size to 10 pixel
    requests = [
        {
            'updateDimensionProperties':{
                'range': {
                    'sheetId': worksheet.id,
                    'dimension': 'COLUMNS',
                    'startIndex': 1,
                    'endIndex': 500
                },
                'properties': {
                    'pixelSize': 5
                },
                'fields': 'pixelSize'
            }
        },
        {
            'updateDimensionProperties': {
                'range': {
                    'sheetId': worksheet.id,
                    'dimension': 'COLUMNS',
                    'startIndex': 0,
                    'endIndex': 1
                },
                'properties': {
                    'pixelSize': 250
                },
                'fields': 'pixelSize'
            }
        },
        {
            "repeatCell": {
                "range": {
                    "sheetId": worksheet.id,
                    "startRowIndex": 0,
                    "endRowIndex": 190,
                    "startColumnIndex": 0,
                    "endColumnIndex": 190
                },
                "cell": {
                    "userEnteredFormat": {
                        "textFormat": {
                            "fontSize": 7
                        }
                    }
                },
                "fields": "userEnteredFormat(textFormat(fontSize))"
            }
        }
    ]
    
    # Send the request to update column width
    body = {
        'requests': requests
    }
    spreadsheet.batch_update(body)
    return worksheet

def num_to_a1(number):
    result = ''
    while number > 0:
        number -= 1 # Start from 1
        remainder = number % 26
        result = chr(65 + remainder) + result
        number //= 26

    return result

def get_a1_notation_range(row, start_column, num_columns):
    start_letter = num_to_a1(start_column)
    if (num_columns == 0):
        end_letter = start_letter
    else:
        end_letter   = num_to_a1(start_column + num_columns - 1)

    return f"{start_letter}{row}:{end_letter}{row}"

def ms_to_hr_min(millisecond):
    sec = millisecond // 1000
    hr = sec // (60 * 60)
    min = round((sec % (60 * 60)) / 60)
    if (min == 60):
        hr += 1
        min = 0
    return f"{hr} hr {min} min"

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Mbed TLS job timestemp chart maker')
    parser.add_argument("-i", "--google-service-account-credential", required = True, help="Google service account credential file")
    parser.add_argument("-s", "--google-spreadsheet", required = False, default = "MbedTLS time charts", help="Google shreadsheet name")
    parser.add_argument("-f", "--timestamp-file", required = True, help="Job timestamp file")

    # Load google service account credential
    credential = parser.parse_args().google_service_account_credential
    sheet = parser.parse_args().google_spreadsheet
    print(f"Open spreadsheet \"{sheet}\"")
    gs = gspread.service_account(filename = credential)
    spreadsheet = gs.open(sheet)

    # Load timestamp file
    tf = parser.parse_args().timestamp_file
    with open(tf, "r") as f:
        json_string = f.read()
    td = json.loads(json_string)
    #job_name = f'{td["job"]}-{td["build"]}'
    job_name = f'{td["build"]}'
    worksheet = create_worksheet(spreadsheet, job_name)

    # Draw main task
    main_task = list(td["main"].keys())[0]
    main_start_timestamp = td["main"][main_task]["start"]
    end_timestamp = td["main"][main_task]["end"]
    duration = end_timestamp - main_start_timestamp
    new_row = [f"{main_task}\n(Total: {ms_to_hr_min(duration)}"]
    updated_row = worksheet.append_row(new_row)
    num_blk = round(duration / ms_block)
    start_blk = 2
    a1_notation = get_a1_notation_range(1, start_blk, num_blk)
    worksheet.format(a1_notation, colors["main"])
    # Subtasks
    subtasks = td["subtasks"]
    row_num = 2
    keys = [["start", "end", colors], ["innerStart", "innerEnd", inner_colors]]
    st_duration = {}
    for i in subtasks:
        subtask = subtasks[i]
        # Sort the tests
        tests = {k: subtask[k] for k in sorted(subtask)}
        s_start = end_timestamp
        s_end = main_start_timestamp
        for t in tests:
            test = tests[t]
            s_start = test["start"] if test["start"] < s_start else s_start
            s_end = test["end"] if test["end"] > s_end else s_end
            duration = test["end"] - test["start"]
            inner_duration = test["innerEnd"] - test["innerStart"]
            nr = [f"{t}\n(Total: {ms_to_hr_min(duration)} / Test: {ms_to_hr_min(inner_duration)})"]
            task_rows.append(nr)

            for k in keys:
                start, end, color = k
                if (test[start] != -1):
                    first_blk = start_blk + round((test[start] - main_start_timestamp)/ms_block)
                    num_blk = round((test[end] - test[start]) / ms_block)
                    a1_notation = get_a1_notation_range(row_num, first_blk, num_blk)
                    row_format = {"range": a1_notation, "format": color[i]}
                    row_formats.append(row_format)

            row_num += 1
        st_duration[i] = {"start": s_start, "end": s_end, "duration": ms_to_hr_min(s_end - s_start)}
    print(st_duration)
    main_str = worksheet.get("A1")[0][0]
    for i in st_duration:
        if i in subtask_mapping:
            main_str += f" / {subtask_mapping[i]}: {st_duration[i]['duration']}"
    main_str += ')'
    print(main_str)
    worksheet.update_cell(1, 1, main_str)
    worksheet.append_rows(task_rows)
    worksheet.batch_format(row_formats)