Skip to content

Commit

Permalink
refactor(api/ldap): ldap test_connection fail with more error detail (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
wklken authored May 19, 2022
1 parent a95035f commit 5b394d8
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 29 deletions.
22 changes: 12 additions & 10 deletions src/api/bkuser_core/categories/plugins/ldap/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@
from dataclasses import dataclass
from typing import TYPE_CHECKING, Dict, List

import ldap3
from django.conf import settings
from django.utils.translation import gettext_lazy as _
from ldap3 import ALL, SIMPLE, Connection, Server
from ldap3.utils import log as ldap3log

Expand Down Expand Up @@ -78,16 +78,18 @@ def initialize(
connection_params.update({"user": user, "password": password, "authentication": SIMPLE})

return Connection(**connection_params)

except KeyError:
except KeyError as e:
logger.exception("failed to initialize ldap server. KeyError. [url=%s]", connection_url)
raise local_exceptions.LDAPSettingNotReady
except ldap3.core.exceptions.LDAPSocketReceiveError:
logger.exception("failed to initialize ldap server. LDAPSocketReceiveError. [url=%s]", connection_url)
raise local_exceptions.LdapCannotBeInitialized
except Exception:
logger.exception("failed to initialize ldap server. [url=%s]", connection_url)
raise local_exceptions.LdapCannotBeInitialized
raise local_exceptions.LDAPSettingNotReady from e
except Exception as e:
logger.exception(
"failed to initialize ldap server. %s.%s [url=%s]",
type(e).__module__,
type(e).__name__,
connection_url,
)
error_detail = f" ({type(e).__module__}.{type(e).__name__}: {str(e)})"
raise local_exceptions.LdapCannotBeInitialized(_("LDAP服务器连接失败") + error_detail) from e

def search(
self,
Expand Down
16 changes: 10 additions & 6 deletions src/api/bkuser_core/categories/plugins/ldap/syncer.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

from django.db import transaction
from django.utils.encoding import force_bytes
from django.utils.translation import gettext_lazy as _

from bkuser_core.categories.exceptions import FetchDataFromRemoteFailed
from bkuser_core.categories.plugins.base import DBSyncManager, Fetcher, SyncContext, Syncer, SyncStep, TypeList
Expand Down Expand Up @@ -77,25 +78,28 @@ def _fetch_data(
groups = self.client.search(start_root=basic_pull_node, force_filter_str=user_group_filter)
else:
groups = []
except Exception:
except Exception as e:
logger.exception("failed to get groups from remote server")
raise FetchDataFromRemoteFailed("无法获取用户组,请检查配置")
error_detail = f" ({type(e).__module__}.{type(e).__name__}: {str(e)})"
raise FetchDataFromRemoteFailed(_("无法获取用户组,请检查配置") + error_detail)

try:
departments = self.client.search(start_root=basic_pull_node, object_class=organization_class)
except Exception:
except Exception as e:
logger.exception("failed to get departments from remote server")
raise FetchDataFromRemoteFailed("无法获取组织部门,请检查配置")
error_detail = f" ({type(e).__module__}.{type(e).__name__}: {str(e)})"
raise FetchDataFromRemoteFailed(_("无法获取组织部门,请检查配置") + error_detail)

try:
users = self.client.search(
start_root=basic_pull_node,
force_filter_str=user_filter,
attributes=attributes or [],
)
except Exception:
except Exception as e:
logger.exception("failed to get users from remote server")
raise FetchDataFromRemoteFailed("无法获取用户数据, 请检查配置")
error_detail = f" ({type(e).__module__}.{type(e).__name__}: {str(e)})"
raise FetchDataFromRemoteFailed(_("无法获取用户数据, 请检查配置") + error_detail)

return groups, departments, users

Expand Down
22 changes: 11 additions & 11 deletions src/api/bkuser_core/categories/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,9 +198,9 @@ def test_connection(self, request, lookup_value):
syncer_cls(instance.id, with_initialize_client=False).fetcher.client.initialize(
**serializer.validated_data
)
except Exception:
except Exception as e:
logger.exception("failed to test initialize category<%s>", instance.id)
raise error_codes.TEST_CONNECTION_FAILED
raise error_codes.TEST_CONNECTION_FAILED.format(str(e), replace=True)

return Response()

Expand Down Expand Up @@ -232,16 +232,15 @@ def test_fetch_data(self, request, lookup_value):

try:
syncer = syncer_cls(instance.id)
except Exception:
except Exception as e:
logger.exception("failed to test initialize category<%s>", instance.id)
raise error_codes.TEST_CONNECTION_FAILED.f("请确保连接设置正确")
raise error_codes.TEST_CONNECTION_FAILED.f(f"请确保连接设置正确 {str(e)}")

try:
syncer.fetcher.test_fetch_data(serializer.validated_data)
except FetchDataFromRemoteFailed as e:
raise error_codes.TEST_FETCH_DATA_FAILED.f(f"{e}")
except Exception: # pylint: disable=broad-except
raise error_codes.TEST_FETCH_DATA_FAILED
except Exception as e: # pylint: disable=broad-except
error_detail = f" ({type(e).__module__}.{type(e).__name__}: {str(e)})"
raise error_codes.TEST_FETCH_DATA_FAILED.f(error_detail)

return Response()

Expand Down Expand Up @@ -274,17 +273,18 @@ def sync(self, request, lookup_value):
request.operator,
task_id,
)
raise error_codes.SYNC_DATA_FAILED.f(f"{e}")
error_detail = f" ({type(e).__module__}.{type(e).__name__}: {str(e)})"
raise error_codes.SYNC_DATA_FAILED.f(error_detail)
except CoreAPIError:
raise
except Exception:
except Exception as e:
logger.exception(
"failed to sync data. " "[instance.id=%s, operator=%s, task_id=%s]",
instance.id,
request.operator,
task_id,
)
raise error_codes.SYNC_DATA_FAILED
raise error_codes.SYNC_DATA_FAILED.f(f"{e}")

return Response({"task_id": task_id})

Expand Down
4 changes: 2 additions & 2 deletions src/bkuser_global/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@ def get_logging(logging_type: int, **kwargs) -> dict:
"%(funcName)s %(process)d %(thread)d %(request_id)s %(message)s"
),
},
"simple": {"format": "%(levelname)s %(message)s"},
"iam": {"format": "[IAM] %(asctime)s %(message)s"},
"simple": {"format": "%(levelname)s [%(asctime)s] %(message)s"},
"iam": {"format": "[IAM] %(levelname)s [%(asctime)s] %(message)s"},
}


Expand Down

0 comments on commit 5b394d8

Please sign in to comment.