-
Notifications
You must be signed in to change notification settings - Fork 24
/
bbbackup.py
executable file
·1569 lines (1382 loc) · 72 KB
/
bbbackup.py
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
# -*- coding: utf-8 -*-
#!/usr/bin/env python
"""
BBBACKUP
Script to clone all repos from a specified BitBucket team/user to create a BitBucket Backup
using the Atlassian BitBucket API 2.0 and GitPython
Author: Helge Staedtler
E-Mail: [email protected]
Company: Open Reply GmbH, Bremen/Germany
Version: 1.4
Language: Python 3
License: MIT License (see https://choosealicense.com/licenses/mit/)
MIT License
Copyright (c) 2019 Open Reply GmbH, Bremen, Germany
Helge Staedtler <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Useful sources:
https://alvinalexander.com/mac-os-x/mac-osx-startup-crontab-launchd-jobs
https://api.slack.com/rtm
https://api.slack.com/methods/chat.postMessage#formatting
https://confluence.atlassian.com/bitbucket/oauth-on-bitbucket-cloud-238027431.html
https://stackoverflow.com/questions/36719540/how-can-i-get-an-oauth2-access-token-using-python
https://rauth.readthedocs.io/en/latest/
https://lanphier.co.uk/scripts/automated-bitbucket-repository-backups-without-a-dedicated-user-account/
https://confluence.atlassian.com/jirakb/how-to-automate-backups-for-jira-cloud-applications-779160659.html
https://bitbucket.org/atlassianlabs/automatic-cloud-backup/src/master/
https://github.com/samkuehn/bitbucket-backup
"""
from argparse import RawTextHelpFormatter
from git import Repo
from requests.auth import HTTPBasicAuth
from datetime import datetime
from datetime import timedelta
from datetime import date
from getpass import getpass
from slack.errors import SlackApiError
from rauth import OAuth2Service
from configparser import ConfigParser
from keyring.errors import KeyringLocked, InitError
import argparse
import json
import os
import requests
import sys
import time
import keyring
import errno
import unicodedata
import shutil
import signal
import slack
import math
import traceback
# CONSTANT VALUES
APP_VERSION = "v1.4"
APP_BUILD = "42"
APP_PATH = os.path.dirname( os.path.abspath( __file__ ) )
APP_CONFIG_FILE = 'bbbackup.cfg'
APP_LOGO = '''
_ _ _ _
| |__| |__| |__ __ _ __| |___ _ _ __
| '_ \ '_ \ '_ \/ _` / _| / / || | '_ \\
|_.__/_.__/_.__/\__,_\__|_\_\\\\_,_| .__/
{} |_|
'''
APP_COPYRIGHT_NOTICE = '''
Copyright (C) 2019-2020 Helge Staedtler from Open Reply GmbH
This program comes with ABSOLUTELY NO WARRANTY
This is free software, and you are welcome to redistribute it
under certain conditions. DETAILS in the LICENSE file!
'''
# API 1
API_V1_ROOT = 'https://api.bitbucket.org/1.0/'
API_V1_USERS = 'users/'
# API 2
API_V2_ROOT = 'https://api.bitbucket.org/2.0/'
API_V2_USERS = 'users/'
API_V2_REPOSITORIES = 'repositories/'
API_V2_PARAM_ROLE = 'role=member'
AUTH_METHOD_OAUTH2 = 'oauth'
AUTH_METHOD_UIDPWD = 'uidpwd'
# DEFAULTS
DEFAULT_API_USED = '2.0' # '1.0' is deprecated
DEFAULT_AUTH = AUTH_METHOD_UIDPWD
DEFAULT_BACKUP_ALL_BRANCHES = False
DEFAULT_BACKUP_ROOT_DIRECTORY = ''
DEFAULT_BACKUP_MAX_RETRIES = 3
DEFAULT_BACKUP_MAX_FAILS = 3
DEFAULT_BACKUP_MIN_FREESPACE_GIGA = 50
DEFAULT_BACKUP_STORE_DAYS = 7
DEFAULT_SLACK_TO_CHANNEL = '@channel'
DEFAULT_LOG_OUTPUT = True
DEFAULT_LOG_COLORIZED = True
# API VERSION TO USE (LATEST 2.0 recommended)
API_USED = DEFAULT_API_USED
AUTH = DEFAULT_AUTH
# OAUTH 2.0 SUPPORT
OAUTH_CLIENT_KEY_OR_ID = None # call with parameter --config-oauth2
OAUTH_CLIENT_SECRET = None # call with parameter --config-oauth2
OAUTH_CLIENT_NAME = None # call with parameter --config-oauth2
OAUTH_URL_AUTORIZE = 'https://bitbucket.org/site/oauth2/authorize'
OAUTH_URL_ACCESS_TOKEN = 'https://bitbucket.org/site/oauth2/access_token'
# OAUTH KEY/SECRET/NAME KEYS
CRED_KEY_OAUTH_KEY = "OAUTH_KEY"
CRED_KEY_OAUTH_SECRET = "OAUTH_SECRET"
CRED_KEY_OAUTH_NAME = "OAUTH_NAME"
# BACKUP STORAGE NAME
BACKUP_ARCHIVE_PREFIX = "BACKUP"
BACKUP_ARCHIVE_SUFFIX = "UTC"
BACKUP_ARCHIVE_DIRECTORY = None
BACKUP_ROOT_DIRECTORY = DEFAULT_BACKUP_ROOT_DIRECTORY
BACKUP_MAX_RETRIES = DEFAULT_BACKUP_MAX_RETRIES
BACKUP_MAX_FAILS = DEFAULT_BACKUP_MAX_FAILS
BACKUP_MIN_FREESPACE_GIGA = DEFAULT_BACKUP_MIN_FREESPACE_GIGA
BACKUP_STORE_MIN_DAYS = 1
BACKUP_STORE_DAYS = DEFAULT_BACKUP_STORE_DAYS
BACKUP_STORE_DAYS_SCOPE = 30
BACKUP_LASTRUN_FILE = "BACKUP_LASTRUN.JSON"
# LOG MODES
LOG_OUTPUT = DEFAULT_LOG_OUTPUT
LOG_COLORIZED = DEFAULT_LOG_COLORIZED
# BACKUP STATUS TAGS
STATUS_SYNC = "SYNC"
STATUS_DONE = "DONE"
STATUS_FAIL = "FAIL"
# CREDENTIAL STORAGE KEYS
CRED_KEY_SERVICE = "BBBACKUP"
CRED_KEY_UID = "UID"
CRED_KEY_PWD = "PWD"
CRED_KEY_TEAM = "TEAM"
# CREDENTIAL VALUES USED FOR AUTH
CONFIG_UID = None
CONFIG_PWD = None
CONFIG_TEAM = None
# SLACK CREDENTIALS
SLACK_API_TOKEN = None
SLACK_CHANNEL = None
SLACK_TO_CHANNEL = DEFAULT_SLACK_TO_CHANNEL
CRED_KEY_SLACK_CHANNEL = "SLACK_CHANNEL"
CRED_KEY_SLACK_TOKEN = "SLACK_TOKEN"
'''
**********************************
*** SYSTEM RELATED METHODS
**********************************
'''
# FORCED EXIT HANDLING
def signal_handler(sig, frame):
print( "" )
exit_with_code( 1 )
# check if the script is run from commandline/terminal (TTY)
def is_running_interactively():
return sys.stdin.isatty()
def exit_with_code( code, optional_message=None ):
finishtime = datetime.now()
printstyled('FINISHED: ' + str( finishtime ), 'yellow', 'bold' )
exit_msg = ''
if code == 0:
exit_msg = 'BACKUP: BYE, BYE.'
elif code == 1:
exit_msg = 'BACKUP: ABORTED. (CODE = {})'.format( str(code).zfill(2) )
elif code == 2:
exit_msg = 'BACKUP: ABORTED. (CODE = {}, no valid credentials provided)'.format( str(code).zfill(2) )
elif code == 3:
exit_msg = 'BACKUP: ABORTED. (CODE = {}, unable to fetch repos, check credentials)'.format( str(code).zfill(2) )
elif code == 4:
exit_msg = 'BACKUP: ABORTED. (CODE = {}, no valid slack configuration)'.format( str(code).zfill(2) )
elif code == 5:
exit_msg = 'BACKUP: ABORTED. (CODE = {}, not enough free space on volume)'.format( str(code).zfill(2) )
elif code == 6:
exit_msg = 'BACKUP: ABORTED. (CODE = {}, no valid oauth 2.0 configuration)'.format( str(code).zfill(2) )
elif code == 7:
exit_msg = 'BACKUP: ABORTED. (CODE = {}, no valid filepath for directory of backups provided, use --filepath or --configuration parameters)'.format( str(code).zfill(2) )
elif code == 8:
exit_msg = 'BACKUP: ABORTED. (CODE = {}, just finished writing/exporting configuration)'.format( str(code).zfill(2) )
elif code == 9:
exit_msg = 'BACKUP: ABORTED. (CODE = {}, just finished reading/importing configuration)'.format( str(code).zfill(2) )
elif code == 10:
exit_msg = 'BACKUP: ABORTED. (CODE = {}, no valid data from API)'.format( str(code).zfill(2) )
elif code == 11:
exit_msg = 'BACKUP: ABORTED. (CODE = {}, unexpected repo data from API)'.format( str(code).zfill(2) )
elif code == 12:
exit_msg = 'BACKUP: ABORTED. (CODE = {}, access to the secure credential store disallowed by user)'.format( str(code).zfill(2) )
elif code == 13:
exit_msg = 'BACKUP: ABORTED. (CODE = {}, no supported secure credential store infrastructure found in current OS environment)'.format( str(code).zfill(2) )
else:
exit_msg = 'BACKUP: UNEXPECTED EXIT. (CODE = {})'.format( str(code).zfill(2) )
if optional_message:
exit_msg = exit_msg + '\n' + optional_message
printstyled( exit_msg, 'cyan' )
if code != 0:
slack_send_message_of_category( exit_msg, 'fail' )
print( "" )
sys.exit( code )
# CHECK IF DIR EXISTS, IF NOT CREATE IT
def ensure_directory_exists( absolute_dir_path ):
if os.path.exists( absolute_dir_path ):
printstyled( 'DIRECTORY: OK {}'.format( absolute_dir_path ), 'cyan' )
return
else:
printstyled( 'DIRECTORY: MISSING {}'.format( absolute_dir_path ), 'cyan' )
printstyled( 'DIRECTORY: CREATING... {}'.format( absolute_dir_path ), 'cyan' )
try:
os.makedirs( absolute_dir_path )
printstyled( 'DIRECTORY: CREATED.', 'green' )
except OSError as e:
printstyled( 'DIRECTORY: CREATION FAILED.', 'red' )
if e.errno != errno.EEXIST:
raise
return
def get_fs_freespace( pathname ):
"Get the free space of the filesystem containing pathname"
stat = os.statvfs( pathname )
return stat.f_bavail * stat.f_frsize
def sizeof_fmt(num, suffix='B'):
for unit in ['','k','M','G','T','P','E','Z']:
if abs(num) < 1024.0:
return "%3.1f %s%s" % (num, unit, suffix)
num /= 1024.0
return "%.1f %s%s" % (num, 'Y', suffix)
def get_size( dir_path ):
total_size = 0
for dirpath, dirnames, filenames in os.walk( dir_path ):
for f in filenames:
fp = os.path.join(dirpath, f)
total_size += os.path.getsize(fp)
return total_size
# HELPER TO COLORIZE PRINT OUTPUT
class termcolor:
RED = '\033[91m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
BLUE = '\033[94m'
MAGENTA = '\033[95m'
CYAN = '\033[96m'
WHITE = '\033[97m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def printstyled( text = '', color = 'white', style = 'plain' ):
if not log_mode:
return
if colorized_mode:
if color == 'red':
text = termcolor.RED + text
if color == 'green':
text = termcolor.GREEN + text
if color == 'yellow':
text = termcolor.YELLOW + text
if color == 'blue':
text = termcolor.BLUE + text
if color == 'magenta':
text = termcolor.MAGENTA + text
if color == 'cyan':
text = termcolor.CYAN + text
if style == 'bold':
text = termcolor.BOLD + text
if style == 'underlined':
text = termcolor.UNDERLINE + text
text += termcolor.ENDC
print( text )
# FILE OPERATIONS
def write_file( filename, content ):
try:
with open( filename, 'w' ) as f:
f.write( content )
except IOError:
printstyled( 'FAILED TO WRITE FILE: {}'.format( filename ), 'red' )
return
def delete_file( filename ):
try:
os.remove( filename )
except:
printstyled( 'FAILED TO DELETE FILE: {}'.format( filename ), 'red' )
return
def delete_dir( dirname ):
if not os.path.exists( dirname ):
printstyled( 'FILE I/O: DIRECTORY TO DESTROY DOES NOT EXIST.', 'red' )
return
try:
shutil.rmtree( dirname )
except Exception as e:
printstyled( 'FILE I/O: FAILED TO DESTROY DIRECTORY RECURSIVELY: {}'.format( dirname ), 'red' )
printstyled( 'FILE I/O EXCEPTION: {}'.format( e ), 'red' )
'''
**********************************
*** CONFIGURATION WITH .CFG-FILE
**********************************
'''
def configuration_print():
printstyled( 'CONFIG I/O: CONFIGURED FOLLOWING VALUES...', 'cyan' )
printstyled( '{}: {}'.format( "AUTH", AUTH ), 'blue' )
printstyled( '{}: {}'.format( "OAUTH_CLIENT_KEY_OR_ID", OAUTH_CLIENT_KEY_OR_ID ), 'blue' )
printstyled( '{}: {}'.format( "OAUTH_CLIENT_SECRET", OAUTH_CLIENT_SECRET ), 'blue' )
printstyled( '{}: {}'.format( "OAUTH_CLIENT_NAME", OAUTH_CLIENT_NAME ), 'blue' )
printstyled( '{}: {}'.format( "CONFIG_UID", CONFIG_UID ), 'blue' )
printstyled( '{}: {}'.format( "CONFIG_PWD", CONFIG_PWD ), 'blue' )
printstyled( '{}: {}'.format( "CONFIG_TEAM", CONFIG_TEAM ), 'blue' )
printstyled( '{}: {}'.format( "SLACK_API_TOKEN", SLACK_API_TOKEN ), 'blue' )
printstyled( '{}: {}'.format( "SLACK_CHANNEL", SLACK_CHANNEL ), 'blue' )
printstyled( '{}: {}'.format( "BACKUP_ALL_BRANCHES", BACKUP_ALL_BRANCHES ), 'blue' )
printstyled( '{}: {}'.format( "BACKUP_ROOT_DIRECTORY", BACKUP_ROOT_DIRECTORY ), 'blue' )
printstyled( '{}: {}'.format( "BACKUP_MAX_RETRIES", BACKUP_MAX_RETRIES ), 'blue' )
printstyled( '{}: {}'.format( "BACKUP_MAX_FAILS", BACKUP_MAX_FAILS ), 'blue' )
printstyled( '{}: {}'.format( "BACKUP_MIN_FREESPACE_GIGA", BACKUP_MIN_FREESPACE_GIGA ), 'blue' )
printstyled( '{}: {}'.format( "BACKUP_STORE_DAYS", BACKUP_STORE_DAYS ), 'blue' )
printstyled( '{}: {}'.format( "LOG_OUTPUT", LOG_OUTPUT ), 'blue' )
printstyled( '{}: {}'.format( "LOG_COLORIZED", LOG_COLORIZED ), 'blue' )
def configuration_import():
global AUTH, OAUTH_CLIENT_KEY_OR_ID, OAUTH_CLIENT_SECRET, OAUTH_CLIENT_NAME, CONFIG_UID, CONFIG_PWD, CONFIG_TEAM
global SLACK_API_TOKEN, SLACK_CHANNEL, BACKUP_ROOT_DIRECTORY, BACKUP_MAX_RETRIES, BACKUP_MAX_FAILS, BACKUP_MIN_FREESPACE_GIGA, BACKUP_STORE_DAYS
global BACKUP_ALL_BRANCHES
CONFIG_FILE_PATH = APP_PATH+'/'+APP_CONFIG_FILE
if not os.path.exists( CONFIG_FILE_PATH ):
printstyled( 'CONFIG I/O: No config {} found. Configuring default values.'.format( CONFIG_FILE_PATH ), 'red' )
# APPLY DEFAULT VALUES
AUTH = DEFAULT_AUTH
OAUTH_CLIENT_KEY_OR_ID = None
OAUTH_CLIENT_SECRET = None
OAUTH_CLIENT_NAME = None
CONFIG_UID = None
CONFIG_PWD = None
CONFIG_TEAM = None
SLACK_API_TOKEN = None
SLACK_CHANNEL = None
BACKUP_ALL_BRANCHES = DEFAULT_BACKUP_ALL_BRANCHES
BACKUP_ROOT_DIRECTORY = DEFAULT_BACKUP_ROOT_DIRECTORY
BACKUP_MAX_RETRIES = DEFAULT_BACKUP_MAX_RETRIES
BACKUP_MAX_FAILS = DEFAULT_BACKUP_MAX_FAILS
BACKUP_MIN_FREESPACE_GIGA = DEFAULT_BACKUP_MIN_FREESPACE_GIGA
BACKUP_STORE_DAYS = DEFAULT_BACKUP_STORE_DAYS
LOG_OUTPUT = DEFAULT_LOG_OUTPUT
LOG_COLORIZED = DEFAULT_LOG_COLORIZED
# CREATE FRESH CONFIG FROM SCRATCH
configuration_export()
return
else:
printstyled( 'CONFIG I/O: READING... {}'.format( CONFIG_FILE_PATH ), 'cyan' )
config_file = ConfigParser( allow_no_value=True )
try:
config_file.read( CONFIG_FILE_PATH )
except Exception as e:
printstyled( 'CONFIG I/O: No config \'{}\' found or unreadable.\n Error: {}'.format( CONFIG_FILE_PATH, e ), 'red' )
return
# READ VALUES
try:
AUTH = config_file.get( 'authorization', 'auth_method' )
OAUTH_CLIENT_KEY_OR_ID = config_file.get( 'bitbucket_oauth', 'key_or_id' )
OAUTH_CLIENT_SECRET = config_file.get( 'bitbucket_oauth', 'secret' )
OAUTH_CLIENT_NAME = config_file.get( 'bitbucket_oauth', 'app_name' )
CONFIG_UID = config_file.get( 'bitbucket_account', 'userid' )
CONFIG_PWD = config_file.get( 'bitbucket_account', 'password' )
CONFIG_TEAM = config_file.get( 'bitbucket_account', 'teamname' )
SLACK_API_TOKEN = config_file.get( 'slack', 'api_token' )
SLACK_CHANNEL = config_file.get( 'slack', 'channel_to_post' )
BACKUP_ALL_BRANCHES = config_file.get( 'backup', 'all_branches' )
BACKUP_ROOT_DIRECTORY = config_file.get( 'backup', 'filepath' )
BACKUP_MAX_RETRIES = config_file.getint( 'backup', 'max_retries' )
BACKUP_MAX_FAILS = config_file.getint( 'backup', 'max_fails' )
BACKUP_MIN_FREESPACE_GIGA = config_file.getint( 'backup', 'min_free_space' )
BACKUP_STORE_DAYS = config_file.getint( 'backup', 'amount_of_days_to_store' )
LOG_OUTPUT = config_file.getboolean( 'log', 'logging_on' )
LOG_COLORIZED = config_file.getboolean( 'log', 'colorized_logging_on' )
except Exception as e:
printstyled( 'CONFIG I/O: Config \'{}\' was missing correct values.\n Error: {}'.format( CONFIG_FILE_PATH, e ), 'red' )
return
printstyled( 'CONFIG I/O: Config \'{}\' succesfully imported.'.format( CONFIG_FILE_PATH ), 'green' )
def configuration_stringify( value ):
if value == None:
return ""
else:
return "{}".format( value )
def configuration_export():
CONFIG_FILE_PATH = APP_PATH+'/'+APP_CONFIG_FILE
config_file = ConfigParser( allow_no_value=True )
# STORE authorization method
config_file.add_section( 'authorization' )
config_file.set( 'authorization', '; ENTER WHICH AUTH METHOD TO USE \'oauth\' OR \'uidpwd\'' )
config_file.set( 'authorization', '; YOU SHOULD CHOOSE \'oauth\' AND REMOVE THE PASSWORD FOR \'bitbucket_account\'' )
config_file.set( 'authorization', 'auth_method', configuration_stringify( AUTH ) )
# STORE oauth
config_file.add_section( 'bitbucket_oauth' )
config_file.set( 'bitbucket_oauth', '; ENTER OAUTH 2.0 CREDENTIALS HERE (RECOMMENDED!)' )
config_file.set( 'bitbucket_oauth', 'key_or_id', configuration_stringify( OAUTH_CLIENT_KEY_OR_ID ) )
config_file.set( 'bitbucket_oauth', 'secret', configuration_stringify( OAUTH_CLIENT_SECRET ) )
config_file.set( 'bitbucket_oauth', 'app_name', configuration_stringify( OAUTH_CLIENT_NAME ) )
# STORE account
config_file.add_section( 'bitbucket_account' )
config_file.set( 'bitbucket_account', '; ENTER YOUR CREDENTIALS FOR BITBUCKET HERE, USE SAME FOR USER AND TEAM IF YOU WANT USER' )
config_file.set( 'bitbucket_account', '; PASSWORD IS ONLY NEEDED IF \'authorization\' USES \'uidpwd\' (NOT RECOMMENDED!)' )
config_file.set( 'bitbucket_account', 'userid', configuration_stringify( CONFIG_UID ) )
config_file.set( 'bitbucket_account', 'password', configuration_stringify( CONFIG_PWD ) )
config_file.set( 'bitbucket_account', 'teamname', configuration_stringify( CONFIG_TEAM ) )
# STORE slack
config_file.add_section( 'slack' )
config_file.set( 'slack', '; ENTER API-TOKEN AND THE CHANNEL NAME WHERE TO POST MESSAGES TO HERE' )
config_file.set( 'slack', 'api_token', configuration_stringify( SLACK_API_TOKEN ) )
config_file.set( 'slack', 'channel_to_post', configuration_stringify( SLACK_CHANNEL ) )
# STORE backup
config_file.add_section( 'backup' )
config_file.set( 'backup', '; ENTER BACKUP RELATED PARAMETERS HERE, I.E. FILEPATH TO DIRECTORY WHERE TO STORE BACKUPS' )
config_file.set( 'backup', 'backup_all_branches', configuration_stringify( BACKUP_ALL_BRANCHES ))
config_file.set( 'backup', 'filepath', configuration_stringify( BACKUP_ROOT_DIRECTORY ) )
config_file.set( 'backup', 'max_retries', configuration_stringify( BACKUP_MAX_RETRIES ) )
config_file.set( 'backup', 'max_fails', configuration_stringify( BACKUP_MAX_FAILS ) )
config_file.set( 'backup', 'min_free_space', configuration_stringify( BACKUP_MIN_FREESPACE_GIGA ) )
config_file.set( 'backup', 'amount_of_days_to_store', configuration_stringify( BACKUP_STORE_DAYS ) )
# STORE log
config_file.add_section( 'log' )
config_file.set( 'log', '; ENTER LOG RELATED OPTIONS AS True AND FALSE' )
config_file.set( 'log', 'logging_on', configuration_stringify( LOG_OUTPUT ) )
config_file.set( 'log', 'colorized_logging_on', configuration_stringify( LOG_COLORIZED ) )
printstyled( 'CONFIG I/O: WRITING... {}'.format( CONFIG_FILE_PATH ), 'cyan' )
try:
with open( CONFIG_FILE_PATH, 'w' ) as file_to_write:
config_file.write( file_to_write )
except Exception as e:
printstyled( 'CONFIG I/O: Failed to save config \'{}\'.\n Error: {}'.format( CONFIG_FILE_PATH, e ), 'red' )
return
'''
**********************************
*** SLACK
**********************************
'''
# SLACK COMMUNICATION
def slack_send_message_to_channel( message, channel ):
global SLACK_API_TOKEN
if not notify_mode:
if log_mode:
if SLACK_API_TOKEN:
printstyled( 'SLACK: SUPRESSING NOTIFICATION\n>>>\n' + message + '\n<<<', 'white' )
return
if SLACK_API_TOKEN == None:
printstyled( 'SLACK: MISSING API TOKEN', 'red' )
else:
if message:
printstyled( 'SLACK: SENDING MESSAGE \'{}\''.format( message ), 'cyan' )
client = None
try:
client = slack.WebClient( token = SLACK_API_TOKEN, timeout=60 )
except Exception as e:
printstyled( 'SLACK: API EXCEPTION {}'.format( e ), 'red' )
if not channel:
channel = '#random'
if client:
try:
response = client.chat_postMessage( channel=channel,text=message, link_names=True, mrkdwn=True )
printstyled( 'SLACK: MESSAGE WAS SENT.', 'green' )
except SlackApiError as e:
printstyled( 'SLACK: API CONNECTION ERROR. EXCEPTION: {}'.format( e ), 'red' )
else:
printstyled( 'SLACK: MESSAGE NOT SENT.', 'red' )
else:
printstyled( 'SLACK: NO MESSAGE TO SEND.', 'red' )
# CONVENIENCE MESSAGE
def slack_send_message_of_category( message, category=None ):
if not message:
return
message_prefix = None
if category == 'fail':
message_prefix = '⛔️ FAIL' + ' ' + SLACK_TO_CHANNEL + ' '
elif category == 'warn':
message_prefix = '⚠️ WARNING'
elif category == 'ok':
message_prefix = '✅ OK'
elif category == 'info':
message_prefix = '🌐 INFO'
else:
message_prefix = None
if message_prefix:
message = message_prefix + '\n' + message
slack_send_message_to_channel( message, SLACK_CHANNEL )
def slack_selftest():
slack_send_message_of_category( 'Nachrichtentest' )
slack_send_message_of_category( 'Nachrichtentest Failed', 'fail' )
slack_send_message_of_category( 'Nachrichtentest Warning', 'warn' )
slack_send_message_of_category( 'Nachrichtentest Okay', 'ok' )
slack_send_message_of_category( 'Nachrichtentest Information', 'info' )
# CHECK SLACK CONFIG
def slack_config_load( should_ask = True ):
global SLACK_API_TOKEN, SLACK_CHANNEL
ring = None
try:
ring = keyring.get_keyring()
SLACK_API_TOKEN = ring.get_password( CRED_KEY_SERVICE, CRED_KEY_SLACK_TOKEN )
SLACK_CHANNEL = ring.get_password( CRED_KEY_SERVICE, CRED_KEY_SLACK_CHANNEL )
except KeyringLocked:
printstyled( 'SLACK: CONFIG NOT AVAILABLE. KEYRING IS LOCKED!', 'red' )
exit_with_code( 12, "Slack API tokens could not be read from secure credential store." )
except InitError:
exit_with_code( 13 )
if not should_ask:
return
if SLACK_API_TOKEN == None or SLACK_CHANNEL == None:
printstyled( 'SLACK: CONFIG NOT FOUND.', 'red' )
if is_running_interactively() and slackconfig:
print( "--- PLEASE ENTER SLACK CHANNEL AND API TOKEN NOW ---" )
print( "--- (WILL BE STORED IN SECURE KEYRING INFRASTRUCTURE.) ---" )
input_token = input( termcolor.BLUE + "API TOKEN: " + termcolor.ENDC )
input_channel = input( termcolor.BLUE + " CHANNEL: " + termcolor.ENDC )
if input_token and input_channel:
ring.set_password( CRED_KEY_SERVICE, CRED_KEY_SLACK_TOKEN, input_token )
SLACK_API_TOKEN = input_token
ring.set_password( CRED_KEY_SERVICE, CRED_KEY_SLACK_CHANNEL, input_channel )
SLACK_CHANNEL = input_channel
printstyled( 'SLACK: SUCCESS, CONFIG STORED.', 'green' )
else:
printstyled( 'SLACK: FAIL, COULD NOT STORE CONFIG.', 'red' )
exit_with_code( 4, 'Slack credential could not be saved.' )
else:
if slackconfig:
exit_with_code( 4, 'Missing credentials could not be requested interactively, because script not running in tty/shell context.' )
else:
printstyled( 'SLACK: CONFIGURED.', 'green' )
def slack_config_reset():
global SLACK_API_TOKEN, SLACK_CHANNEL
printstyled( 'SLACK: RESETTING...', 'cyan' )
ring = None
try:
ring = keyring.get_keyring()
except KeyringLocked:
exit_with_code( 12 )
except InitError:
exit_with_code( 13 )
try:
ring.delete_password( CRED_KEY_SERVICE, CRED_KEY_SLACK_CHANNEL )
ring.delete_password( CRED_KEY_SERVICE, CRED_KEY_SLACK_TOKEN )
SLACK_API_TOKEN = None
SLACK_CHANNEL = None
printstyled( 'SLACK: REMOVED.', 'cyan' )
except:
printstyled( 'SLACK: NO CREDENTIALS TO REMOVE.', 'red' )
slack_config_load()
'''
**********************************
*** OAUTH CREDENTIALS
**********************************
'''
# CHECK OAUTH 2 CONFIG
def oauth_config_load( should_ask = True ):
global OAUTH_CLIENT_NAME, OAUTH_CLIENT_KEY_OR_ID, OAUTH_CLIENT_SECRET
ring = None
try:
ring = keyring.get_keyring()
OAUTH_CLIENT_NAME = ring.get_password( CRED_KEY_SERVICE, CRED_KEY_OAUTH_NAME )
OAUTH_CLIENT_KEY_OR_ID = ring.get_password( CRED_KEY_SERVICE, CRED_KEY_OAUTH_KEY )
OAUTH_CLIENT_SECRET = ring.get_password( CRED_KEY_SERVICE, CRED_KEY_OAUTH_SECRET )
except KeyringLocked:
printstyled( 'OAUTH: NOT AVAILABLE. KEYRING IS LOCKED!', 'red' )
exit_with_code( 12, "Bitbucket OAuth 2.0 config could not be read from secure credential store." )
except InitError:
exit_with_code( 13 )
if not should_ask:
return
if OAUTH_CLIENT_NAME == None or OAUTH_CLIENT_KEY_OR_ID == None or OAUTH_CLIENT_SECRET == None:
printstyled( 'OAUTH: CONFIG NOT FOUND.', 'red' )
if is_running_interactively():
print( "--- PLEASE ENTER OAUTH NAME/KEY/SECRET FOR BITBUCKET ---" )
print( "--- (WILL BE STORED IN SECURE KEYRING INFRASTRUCTURE.) ---" )
input_key = input( termcolor.BLUE + " OAUTH KEY: " + termcolor.ENDC )
input_secret = input( termcolor.BLUE + " OAUTH SECRET: " + termcolor.ENDC )
input_name = input( termcolor.BLUE + "OAUTH APP NAME: " + termcolor.ENDC )
if input_name and input_key and input_secret:
ring.set_password( CRED_KEY_SERVICE, CRED_KEY_OAUTH_NAME, input_name )
OAUTH_CLIENT_NAME = input_name
ring.set_password( CRED_KEY_SERVICE, CRED_KEY_OAUTH_KEY, input_key )
OAUTH_CLIENT_KEY_OR_ID = input_key
ring.set_password( CRED_KEY_SERVICE, CRED_KEY_OAUTH_SECRET, input_secret )
OAUTH_CLIENT_SECRET = input_secret
printstyled( 'OAUTH: SUCCESS, CONFIG STORED.', 'green' )
else:
printstyled( 'OAUTH: FAIL, COULD NOT STORE CONFIG.', 'red' )
exit_with_code( 6, 'OAuth 2.0 credentials could not be saved.' )
else:
if oauthconfig:
exit_with_code( 6, 'Missing OAuth 2.0 credentials could not be requested interactively, because script not running in tty/shell context.' )
else:
printstyled( 'OAUTH: CONFIGURED.', 'green' )
def oauth_config_reset():
global OAUTH_CLIENT_NAME, OAUTH_CLIENT_KEY_OR_ID, OAUTH_CLIENT_SECRET
printstyled( 'OAUTH: RESETTING...', 'cyan' )
ring = None
try:
ring = keyring.get_keyring()
except KeyringLocked:
exit_with_code( 12 )
except InitError:
exit_with_code( 13 )
try:
ring.delete_password( CRED_KEY_SERVICE, CRED_KEY_OAUTH_NAME )
ring.delete_password( CRED_KEY_SERVICE, CRED_KEY_OAUTH_KEY )
ring.delete_password( CRED_KEY_SERVICE, CRED_KEY_OAUTH_SECRET )
OAUTH_CLIENT_NAME = None
OAUTH_CLIENT_KEY_OR_ID = None
OAUTH_CLIENT_SECRET = None
printstyled( 'OAUTH: REMOVED.', 'cyan' )
except:
printstyled( 'OAUTH: NO CREDENTIALS TO REMOVE.', 'red' )
oauth_config_load()
'''
**********************************
*** BITBUCKET
**********************************
'''
# CHECKS IF VALID CREDENTIALS ARE STORED IN SECURE STORAGE
def bitbucket_config_load( should_ask = True ):
global CONFIG_UID, CONFIG_PWD, CONFIG_TEAM
ring = None
try:
ring = keyring.get_keyring()
CONFIG_UID = ring.get_password( CRED_KEY_SERVICE, CRED_KEY_UID )
CONFIG_PWD = ring.get_password( CRED_KEY_SERVICE, CRED_KEY_PWD )
CONFIG_TEAM = ring.get_password( CRED_KEY_SERVICE, CRED_KEY_TEAM )
except KeyringLocked:
printstyled( 'BITBUCKET: CONFIG NOT AVAILABLE. KEYRING IS LOCKED!', 'red' )
exit_with_code( 12, "Bitbucket credentials could not be read from secure credential store." )
except InitError:
exit_with_code( 13 )
if not should_ask:
return
if CONFIG_UID == None or CONFIG_PWD == None:
printstyled( 'BITBUCKET: NOT CONFIGURED.', 'red' )
if is_running_interactively():
print( "--- PLEASE ENTER CREDENTIALS FOR BITBUCKET ACCOUNT NOW ---" )
print( "--- (WILL BE STORED IN SECURE KEYRING INFRASTRUCTURE.) ---" )
input_uid = input( termcolor.BLUE + " BitBucket USER ID: " + termcolor.ENDC )
input_password = getpass( prompt=termcolor.BLUE + " BitBucket PASSWORD: " + termcolor.ENDC )
input_team = input( termcolor.BLUE + " BitBucket TEAM ID: " + termcolor.ENDC )
if input_uid and input_password:
ring.set_password( CRED_KEY_SERVICE, CRED_KEY_UID, input_uid )
CONFIG_UID = input_uid
ring.set_password( CRED_KEY_SERVICE, CRED_KEY_PWD, input_password )
CONFIG_PWD = input_password
if input_team:
ring.set_password( CRED_KEY_SERVICE, CRED_KEY_TEAM, input_team )
CONFIG_TEAM = input_team
printstyled( 'BITBUCKET: SUCCESS, CONFIG STORED.', 'green' )
else:
printstyled( 'BITBUCKET: FAIL, CONFIG COULD NOT BE STORED.', 'red' )
exit_with_code( 2, 'Credentials could not be saved.' )
else:
exit_with_code( 2, 'Missing credentials could not be requested interactively, because script not running in tty/shell context.' )
else:
printstyled( 'BITBUCKET: CONFIGURED.', 'green' )
# REMOVES ALL STORED CREDENTIALS FROM SECURE STORAGE
def bitbucket_config_reset():
printstyled( 'BITBUCKET: RESETTING CONFIG...', 'cyan' )
ring = None
try:
ring = keyring.get_keyring()
except InitError:
printstyled( 'BITBUCKET: UNABLE TO RESET CONFIG.', 'red' )
exit_with_code( 13 )
try:
ring.delete_password( CRED_KEY_SERVICE, CRED_KEY_UID )
ring.delete_password( CRED_KEY_SERVICE, CRED_KEY_PWD )
ring.delete_password( CRED_KEY_SERVICE, CRED_KEY_TEAM )
CONFIG_UID = None
CONFIG_PWD = None
CONFIG_TEAM = None
printstyled( 'BITBUCKET: CONFIG REMOVED.', 'cyan' )
except:
printstyled( 'BITBUCKET: NO CREDENTIALS TO REMOVE.', 'red' )
bitbucket_config_load()
'''
**********************************
*** REPO STATUS HANDLING
**********************************
'''
def repo_status_is( repo_path, status ):
filename_status = "{}.{}".format( repo_path, status )
return os.path.exists( filename_status )
def repo_status_set( repo_path, status, content ):
filename_status = "{}.{}".format( repo_path, status )
if os.path.exists( filename_status ):
os.remove( filename_status )
if content == None:
content = status
write_file( filename_status, content )
def mark_repo_sync( repo_path, content=None ):
mark_repo_clear( repo_path )
repo_status_set( repo_path, STATUS_SYNC, content )
printstyled( "REPO SYNC: {}".format( repo_path ), 'yellow' )
# step 1: check if a syncing-tag exists
# step 2: if yes, remove it and remove the incomplete git repo (we will retry a full backup any way)
# step 3: if no, create a syncing-tag
return
def mark_repo_done( repo_path, content=None ):
mark_repo_clear( repo_path )
repo_status_set( repo_path, STATUS_DONE, content )
printstyled( "REPO DONE: {}".format( repo_path ), 'green' )
# step 1: remove existing syncing-tag
# step 2: add complete-tag
return
def mark_repo_fail( repo_path, content=None ):
mark_repo_clear( repo_path )
repo_status_set( repo_path, STATUS_FAIL, content )
printstyled( "REPO FAIL: {}".format( repo_path ), 'red' )
# step 1: remove syncing-tag
# step 2: add failed-tag
return
def mark_repo_clear( repo_path ):
filename_sync = "{}.{}".format( repo_path, STATUS_SYNC )
filename_done = "{}.{}".format( repo_path, STATUS_DONE )
filename_fail = "{}.{}".format( repo_path, STATUS_FAIL )
files = {filename_sync, filename_done, filename_fail}
for current_file in files:
if os.path.exists( current_file ):
os.remove( current_file )
'''
**********************************
*** BACKUP
**********************************
'''
def backup_archive_system_stats():
BACKUP_LOCAL_PATH = os.path.abspath( os.path.join( BACKUP_ROOT_DIRECTORY, BACKUP_ARCHIVE_DIRECTORY ) )
size_of_directory = get_size( BACKUP_LOCAL_PATH )
string_dirsize = 'Storage size used by backup: {}'.format( sizeof_fmt( size_of_directory ) )
size_remaining = get_fs_freespace( BACKUP_ROOT_DIRECTORY )
string_freespace = 'Storage size available on volume: {}'.format( sizeof_fmt( size_remaining ) )
size_of_root_directory = get_size( BACKUP_ROOT_DIRECTORY )
string_rootsize = 'Storage size used over ALL backups: {}'.format( sizeof_fmt( size_of_root_directory ) )
return string_dirsize + '\n' + string_freespace + '\n' + string_rootsize
# returns datetime of last run based on stored JSON datetime object
def backup_archive_datetime_lastrun():
t = None
try:
with open( BACKUP_LASTRUN_FILE, 'r' ) as json_file:
lastrun = json.load( json_file )
json_file.close()
t = datetime( year=lastrun['year'], month=lastrun['month'],day=lastrun['day'],hour=lastrun['hour'],minute=lastrun['minute'],second=lastrun['second'] )
printstyled( 'LASTRUN: WAS AT {}'.format( str( t ) ), 'green' )
except Exception as e:
printstyled( 'LASTRUN: NOT AVAILABLE. {}'.format( e ), 'red' )
return t
def backup_archive_num_of_repos_lastrun():
num_of_repos = None
try:
with open( BACKUP_LASTRUN_FILE, 'r' ) as json_file:
lastrun = json.load( json_file )
json_file.close()
num_of_repos = int( lastrun['num_of_repos'] )
printstyled( 'LASTRUN: NUM OF REPOS WAS {}'.format( str( num_of_repos ) ), 'green' )
except Exception as e:
printstyled( 'LASTRUN: NUM OF REPOS NOT AVAILABLE. {}'.format( e ), 'red' )
return num_of_repos
# save the date and time the last successful backup was completed
# this is needed to detect issues of system clock/date/timezone
# to not accidentially delete valid backups
def backup_archive_save_lastrun( num_of_repos, size_of_repos):
t = datetime.now().utcnow()
lastrun = {
'year' : t.year,
'month' : t.month,
'day' : t.day,
'hour' : t.hour,
'minute' : t.minute,
'second' : t.second,
'num_of_repos' : num_of_repos,
'size_of_repos' : size_of_repos,
}
with open( BACKUP_LASTRUN_FILE, 'w' ) as json_file:
json.dump( lastrun, json_file )
json_file.close()
# check if we can safely operate with the provided datetime by the operating system
def backup_archive_has_valid_time_context():
past = backup_archive_datetime_lastrun()
if not past: # no last run available, thus no valid context
return False
present = datetime.now().utcnow()
if present < past: # present MUST always be greater than past to have valid context
return False
return True
# GENERATE NEW TIMESTAMPED BACKUP DIRECTORY NAME, e.g. BACKUP_20190513_UTC
def backup_archive_name_for_datetime_utc( timestamp_utc ):
global BACKUP_ARCHIVE_PREFIX, BACKUP_ARCHIVE_SUFFIX, BACKUP_ARCHIVE_NAME
if not timestamp_utc:
timestamp_utc = datetime.now().utcnow()
return BACKUP_ARCHIVE_PREFIX+"_"+str(timestamp_utc.year)+str(timestamp_utc.month).zfill(2)+str(timestamp_utc.day).zfill(2)+"_"+BACKUP_ARCHIVE_SUFFIX
# +"_"+str(now.hour).zfill(2)+str(now.minute).zfill(2)
# check existence
def backup_archive_exists_with_name( directory_name ):
if not directory_name:
return False
BACKUP_LOCAL_PATH = os.path.abspath( os.path.join( BACKUP_ROOT_DIRECTORY, directory_name ) )
return os.path.exists( BACKUP_LOCAL_PATH )
def backup_archive_rotate_with_days( days_into_past_keep, days_into_past_scope ):
printstyled( 'ROTATION: VACUUMING OLD BACKUPS ...', 'magenta' )
current_day = datetime.now().utcnow()
oneday = timedelta( days=1 )
i = 0
while i < days_into_past_scope:
current_day = current_day - oneday
current_archive_name = backup_archive_name_for_datetime_utc( current_day )
should_remove = ( i + 1 > days_into_past_keep )
if backup_archive_exists_with_name( current_archive_name ):
printstyled( 'ROTATION: BACKUP EXISTS: {}; SHOULD DELETE == {}'.format( current_archive_name, str(should_remove) ), 'green', 'bold' )
if should_remove: # REMOVE(!!!) complete backupfolder
printstyled( 'ROTATION: DESTROYING {}'.format( current_archive_name ), 'magenta', 'bold' )
BACKUP_LOCAL_PATH = os.path.abspath( os.path.join( BACKUP_ROOT_DIRECTORY, current_archive_name ) )
delete_dir( BACKUP_LOCAL_PATH )
else:
printstyled( 'ROTATION: BACKUP NOT EXISTING: {}; SHOULD DELETE == {}'.format( current_archive_name, str(should_remove) ), 'red', 'bold' )
i += 1
printstyled( 'ROTATION: VACUUMING COMPLETED.', 'magenta' )
return
def backup_archive_days_archived( days_into_past_keep ):
current_day = datetime.now().utcnow()
oneday = timedelta( days=1 )
num_stored_archives = 0
i = 0
current_day = current_day + oneday
while i < ( days_into_past_keep + 1 ):
current_day = current_day - oneday
current_archive_name = backup_archive_name_for_datetime_utc( current_day )
if backup_archive_exists_with_name( current_archive_name ):
num_stored_archives += 1
i += 1
return num_stored_archives
'''
**********************************
*** BITBUCKET & API & OAUTH HELPERS
**********************************
'''
# OAUTH 2.0 SUPPORT/HELPERS
def bitbucket_api_oauth2_token():
global OAUTH_CLIENT_NAME, OAUTH_CLIENT_KEY_OR_ID, OAUTH_CLIENT_SECRET
printstyled( "BITBUCKET: Fetching OAuth 2.0 Token... ", 'magenta' )
bitbucket_service = OAuth2Service(
client_id = OAUTH_CLIENT_KEY_OR_ID,
client_secret = OAUTH_CLIENT_SECRET,
name = OAUTH_CLIENT_NAME,
authorize_url = OAUTH_URL_AUTORIZE,
access_token_url = OAUTH_URL_ACCESS_TOKEN,
base_url = API_V2_ROOT)
data = { 'code':'bar', 'grant_type':'client_credentials', 'redirect_uri':'http://127.0.0.1/' }
session = bitbucket_service.get_auth_session( data=data, decoder=json.loads )
if session.access_token:
printstyled( 'BITBUCKET: Received OAuth 2.0 Token: {}'.format( session.access_token ), 'magenta' )
else:
printstyled( 'BITBUCKET: ERROR, no OAuth 2.0 Token received.', 'red' )
return session.access_token
def bitbucket_api_oauth2_header_with_token( oauth_token ):
bearer_token = 'Bearer {}'.format( oauth_token )
header = { 'Authorization': bearer_token }
return header
# FETCH LIST OF REPOSITORIES (API 1.0)
def bitbucket_api_get_repos_10( username, password, team ):
bitbucket_endpoint_repos = API_V1_ROOT + API_V1_USERS
raw_request = None
if AUTH == AUTH_METHOD_UIDPWD:
raw_request = requests.get( bitbucket_endpoint_repos + team, auth = HTTPBasicAuth( username, password ) )
elif AUTH == AUTH_METHOD_OAUTH2:
oauth_token = bitbucket_api_oauth2_token()
raw_request = requests.get( bitbucket_endpoint_repos + team, headers = bitbucket_api_oauth2_header_with_token( oauth_token ) )
dict_request = None
repos = None
statuscode = None
try:
statuscode = raw_request.status_code
dict_request = json.loads( raw_request.content.decode('utf-8') )
repos = dict_request['repositories']
except Exception as e:
error_msg = 'BITBUCKET: CONNECTION FAILED. — HTTP STATUS CODE: {}'.format( str(statuscode) )
printstyled( error_msg, 'red' )
if backup:
slack_send_message_of_category( error_msg, 'fail' )
raw_request.raise_for_status()
return repos
def bitbucket_api_get_repos_20_oauth( username, password, team ):
if not username or not team:
exit_with_code( 2 )
bitbucket_endpoint_repos = 'https://api.bitbucket.org/2.0/' + API_V2_REPOSITORIES + team + '/?'+ API_V2_PARAM_ROLE
# GET OVERVIEW OF HOW MANY REPOS AND PAGES TO FETCH...
dict_request = None
repos = []
statuscode = None
oauth_token = bitbucket_api_oauth2_token()
printstyled( "BITBUCKET: Fetching list of repos (OAUTH)... "+bitbucket_endpoint_repos, 'green' )
try:
raw_request = requests.get( bitbucket_endpoint_repos, headers = bitbucket_api_oauth2_header_with_token( oauth_token ) )
statuscode = raw_request.status_code
except Exception as e:
error_msg = 'BITBUCKET: CONNECTION FAILED. — HTTP STATUS CODE: {}'.format( str(statuscode) )
printstyled( error_msg, 'red' )
if backup:
slack_send_message_of_category( error_msg, 'fail' )