Skip to content

Commit f58a4aa

Browse files
authored
Grafana united scripts (#24)
Grafana united scripts Unite code for OTC and Swiss clouds Update README.md Reviewed-by: Vladimir Vshivkov
1 parent a5778be commit f58a4aa

12 files changed

+334
-1275
lines changed

README.md

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,12 @@
1-
# grafana-docs-monitoring
2-
Script gathering HC3.0 docs PRs and issues info from Github and Gitea
1+
grafana-docs-monitoring
2+
=======================
3+
Scripts gathering HC3.0 PRs, issues and docs info from Github and Gitea. Scripts are works both for OTC and Swiss clouds in a one run. Data store in two Postgres databases: **_CSV_** is for a service tables, open PRs, failed Zuul PRs, issues and commits updates, **_ORPH_** is a dedicated DB special for orphan PRs
4+
5+
1) **otc_services_dict.py:** service script gathering metadata for service, its full names, categories and types. Should be run first, since all of the following scripts are relay on it in terms of repo names, service titles and squad names.
6+
2) **gitea_info.py:** this script is using for open & orphan PRs data collecting
7+
3) **github_info.py:** add info regarding child PRs in Github
8+
4) **failed_zuul.py:** collecting info about PRs which checks in Zuul has been failed
9+
5) **open_issues.py:** this script gather info regarding all open issues both from Gitea and Gitnub
10+
6) **last_commit_info.py:** this script gather and calculate date of the last update of a prospective doc for all the services and types of docs (user manual, API reference and so on)
11+
12+
Postgres database names, table names, Gitea & Github organization names and access tokens are store in environment variables.

failed_zuul.py

Lines changed: 42 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,12 @@
1313
gitea_api_endpoint = "https://gitea.eco.tsi-dev.otc-service.com/api/v1"
1414
session = requests.Session()
1515
session.debug = False
16-
org = "docs"
1716
gitea_token = os.getenv("GITEA_TOKEN")
1817
github_token = os.getenv("GITHUB_TOKEN")
1918

2019
db_host = os.getenv("DB_HOST")
2120
db_port = os.getenv("DB_PORT")
22-
db_name = os.getenv("DB_NAME")
21+
db_name = os.getenv("DB_CSV") # here we're using main postgres db since we don't need orphan PRs
2322
db_user = os.getenv("DB_USER")
2423
db_password = os.getenv("DB_PASSWORD")
2524

@@ -34,8 +33,8 @@ def check_env_variables():
3433
raise Exception(f"Missing environment variable: {var}")
3534

3635

37-
def connect_to_db():
38-
print("Connecting to Postgres...")
36+
def connect_to_db(db_name):
37+
print(f"Connecting to Postgres ({db_name})...")
3938
try:
4039
return psycopg2.connect(
4140
host=db_host,
@@ -45,7 +44,7 @@ def connect_to_db():
4544
password=db_password
4645
)
4746
except psycopg2.Error as e:
48-
print(f"Connecting to Postgres: an error occurred while trying to connect to the database: {e}")
47+
print(f"Connecting to Postgres: an error occurred while trying to connect to the database {db_name}: {e}")
4948
return None
5049

5150

@@ -114,21 +113,21 @@ def extract_number_from_body(text):
114113
return None
115114

116115

117-
def get_f_pr_commits(repo, f_pr_number, gitea_token):
116+
def get_f_pr_commits(org, repo, f_pr_number, gitea_token):
118117
try:
119118
zuul_url = None
120119
status = None
121120
created_at = None
122121
days_passed = None
123122

124-
pull_request_resp = session.get(f"{gitea_api_endpoint}/repos/docs/{repo}/pulls/{f_pr_number}/commits?token={gitea_token}")
125-
pull_request_resp.raise_for_status() # Raise an exception if the response contains an HTTP error status.
123+
pull_request_resp = session.get(f"{gitea_api_endpoint}/repos/{org}/{repo}/pulls/{f_pr_number}/commits?token={gitea_token}")
124+
pull_request_resp.raise_for_status()
126125

127126
f_pr_info = json.loads(pull_request_resp.content.decode("utf-8"))
128127

129128
if len(f_pr_info) > 0:
130129
f_commit_sha = f_pr_info[0]["sha"]
131-
commit_status_resp = session.get(f"{gitea_api_endpoint}/repos/docs/{repo}/statuses/{f_commit_sha}?token={gitea_token}")
130+
commit_status_resp = session.get(f"{gitea_api_endpoint}/repos/{org}/{repo}/statuses/{f_commit_sha}?token={gitea_token}")
132131
commit_status_resp.raise_for_status()
133132

134133
commit_info = json.loads(commit_status_resp.content.decode("utf-8"))
@@ -143,10 +142,10 @@ def get_f_pr_commits(repo, f_pr_number, gitea_token):
143142
return zuul_url, status, created_at, days_passed
144143

145144
except requests.exceptions.RequestException as e:
146-
print(f"Get failed PR commits: an error occurred while trying to get pull requests of {repo} repo: {e}")
145+
print(f"Get failed PR commits: an error occurred while trying to get pull requests of {repo} repo for {org} org: {e}")
147146

148147

149-
def get_failed_prs(repo, gitea_token, conn, cur):
148+
def get_failed_prs(org, repo, gitea_token, conn, cur, table_name):
150149
try:
151150
if repo != "doc-exports" and repo != "dsf":
152151
page = 1
@@ -174,47 +173,49 @@ def get_failed_prs(repo, gitea_token, conn, cur):
174173
title = pull_req["title"]
175174
f_pr_url = pull_req["url"]
176175
f_pr_state = pull_req["state"]
177-
zuul_url, status, created_at, days_passed = get_f_pr_commits(repo, f_pr_number, gitea_token)
176+
zuul_url, status, created_at, days_passed = get_f_pr_commits(org, repo, f_pr_number, gitea_token)
178177
try:
179178
if all(item is not None for item in [zuul_url, status, created_at, days_passed]):
180-
cur.execute("""
181-
INSERT INTO public.failed_zuul_prs
179+
cur.execute(f"""
180+
INSERT INTO public.{table_name}
182181
("Service Name", "Failed PR Title", "Failed PR URL", "Squad", "Failed PR State", "Zuul URL", "Zuul Check Status", "Days Passed", "Parent PR Number")
183182
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
184183
""",
185184
(service_name, title, f_pr_url, squad, f_pr_state, zuul_url, status, days_passed, f_par_pr_num)
186185
)
187186
conn.commit()
188187
except Exception as e:
189-
print(f"Failed PRs: an error occurred while inserting into the failed_zuul_prs table: {e}")
188+
print(f"Failed PRs: an error occurred while inserting into {table_name} table: {e}")
190189
else:
191190
continue
191+
elif org == "docs-swiss" and repo_resp.status_code != 200:
192+
break
192193
page += 1
193194

194195
except Exception as e:
195196
print('Failed PRs: an error occurred:', e)
196197

197198

198-
def update_squad_and_title(conn, cur):
199-
print("Updating squads and titles...")
199+
def update_squad_and_title(conn, cur, table_name, rtc):
200+
print(f"Updating squads and titles with {rtc}...")
200201
try:
201-
cur.execute("SELECT * FROM failed_zuul_prs;")
202+
cur.execute(f"SELECT * FROM {table_name};")
202203
failed_prs_rows = cur.fetchall()
203204

204205
for row in failed_prs_rows:
205206
cur.execute(
206-
"""UPDATE failed_zuul_prs
207+
f"""UPDATE {table_name}
207208
SET "Service Name" = rtc."Title", "Squad" = rtc."Category"
208-
FROM repo_title_category AS rtc
209-
WHERE failed_zuul_prs."Service Name" = rtc."Repository"
210-
AND failed_zuul_prs.id = %s;""",
209+
FROM {rtc} AS rtc
210+
WHERE {table_name}."Service Name" = rtc."Repository"
211+
AND {table_name}.id = %s;""",
211212
(row[0],)
212213
)
213214
cur.execute(
214-
"""UPDATE failed_zuul_prs
215+
f"""UPDATE {table_name}
215216
SET "Squad" = 'Other'
216-
WHERE failed_zuul_prs."Service Name" IN ('doc-exports', 'docs_on_docs', 'docsportal')
217-
AND failed_zuul_prs.id = %s;""",
217+
WHERE {table_name}."Service Name" IN ('doc-exports', 'docs_on_docs', 'docsportal')
218+
AND {table_name}.id = %s;""",
218219
(row[0],)
219220
)
220221
conn.commit()
@@ -224,33 +225,40 @@ def update_squad_and_title(conn, cur):
224225
conn.rollback()
225226

226227

227-
def main():
228+
def main(org, table_name, rtc):
228229
check_env_variables()
229230

230-
conn = connect_to_db()
231+
conn = connect_to_db(db_name)
231232
cur = conn.cursor()
232233

233-
cur.execute("DROP TABLE IF EXISTS failed_zuul_prs")
234+
cur.execute(f"DROP TABLE IF EXISTS {table_name}")
234235
conn.commit()
235236

236-
create_prs_table(conn, cur, "failed_zuul_prs")
237+
create_prs_table(conn, cur, table_name)
237238

238239
repos = get_repos(org, gitea_token)
239240

240241
print("Gathering PRs info...")
241242
for repo in repos:
242-
get_failed_prs(repo, gitea_token, conn, cur)
243+
get_failed_prs(org, repo, gitea_token, conn, cur, table_name)
243244

244-
update_squad_and_title(conn, cur)
245+
update_squad_and_title(conn, cur, table_name, rtc)
245246

246247
cur.close()
247248
conn.close()
248249

250+
251+
if __name__ == "__main__":
252+
org_string = "docs"
253+
failed_table = "failed_zuul_prs"
254+
rtc_table = "repo_title_category"
255+
256+
main(org_string, failed_table, rtc_table)
257+
main(f"{org_string}-swiss", f"{failed_table}_swiss", f"{rtc_table}_swiss")
258+
259+
249260
end_time = time.time()
250261
execution_time = end_time - start_time
251262
minutes, seconds = divmod(execution_time, 60)
252263
print(f"Script failed_zuul.py executed in {int(minutes)} minutes {int(seconds)} seconds! Let's go drink some beer :)")
253264

254-
255-
if __name__ == "__main__":
256-
main()

0 commit comments

Comments
 (0)