-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTriggerDockerBuild.py
More file actions
1490 lines (945 loc) · 56.9 KB
/
TriggerDockerBuild.py
File metadata and controls
1490 lines (945 loc) · 56.9 KB
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import requests
import configobj
import validate
import argparse
import os
import sys
import re
import socket
import logging
import logging.handlers
import backoff
import json
import yagmail
import schedule
import time
import daemon
import urllib3
import signal
import kodijson
import datetime
from bs4 import BeautifulSoup
# hack to workaround bs not being compatible with python 3.10 see
# https://stackoverflow.com/questions/69515086/error-attributeerror-collections-has-no-attribute-callable-using-beautifu
# import collections
# collections.Callable = collections.abc.Callable
urllib3.disable_warnings() # required to suppress ssl warning for urllib3 (requests uses urllib3)
signal.signal(signal.SIGINT, signal.default_int_handler) # ensure we correctly handle all keyboard interrupts
# TODO change input to functions as dictionary
# TODO change functions to **kwargs and use .get() to get value (will be none if not fund)
# TODO change return for function to dictionary
def create_config():
validator = validate.Validator()
config_obj.validate(validator, copy=True)
config_obj.filename = config_ini
config_obj.write()
def time_check(current_time, grace_period_mins, source_version_change_datetime):
# compare difference between local date/time and trigger date/time to produce timedelta
time_delta = current_time - source_version_change_datetime
app_logger_instance.debug(u"Time delta object is %s" % time_delta)
# turn timedelta object into minutes
time_delta_secs = datetime.timedelta.total_seconds(time_delta)
time_delta_mins = int(time_delta_secs) / 60
grace_period_mins_int = int(grace_period_mins)
# check if time_delta is greater than or equal to grace_period_mins
if time_delta_mins >= grace_period_mins_int:
app_logger_instance.info(u"Time since last update (%s mins) >= to grace period (%s mins)" % (time_delta_mins, grace_period_mins))
return True
else:
app_logger_instance.info(u"Time since last update (%s mins) < grace period (%s mins)" % (time_delta_mins, grace_period_mins))
return False
def app_logging():
# read log levels
log_level = config_obj["general"]["log_level"]
# setup formatting for log messages
app_formatter = logging.Formatter("%(asctime)s %(threadName)s %(module)s %(funcName)s :: [%(levelname)s] %(message)s")
# setup logger for app
app_logger = logging.getLogger("app")
# add rotating log handler
app_rotatingfilehandler = logging.handlers.RotatingFileHandler(app_log_file, "a", maxBytes=10485760, backupCount=3, encoding="utf-8")
# set formatter for app
app_rotatingfilehandler.setFormatter(app_formatter)
# add the log message handler to the logger
app_logger.addHandler(app_rotatingfilehandler)
# set level of logging from config
if log_level == "INFO":
app_logger.setLevel(logging.INFO)
elif log_level == "WARNING":
app_logger.setLevel(logging.WARNING)
elif log_level == "exception":
app_logger.setLevel(logging.ERROR)
elif log_level == "debug":
app_logger.setLevel(logging.DEBUG)
# setup logging to console
console_streamhandler = logging.StreamHandler()
# set formatter for console
console_streamhandler.setFormatter(app_formatter)
# add handler for formatter to the console
app_logger.addHandler(console_streamhandler)
# set level of logging from config
if log_level == "INFO":
console_streamhandler.setLevel(logging.INFO)
elif log_level == "WARNING":
console_streamhandler.setLevel(logging.WARNING)
elif log_level == "exception":
console_streamhandler.setLevel(logging.ERROR)
elif log_level == "debug":
console_streamhandler.setLevel(logging.DEBUG)
return {'logger': app_logger, 'handler': app_rotatingfilehandler}
def notification_email(**kwargs):
if not email_notification:
app_logger_instance.info(u"Email notification not enabled")
return 1
# unpack arguments from dictionary
action = kwargs.get("action")
msg_type = kwargs.get("msg_type")
error_msg = kwargs.get("error_msg")
source_app_name = kwargs.get("source_app_name")
source_repo_name = kwargs.get("source_repo_name")
source_site_name = kwargs.get("source_site_name")
source_site_url = kwargs.get("source_site_url")
target_repo_name = kwargs.get("target_repo_name")
previous_version = kwargs.get("previous_version")
current_version = kwargs.get("current_version")
if msg_type == "site_error":
yag = yagmail.SMTP(email_username, email_password)
subject = '%s - %s' % (source_site_name, msg_type)
html = '''
<b>Source Site Name:</b> %s<br>
<b>Source Site URL:</b> <a href="%s">%s</a><br>
<b>Error Message:</b> %s
''' % (source_site_name, source_site_url, source_site_name, error_msg)
elif msg_type == "config_error" or msg_type == "app_error":
yag = yagmail.SMTP(email_username, email_password)
subject = '%s - %s' % (source_app_name, msg_type)
html = '''
<b>Source Site Name:</b> %s<br>
<b>Source Repository:</b> %s<br>
<b>Source Site URL:</b> <a href="%s">%s</a><br>
<b>Error Message:</b> %s
''' % (source_site_name, source_repo_name, source_site_url, source_app_name, error_msg)
else:
target_repo_owner = config_obj["general"]["target_repo_owner"]
# construct url to docker hub build details
dockerhub_build_details = "https://hub.docker.com/r/%s/%s/tags?page=1&ordering=last_updated&name=latest" % (target_repo_owner, target_repo_name)
# construct url to github workflow details
github_action_details = "https://github.com/%s/%s/actions" % (target_repo_owner, target_repo_name)
# construct url to github container registry details
github_ghcr_details = "https://github.com/users/%s/packages/container/package/%s" % (target_repo_owner, target_repo_name)
yag = yagmail.SMTP(email_username, email_password)
subject = '%s [%s] - updated to %s' % (source_app_name, action, current_version)
html = '''
<b>Action:</b> %s<br>
<b>Previous Version:</b> %s<br>
<b>Current Version:</b> %s<br>
<b>Source Site Name:</b> %s<br>
<b>Source Repository:</b> %s<br>
<b>Source Site URL:</b> <a href="%s">%s</a>
''' % (action, previous_version, current_version, source_site_name, source_repo_name, source_site_url, source_app_name)
if action == "trigger":
html += '''
<b>Target Repository URL:</b> <a href="https://github.com/%s/%s">github repo</a><br>
<b>Target Github Action URL:</b> <a href="%s">github workflow</a><br>
<b>Target Github Container Registry URL:</b> <a href="%s">github registry</a><br>
<b>Target Docker Hub Registry URL:</b> <a href="%s">dockerhub registry</a>
''' % (target_repo_owner, target_repo_name, github_action_details, github_ghcr_details, dockerhub_build_details)
try:
app_logger_instance.info(u'Sending email notification...')
yag.send(to=email_to, subject=subject, contents=[html])
except Exception:
app_logger_instance.warning(u"Failed to send E-Mail notification to %s" % email_to)
return 1
# noinspection PyUnresolvedReferences
def notification_kodi(action, source_app_name, current_version):
if not kodi_notification:
app_logger_instance.info(u"Kodi notification not enabled")
return 1
# read kodi config
kodi_username = config_obj["notification"]["kodi_username"]
kodi_hostname = config_obj["notification"]["kodi_hostname"]
kodi_port = config_obj["notification"]["kodi_port"]
# construct login with custom credentials for rpc call
kodi = kodijson.Kodi("http://%s:%s/jsonrpc" % (kodi_hostname, kodi_port), kodi_username, kodi_password)
# send gui notification
try:
app_logger_instance.info(u'Sending kodi notification...')
kodi.GUI.ShowNotification({"title": "TriggerDockerBuild", "message": "%s [%s] - updated to %s" % (source_app_name, action, current_version)})
except Exception:
app_logger_instance.warning(u"Failed to send notification to Kodi instance at http://%s:%s/jsonrpc" % (kodi_hostname, kodi_port))
return 1
@backoff.on_exception(backoff.expo, (socket.timeout, requests.exceptions.Timeout, requests.exceptions.HTTPError), max_tries=10)
def http_client(**kwargs):
if kwargs is not None:
if "url" in kwargs:
url = kwargs['url']
else:
app_logger_instance.warning(u'No URL sent to function, exiting function...')
return 1, None, None
if "user_agent" in kwargs:
user_agent = kwargs['user_agent']
else:
app_logger_instance.warning(u'No User Agent sent to function, exiting function...')
return 1, None, None
if "request_type" in kwargs:
request_type = kwargs['request_type']
else:
app_logger_instance.warning(u'No request type (get/put/post) sent to function, exiting function...')
return 1, None, None
# optional stuff to include
if "auth" in kwargs:
auth = kwargs['auth']
else:
auth = None
if "additional_header" in kwargs:
additional_header = kwargs['additional_header']
else:
additional_header = None
if "data_payload" in kwargs:
data_payload = kwargs['data_payload']
else:
data_payload = None
else:
app_logger_instance.warning(u'No keyword args sent to function, exiting function...')
return 1, None, None
# set connection timeout value (max time to wait for connection)
connect_timeout = 60.0
# set read timeout value (max time to wait between each byte)
read_timeout = 60.0
# use a session instance to customize how "requests" handles making http requests
session = requests.Session()
# set status_code and content to None in case nothing returned
status_code = None
try:
# define dict of common arguments for requests
requests_data_dict = {'url': url, 'timeout': (connect_timeout, read_timeout), 'allow_redirects': True, 'verify': False}
# define default headers to compress and fake user agent
session.headers.update({
'Accept-encoding': 'gzip',
'User-Agent': user_agent
})
if "additional_header" in kwargs:
# append to headers dict with additional headers dict
session.headers.update(additional_header)
if "auth" in kwargs:
session.auth = auth
if request_type == "put":
# add additional keyword arguments
requests_data_dict.update({'data': data_payload})
elif request_type == "post":
# add additional keyword arguments
requests_data_dict.update({'data': data_payload})
# construct class.method from request_type
request_method = getattr(session, request_type)
# use keyword argument unpack to convert dict to keyword args
response = request_method(**requests_data_dict)
# get status code and content returned
status_code = response.status_code
content = response.content
if status_code == 401:
app_logger_instance.warning(u"The status code %s indicates unauthorised access for %s, error is %s" % (status_code, url, content))
raise requests.exceptions.HTTPError(status_code, url, content)
elif status_code == 404:
app_logger_instance.warning(u"The status code %s indicates the requested resource could not be found for %s, error is %s" % (status_code, url, content))
raise requests.exceptions.HTTPError(status_code, url, content)
elif status_code == 422:
app_logger_instance.warning(u"The status code %s indicates a request was well-formed but was unable to be followed due to semantic errors for %s, error is %s" % (status_code, url, content))
raise requests.exceptions.HTTPError(status_code, url, content)
elif not 200 <= status_code <= 299:
app_logger_instance.warning(u"The status code %s indicates an unexpected error for %s, error is %s" % (status_code, url, content))
raise requests.exceptions.HTTPError(status_code, url, content)
except requests.exceptions.ConnectTimeout as content:
# connect timeout occurred
app_logger_instance.warning(u"Connection timeout for URL %s with error %s" % (url, content))
return 1, status_code, content
except requests.exceptions.ConnectionError as content:
# connection error occurred
app_logger_instance.warning(u"Connection error for URL %s with error %s" % (url, content))
return 1, status_code, content
except requests.exceptions.TooManyRedirects as content:
# too many redirects, bad site or circular redirect
app_logger_instance.warning(u"Too many retries for URL %s with error %s" % (url, content))
return 1, status_code, content
except requests.exceptions.HTTPError as content:
# catch http exceptions thrown by requests
return 1, status_code, content
except requests.exceptions.ReadTimeout as content:
# too many redirects, bad site or circular redirect
app_logger_instance.warning(u"Read timeout for URL %s with error %s" % (url, content))
return 1, status_code, content
except requests.exceptions.RequestException as content:
# catch any other exceptions thrown by requests
app_logger_instance.warning(u"Caught other exceptions for URL %s with error %s" % (url, content))
return 1, status_code, content
else:
if 200 <= status_code <= 299:
app_logger_instance.info(u"The status code %s indicates a successful request for %s" % (status_code, url))
return 0, status_code, content
def github_create_release(current_version, target_repo_branch, target_repo_owner, target_repo_name, user_agent):
# remove illegal characters from version (github does not allow certain chars for release name)
current_version = re.sub(r":", r".", current_version, flags=re.IGNORECASE)
app_logger_instance.info(u"Creating Release on GitHub for version %s..." % current_version)
github_tag_name = "%s-01" % current_version
github_release_name = "API/URL triggered release"
github_release_body = github_tag_name
request_type = "post"
http_url = 'https://api.github.com/repos/%s/%s/releases' % (target_repo_owner, target_repo_name)
data_payload = '{"tag_name": "%s", "target_commitish": "%s", "name": "%s", "body": "%s", "draft": false, "prerelease": false}' % (github_tag_name, target_repo_branch, github_release_name, github_release_body)
# process post request
return_code, status_code, content = http_client(url=http_url, user_agent=user_agent, additional_header={'Authorization': 'token %s' % target_access_token}, request_type=request_type, data_payload=data_payload)
return return_code, status_code, content
def check_site(**kwargs):
# unpack arguments from dictionary
url = kwargs.get("url")
user_agent = kwargs.get("user_agent")
site_name = kwargs.get("site_name")
# construct url to github rest api
request_type = "get"
# set number of retries and set default site_down boolean
retries = 10
sleep_secs = 60
site_down = True
while True:
# download json content
return_code, status_code, content = http_client(url=url, user_agent=user_agent, additional_header={'Authorization': 'token %s' % target_access_token}, request_type=request_type)
if return_code == 0:
site_down = False
app_logger_instance.debug(f"'{site_name}' site operational for '{url}'")
break
else:
app_logger_instance.info(f"Having issues connecting to '{site_name}' for '{url}', retrying in '{sleep_secs}' seconds...")
time.sleep(sleep_secs)
retries = retries - 1
if retries <= 0:
app_logger_instance.warning(f"'{site_name}' site down for '{url}'")
break
if site_down:
msg_type = "site_error"
error_msg = f"{site_name} site down - '{url}'"
notification_email(msg_type=msg_type, error_msg=error_msg, source_site_name=site_name, source_site_url=url)
app_logger_instance.warning(error_msg)
# convert the following then compare against throttle days value "2020-04-15T21:53:20Z"
return site_down
def github_target_last_release_date(target_repo_owner, target_repo_name, user_agent):
github_query_type = "releases/latest"
json_query = "published_at"
# construct url to github rest api
url = "https://api.github.com/repos/%s/%s/%s" % (target_repo_owner, target_repo_name, github_query_type)
request_type = "get"
# download json content
return_code, status_code, content = http_client(url=url, user_agent=user_agent, additional_header={'Authorization': 'token %s' % target_access_token}, request_type=request_type)
if return_code == 0:
try:
content = json.loads(content)
except (ValueError, TypeError, KeyError):
app_logger_instance.info(u"Problem loading json from %s" % url)
return 1, None
else:
app_logger_instance.info(u"Problem downloading json content from %s" % url)
return 1, None
try:
# get release date from json
target_last_release_date = content['%s' % json_query]
except IndexError:
app_logger_instance.info(u"Problem parsing json from %s, skipping to next iteration..." % url)
return 1, None
# convert the following then compare against throttle days value "2020-04-15T21:53:20Z"
return 0, target_last_release_date
def github_apps(source_app_name, source_query_type, source_repo_name, user_agent, source_branch_name):
# certain github repos do not have releases, only tags, thus we need to account for these differently
if source_query_type.lower() == "tag":
github_query_type = "tags"
json_query = "name"
elif source_query_type.lower() == "pre-release":
github_query_type = "releases"
json_query = "tag_name"
elif source_query_type.lower() == "release":
github_query_type = "releases/latest"
json_query = "tag_name"
elif source_query_type.lower() == "branch":
github_query_type = "commits"
json_query = "sha"
else:
app_logger_instance.warning(u"source_query_type '%s' is not valid, skipping to next iteration..." % source_query_type.lower())
return None, None
# construct url for package details
source_site_url = "https://github.com/%s/%s/%s" % (source_repo_name, source_app_name, github_query_type)
# construct url to github rest api
url = "https://api.github.com/repos/%s/%s/%s" % (source_repo_name, source_app_name, github_query_type)
# if github branch then we specify the branch name via 'sha' parameter
if source_query_type.lower() == "branch":
url = "%s?sha=%s" % (url, source_branch_name)
request_type = "get"
# download json content
return_code, status_code, content = http_client(url=url, user_agent=user_agent, additional_header={'Authorization': 'token %s' % target_access_token}, request_type=request_type)
if return_code == 0:
try:
content = json.loads(content)
except (ValueError, TypeError, KeyError):
app_logger_instance.info(u"Problem loading json from %s" % url)
return None, source_site_url
else:
app_logger_instance.info(u"Problem downloading json content from %s" % url)
return None, source_site_url
try:
if github_query_type == "tags" or github_query_type == "commits":
# get tag/sha from json
current_version = content[0]['%s' % json_query]
elif github_query_type == "releases/latest":
# get release from json
current_version = content['%s' % json_query]
else:
app_logger_instance.warning(u"Unknown Github query type of '%s', skipping to next iteration..." % github_query_type)
return None, source_site_url
except IndexError:
app_logger_instance.warning(u"Problem parsing json from %s, skipping to next iteration..." % url)
return None, source_site_url
if source_query_type.lower() == "branch":
source_site_url = "%s/%s" % (source_site_url, source_branch_name)
return current_version, source_site_url
def gitlab_apps(source_app_name, source_repo_name, source_project_id, source_branch_name, source_query_type, user_agent):
# use gitlab rest api
url = 'https://gitlab.com/api/v4/projects/%s/repository/commits/%s' % (source_project_id, source_branch_name)
# construct url for package details
source_site_url = 'https://gitlab.com/%s/%s' % (source_repo_name, source_app_name)
request_type = "get"
if source_query_type.lower() == "branch":
json_query = "id"
else:
app_logger_instance.warning(u"source_query_type '%s' is not valid, skipping to next iteration..." % source_query_type.lower())
return None, source_site_url
# download webpage content
return_code, status_code, content = http_client(url=url, user_agent=user_agent, request_type=request_type)
if return_code == 0:
try:
# decode json
content = json.loads(content)
except (ValueError, TypeError, KeyError, IndexError):
app_logger_instance.info(u"Problem loading json from %s" % url)
return None, source_site_url
else:
app_logger_instance.info(u"Problem downloading json content from %s" % url)
return None, source_site_url
try:
# construct app version
current_version = content['%s' % json_query]
except (ValueError, TypeError, KeyError, IndexError):
app_logger_instance.info(u"Problem parsing json from %s, skipping to next iteration..." % url)
return None, source_site_url
return current_version, source_site_url
def pypi_apps(source_app_name, user_agent):
# use pypi json to get python package version
url = "https://pypi.org/pypi/%s/json" % source_app_name
request_type = "get"
# construct url for package details
source_site_url = f"https://pypi.org/search/?q={source_app_name}"
# download webpage content
return_code, status_code, content = http_client(url=url, user_agent=user_agent, request_type=request_type)
if return_code == 0:
try:
# decode json
content = json.loads(content)
except (ValueError, TypeError, KeyError, IndexError):
app_logger_instance.info(u"Problem loading json from %s" % url)
return None, source_site_url
else:
app_logger_instance.info(u"Problem downloading json content from %s" % url)
return None, source_site_url
current_version = content['info']['version']
return current_version, source_site_url
def aor_apps(source_app_name, user_agent):
# use aor unofficial api to get app release info
url = 'https://archlinux.org/packages/search/json/?q=%s' % source_app_name
request_type = "get"
# construct url for package details
source_site_url = f"https://archlinux.org/packages/?sort=&q={source_app_name}&maintainer=&flagged="
# download webpage content
return_code, status_code, content = http_client(url=url, user_agent=user_agent, request_type=request_type)
try:
# decode json
content = json.loads(content)
# filter python objects with list comprehension to prevent fuzzy mismatch
content = [x for x in content['results'] if x['pkgname'] == source_app_name]
except (ValueError, TypeError, KeyError, IndexError):
app_logger_instance.info(u"Problem loading json from %s" % url)
return None, source_site_url
try:
# get package version and release number from json
pkgver = content[0]['pkgver']
pkgrel = content[0]['pkgrel']
# construct app version
current_version = "%s-%s" % (pkgver, pkgrel)
except (ValueError, TypeError, KeyError, IndexError):
app_logger_instance.info(u"Problem parsing json from %s, skipping to next iteration..." % url)
return None, source_site_url
return current_version, source_site_url
def aur_apps(source_app_name, user_agent):
# use aur api to get app release info
url = "https://aur.archlinux.org/rpc/?v=5&type=info&arg[]=%s" % source_app_name
request_type = "get"
# construct url for package details
source_site_url = "https://aur.archlinux.org/packages/%s/" % source_app_name
# download webpage content
return_code, status_code, content = http_client(url=url, user_agent=user_agent, request_type=request_type)
if return_code == 0:
try:
content = json.loads(content)
except (ValueError, TypeError, KeyError):
app_logger_instance.info(u"Problem loading json from %s" % url)
return None, source_site_url
else:
app_logger_instance.info(u"Problem downloading json content from %s" % url)
return None, source_site_url
try:
# get app version from json
current_version = content["results"][0]["Version"]
except IndexError:
app_logger_instance.info(u"Problem parsing json from %s, skipping to next iteration..." % url)
return None, source_site_url
return current_version, source_site_url
def soup_regex(source_site_url, user_agent):
# download webpage
request_type = "get"
# download webpage content
return_code, status_code, content = http_client(url=source_site_url, user_agent=user_agent, request_type=request_type)
if return_code == 0:
try:
soup = BeautifulSoup(content, features="html.parser")
except (ValueError, TypeError, KeyError):
app_logger_instance.info(u"Problem extracting url using regex from url %s" % source_site_url)
return None, None
else:
app_logger_instance.info(u"Problem downloading webpage from url %s" % source_site_url)
return None, None
return soup
def monitor_sites():
# read sites list from config
config_site_list = config_obj["monitor_sites"]["site_list"]
target_repo_owner = config_obj["general"]["target_repo_owner"]
# pretend to be windows 10 running chrome (required for minecraft bedrock)
user_agent_chrome = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36'
# check github api is operational
url = "https://api.github.com"
site_down_github = check_site(url=url, user_agent=user_agent_chrome, site_name='GitHub')
# check gitlab rest api is operational
url = "https://gitlab.com/api/v4/projects"
site_down_gitlab = check_site(url=url, user_agent=user_agent_chrome, site_name='GitLab')
# check pypi website is operational
test_package = 'requests'
url = f"https://pypi.org/pypi/{test_package}/json"
site_down_pypi = check_site(url=url, user_agent=user_agent_chrome, site_name='PyPi')
# check aor site is operational
test_package = 'base'
url = f'https://archlinux.org/packages/core/any/{test_package}/'
site_down_aor = check_site(url=url, user_agent=user_agent_chrome, site_name='AOR')
# check aur site is operational
test_package = 'yay'
url = f"https://aur.archlinux.org/rpc/?v=5&type=info&arg[]={test_package}"
site_down_aur = check_site(url=url, user_agent=user_agent_chrome, site_name='AUR')
# set counter for number of failures to get app package details
app_down_gitlab_counter = 0
app_down_github_counter = 0
app_down_pypi_counter = 0
app_down_aor_counter = 0
app_down_aur_counter = 0
# set maximum number of email notifications for failed downloads before skipping
app_down_counter_max = 3
# loop over each site and check previous and current result
for site_item in config_site_list:
source_site_name = site_item.get("source_site_name")
source_app_name = site_item.get("source_app_name")
source_repo_name = site_item.get("source_repo_name")
source_project_id = site_item.get("source_project_id")
source_branch_name = site_item.get("source_branch_name")
target_release_days = site_item.get("target_release_days")
target_repo_name = site_item.get("target_repo_name")
target_repo_branch = site_item.get("target_repo_branch")
source_query_type = site_item.get("source_query_type")
grace_period_mins = site_item.get("grace_period_mins")
source_version_change_datetime = site_item.get("source_version_change_datetime")
action = site_item.get("action")
# set default values in case they are not supplied
source_site_url = None
app_logger_instance.info(u"-------------------------------------")
app_logger_instance.info(u"Processing started for application %s..." % source_app_name)
if action != "notify":
# if target branch not defined then send email notification and skip to next item
if target_repo_branch is None:
msg_type = "config_error"
error_msg = u"Target repo branch not defined for target repo '%s', skipping to next iteration..." % target_repo_name
notification_email(msg_type=msg_type, error_msg=error_msg, source_site_name=source_site_name, source_repo_name=source_repo_name, source_app_name=source_app_name, source_site_url=source_site_url)
app_logger_instance.warning(error_msg)
continue
if source_site_name == "github":
if site_down_github:
app_logger_instance.warning(u"Site '%s' marked as down, skipping processing for application '%s'..." % (source_site_name, source_app_name))
continue
current_version, source_site_url = github_apps(source_app_name, source_query_type, source_repo_name, user_agent_chrome, source_branch_name)
if current_version is None:
error_msg = f"Unable to connect to site '{source_site_name}' for application '{source_app_name}', skipping to next iteration..."
# increment counter for number of failed app detail downloads
app_down_github_counter += 1
# if number of failed app package detail downloads above limit then silence email notifications
if app_down_github_counter <= app_down_counter_max:
msg_type = "app_error"
notification_email(msg_type=msg_type, error_msg=error_msg, source_site_name=source_site_name, source_repo_name=source_repo_name, source_app_name=source_app_name, source_site_url=source_site_url)
else:
app_logger_instance.info(f"Number of failed downloads for site '{source_site_name}' has exceeded '{app_down_counter_max}', skipping notifications")
app_logger_instance.warning(error_msg)
continue
elif source_site_name == "gitlab":
if site_down_gitlab:
app_logger_instance.warning(u"Site '%s' marked as down, skipping processing for application '%s'..." % (source_site_name, source_app_name))
continue
current_version, source_site_url = gitlab_apps(source_app_name, source_repo_name, source_project_id, source_branch_name, source_query_type, user_agent_chrome)
if current_version is None:
error_msg = f"Unable to connect to site '{source_site_name}' for application '{source_app_name}', skipping to next iteration..."
# increment counter for number of failed app detail downloads
app_down_gitlab_counter += 1
# if number of failed app package detail downloads above limit then silence email notifications
if app_down_gitlab_counter <= app_down_counter_max:
msg_type = "app_error"
notification_email(msg_type=msg_type, error_msg=error_msg, source_site_name=source_site_name, source_repo_name=source_repo_name, source_app_name=source_app_name, source_site_url=source_site_url)
else:
app_logger_instance.info(f"Number of failed downloads for site '{source_site_name}' has exceeded '{app_down_counter_max}', skipping notifications")
app_logger_instance.warning(error_msg)
continue
elif source_site_name == "pypi":
if site_down_pypi:
app_logger_instance.warning(u"Site '%s' marked as down, skipping processing for application '%s'..." % (source_site_name, source_app_name))
continue
current_version, source_site_url = pypi_apps(source_app_name, user_agent_chrome)
if current_version is None:
error_msg = f"Unable to connect to site '{source_site_name}' for application '{source_app_name}', skipping to next iteration..."
# increment counter for number of failed app detail downloads
app_down_pypi_counter += 1
# if number of failed app package detail downloads above limit then silence email notifications
if app_down_pypi_counter <= app_down_counter_max:
msg_type = "app_error"
notification_email(msg_type=msg_type, error_msg=error_msg, source_site_name=source_site_name, source_repo_name=source_repo_name, source_app_name=source_app_name, source_site_url=source_site_url)
else:
app_logger_instance.info(f"Number of failed downloads for site '{source_site_name}' has exceeded '{app_down_counter_max}', skipping notifications")
app_logger_instance.warning(error_msg)
continue
elif source_site_name == "aor":
if site_down_aor:
app_logger_instance.warning(u"Site '%s' marked as down, skipping processing for application '%s'..." % (source_site_name, source_app_name))
continue
# if grace period not defined then set to default value (required for aor)
if grace_period_mins is None:
grace_period_mins = 60
current_version, source_site_url = aor_apps(source_app_name, user_agent_chrome)
if current_version is None:
error_msg = f"Unable to connect to site '{source_site_name}' for application '{source_app_name}', skipping to next iteration..."
# increment counter for number of failed app detail downloads
app_down_aor_counter += 1
# if number of failed app package detail downloads above limit then silence email notifications
if app_down_aor_counter <= app_down_counter_max: