Skip to content

Commit c4a1b7e

Browse files
committed
Changed logging format
1 parent ac12ba6 commit c4a1b7e

File tree

9 files changed

+93
-72
lines changed

9 files changed

+93
-72
lines changed

.gitignore

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,4 +131,6 @@ dmypy.json
131131

132132
# Project-specific
133133
.lock
134-
.idea
134+
.idea
135+
/shelf/
136+
/workspace.xml

.idea/.gitignore

Lines changed: 0 additions & 3 deletions
This file was deleted.

config.yml

Lines changed: 0 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,56 +1,39 @@
11
config:
2-
32
grafana:
43

54
# URL of the target grafana-server.
65
url: localhost:3000
7-
86
# User account name with admin rights on target grafana-server.
97
user: admin
10-
118
# Password of account with admin rights on target grafana-server.
129
password: admin
1310

1411
ldap:
15-
1612
# Set to True if NTLM should be used for LDAP.
1713
useNTLM: True
18-
1914
# If True, SSL will be used for connection to LDAP.
2015
useSSL: False
21-
2216
# URL of the source LDAP-Server.
2317
url: ldap.forumsys.com
24-
2518
# Port of the ldap instance provided in the url-variable.
2619
port: 389
27-
2820
# Group search-base of the source LDAP-Server.
2921
groupSearchBase: dc=example,dc=com
30-
3122
# Filter that should be used for the group search.
3223
groupSearchFilter:
33-
3424
# Search-Base for user objects on the LDAP-Server.
3525
userSearchBase: dc=example,dc=com
36-
3726
# Filter that should be used for user searches.
3827
userSearchFilter:
39-
4028
# Attribute name under which the members of a group object can be found.
4129
memberAttributeName: uniqueMember
42-
4330
# Name of the attribute which should be used as login in grafana.
4431
userLoginAttribute: uid
45-
4632
# Name of the attribute which should be used as Name in grafana.
4733
userNameAttribute: cn
48-
4934
# Name of the attribute which should be used as mail in grafana.
5035
userMailAttribute: mail
51-
5236
# Login for the LDAP-Server.
5337
login: test\cn=read-only-admin,dc=example,dc=com
54-
5538
# Password for the LDAP-Server.
5639
password: password

run.py

Lines changed: 44 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,42 @@
1-
from script.core import export
1+
from script.core import startUserSync
22
import argparse
3+
import logging
4+
5+
class DispatchingFormatter:
6+
def __init__(self, formatters, default_formatter):
7+
self._formatters = formatters
8+
self._default_formatter = default_formatter
9+
10+
def format(self, record):
11+
formatter = self._formatters.get(record.name, self._default_formatter)
12+
return formatter.format(record)
13+
14+
def setup_logger():
15+
"""
16+
Setting up the used logger. The 'mutate' logger will print whether dry-run is used and changes are being applied.
17+
"""
18+
log_format = '%(asctime)s - %(levelname)s - %(module)7s - %(message)s'
19+
log_format_mut = log_format
20+
21+
if args.dry_run:
22+
log_format_mut = '%(asctime)s - %(levelname)s - %(module)7s - [SKIPPED] %(message)s'
23+
else:
24+
log_format_mut = log_format
25+
26+
27+
logger = logging.getLogger()
28+
while logger.handlers:
29+
logger.handlers.pop()
30+
31+
formatter = DispatchingFormatter({
32+
'mutate': logging.Formatter(log_format_mut),
33+
},
34+
logging.Formatter(log_format)
35+
)
36+
handler = logging.StreamHandler()
37+
handler.setFormatter(formatter)
38+
logger.setLevel(logging.INFO)
39+
logger.addHandler(handler)
340

441
if __name__ == "__main__":
542
parser = argparse.ArgumentParser(description='Process config path')
@@ -10,4 +47,9 @@
1047
'changes are printed to the console.',
1148
action='store_true')
1249
args = parser.parse_args()
13-
export(args.config_path, args.bind, args.dry_run)
50+
51+
# setup the logger
52+
setup_logger()
53+
54+
# starts the sync process
55+
startUserSync(args.config_path, args.bind, args.dry_run)

script/core.py

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,7 @@
88
from requests.exceptions import ConnectionError
99
from .config import *
1010

11-
logging.basicConfig(level=logging.INFO)
12-
logger = logging.getLogger("grafana-ldap-sync-script")
11+
logger = logging.getLogger()
1312

1413
PERMISSION_MAP = {
1514
"View": 1,
@@ -237,26 +236,39 @@ def remove_unused_items(team_mappings):
237236
delete_unmapped_users(team_mappings)
238237

239238

240-
def export(config_path, bind, dry_run):
239+
def startUserSync(config_path, bind, dry_run):
241240
"""
242241
Checks if a .lock file is currently present. If no .lock file is present, the updating of the grafana teams,
243242
folders and users is performed.
244243
If a .lock file is present, no action is performed.
245244
"""
246245
global configuration
247246
if lock():
248-
logger.info("Starting task...")
249247
try:
248+
logger.info("=================================================")
249+
logger.info("Starting user synchronization...")
250+
250251
configuration = config(config_path)
252+
251253
configuration.DRY_RUN = dry_run
252254
if configuration.DRY_RUN:
253-
print("dryRun enabled: Changes will not be applied!")
255+
logger.info("!! DryRun enabled: Changes will not be applied !!")
256+
257+
logger.info("=================================================")
258+
259+
logger.info("Setting up the connection to the Grafana server..")
254260
setup_grafana(configuration)
261+
logger.info("Setting up the connection to the LDAP server..")
255262
setup_ldap(configuration)
263+
logger.info("Reading the user and team mappings..")
256264
mapping = read_mapping_from_csv(bind)
265+
logger.info("Updating the Grafana teams..")
257266
update_teams(mapping["teams"])
267+
logger.info("Updating the Grafana folders..")
258268
update_folders(mapping["folders"])
269+
logger.info("Removing unused teams and users..")
259270
remove_unused_items(mapping["teams"])
271+
260272
logger.info("Task finished successfully!")
261273
except LDAPSocketOpenError:
262274
logger.error("Task aborted, unable to reach LDAP-Server.")

script/grafana.py

Lines changed: 24 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,13 @@
22
from grafana_api.grafana_face import GrafanaFace
33
from .config import *
44
from .helpers import *
5+
import logging
56

67
grafana_api = ""
78
configuration = ""
89

9-
logging.basicConfig(level=logging.INFO)
10-
logger = logging.getLogger("grafana-ldap-sync-script")
10+
logger = logging.getLogger()
11+
logger_mut = logging.getLogger("mutate")
1112

1213
def setup_grafana(config_dict):
1314
global grafana_api, configuration
@@ -27,10 +28,8 @@ def delete_team_by_name(name):
2728
team_data = grafana_api.teams.get_team_by_name(name)
2829
if len(team_data) > 0:
2930
for data_set in team_data:
30-
if configuration.DRY_RUN:
31-
logger.info("Would have deleted team with name: %s and id: %s" % (name, data_set["id"]))
32-
else:
33-
logger.info("Deleting team with name %s and id %s" % (name, data_set["id"]))
31+
logger_mut.info("Deleting team with name %s and id %s" % (name, data_set["id"]))
32+
if not configuration.DRY_RUN:
3433
grafana_api.teams.delete_team(data_set["id"])
3534
return True
3635
return False
@@ -43,10 +42,8 @@ def create_team(name, mail):
4342
:param mail: The mail of the team.
4443
:return: The API response.
4544
"""
46-
if configuration.DRY_RUN:
47-
logger.info("Would have created team with name: %s" % name)
48-
else:
49-
logger.info("Creating team with name %s" % name)
45+
logger_mut.info("Creating team with name %s" % name)
46+
if not configuration.DRY_RUN:
5047
return grafana_api.teams.add_team({
5148
"name": name,
5249
"mail": mail
@@ -61,12 +58,10 @@ def create_user_with_random_pw(user):
6158
user_dict = dict(user)
6259
user_dict["password"] = get_random_alphanumerical()
6360
user_dict["OrgId"] = 1
64-
if configuration.DRY_RUN:
65-
logger.info("Would have created user with json %s" % str(user_dict))
66-
else:
67-
logger.info("Creating user with login %s, name %s and mail %s" %
68-
(user_dict["login"], user_dict["name"], user_dict["email"])
69-
)
61+
62+
logger_mut.info("Creating user with login %s, name %s and mail %s" % (user_dict["login"], user_dict["name"], user_dict["email"]))
63+
64+
if not configuration.DRY_RUN:
7065
grafana_api.admin.create_user(user_dict)
7166

7267

@@ -76,11 +71,11 @@ def delete_user_by_login(login):
7671
:param login: The login of the user to be deleted.
7772
:return: The response of the api.
7873
"""
79-
if not login == "admin":
80-
if configuration.DRY_RUN:
81-
logger.info("Would have deleted user with name: %s" % login)
82-
else:
83-
logger.info("Deleting user with name %s" % login)
74+
if login == configuration.GRAFANA_AUTH[0]:
75+
logger.info("The user '%s' is used by this script for accessing Grafana thus will not be deleted." % login)
76+
else:
77+
logger_mut.info("Deleting user with name %s" % login)
78+
if not configuration.DRY_RUN:
8479
return grafana_api.admin.delete_user(grafana_api.users.find_user(login)["id"])
8580
return False
8681

@@ -94,10 +89,8 @@ def create_folder(folder_name, folder_uuid):
9489
:return: The api-response if the folder was create successfully. If an error occurs, false is returned.
9590
"""
9691
try:
97-
if configuration.DRY_RUN:
98-
logger.info("Would have created folder with name: %s and id: %s" % (folder_name, folder_uuid))
99-
else:
100-
logger.info("Creating folder with name %s and id %s" % (folder_name, folder_uuid))
92+
logger_mut.info("Creating folder with name %s and id %s" % (folder_name, folder_uuid))
93+
if not configuration.DRY_RUN:
10194
return grafana_api.folder.create_folder(folder_name, folder_uuid)
10295
except GrafanaClientError:
10396
return False
@@ -110,10 +103,8 @@ def add_user_to_team(login, team):
110103
:param team: The team the user should be added to.
111104
"""
112105
try:
113-
if configuration.DRY_RUN:
114-
logger.info("Would have added user %s to team %s" % (login, team))
115-
else:
116-
logger.info("Adding user %s to team %s" % (login, team))
106+
logger_mut.info("Adding user %s to team %s" % (login, team))
107+
if not configuration.DRY_RUN:
117108
grafana_api.teams.add_team_member(get_id_of_team(team), get_id_by_login(login))
118109
except GrafanaBadInputError:
119110
return False
@@ -142,10 +133,8 @@ def get_members_of_team(team):
142133

143134

144135
def remove_member_from_team(grafana_team, user_login):
145-
if configuration.DRY_RUN:
146-
print("Would have removed user %s from team %s" % (user_login, grafana_team))
147-
else:
148-
logger.info("Removing user %s from team %s" % (user_login, grafana_team))
136+
logger_mut.info("Removing user %s from team %s" % (user_login, grafana_team))
137+
if not configuration.DRY_RUN:
149138
grafana_api.teams.remove_team_member(get_id_of_team(grafana_team), get_id_by_login(user_login))
150139

151140

@@ -200,10 +189,8 @@ def update_folder_permissions(folder_id, permissions):
200189
"""
201190
Sets the given permissions for the folder found under the given id
202191
"""
203-
if configuration.DRY_RUN:
204-
logger.info("Would have set permission of folder %s to %s" % (folder_id, permissions))
205-
else:
206-
logger.info("Setting permission of folder %s to %s" % (folder_id, permissions))
192+
logger_mut.info("Setting permission of folder %s to %s" % (folder_id, permissions))
193+
if not configuration.DRY_RUN:
207194
grafana_api.folder.update_folder_permissions(folder_id, {"items": permissions})
208195

209196

script/ldap.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,7 @@
44
from .config import config
55
from .helpers import *
66

7-
logging.basicConfig(level=logging.INFO)
8-
logger = logging.getLogger("grafana-ldap-sync-script")
7+
logger = logging.getLogger()
98

109
configuration = ""
1110
user_cache = {}

setup.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
from setuptools import setup, find_packages
22

3-
43
setup(
54
name='grafana-ldap-sync-script',
65
version='0.1.0',

tests/test_core.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -379,7 +379,7 @@ def test_locks_and_unlocks(self, mock_setup_ldap, mock_unlock, mock_remove_unuse
379379
mock_config.return_value = True
380380
mock_lock.return_value = True
381381

382-
core.export("")
382+
core.startUserSync("")
383383

384384
self.assertEqual(mock_lock.call_count, 1)
385385
self.assertEqual(mock_unlock.call_count, 1)
@@ -405,7 +405,7 @@ def test_locks_and_unlocks_on_connection_error(self, mock_setup_ldap, mock_unloc
405405
mock_config.return_value = True
406406
mock_lock.return_value = True
407407

408-
core.export("")
408+
core.startUserSync("")
409409

410410
self.assertEqual(mock_lock.call_count, 1)
411411
self.assertEqual(mock_unlock.call_count, 1)
@@ -432,7 +432,7 @@ def test_locks_and_unlocks_on_LDAPSocketOpenError(self, mock_setup_ldap, mock_un
432432
mock_config.return_value = True
433433
mock_lock.return_value = True
434434

435-
core.export("")
435+
core.startUserSync("")
436436

437437
self.assertEqual(mock_lock.call_count, 1)
438438
self.assertEqual(mock_unlock.call_count, 1)
@@ -457,7 +457,7 @@ def test_nothing_called_when_locked(self, mock_unlock, mock_remove_unused_items,
457457
mock_config.return_value = True
458458
mock_lock.return_value = False
459459

460-
core.export("")
460+
core.startUserSync("")
461461

462462
self.assertEqual(mock_lock.call_count, 1)
463463
self.assertFalse(mock_remove_unused_items.called)

0 commit comments

Comments
 (0)