Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(api/ldap): ldap test_connection fail with more error detail #445

Merged
merged 5 commits into from
May 19, 2022
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 . import exceptions as local_exceptions
Expand Down Expand Up @@ -69,16 +69,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
wklken marked this conversation as resolved.
Show resolved Hide resolved

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 @@ -74,25 +75,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 @@ -196,9 +196,9 @@ def test_connection(self, request, lookup_value):

try:
syncer_cls(instance.id).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 @@ -230,16 +230,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 @@ -272,17 +271,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