From 98e01baa8e51e5bad418cddac534853c8beb49da Mon Sep 17 00:00:00 2001 From: awu0403 <76416779+awu0403@users.noreply.github.com> Date: Fri, 7 Mar 2025 16:42:23 +0800 Subject: [PATCH] add metrics api (#7539) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * add metrics api update * update * update * Update __init__.py --------- Co-authored-by: 孙永强 <11704063+s-yongqiang@user.noreply.gitee.com> --- seahub/api2/endpoints/admin/logs_export.py | 2 +- seahub/api2/endpoints/utils.py | 8 ++++++ seahub/urls.py | 1 + seahub/utils/__init__.py | 1 - seahub/views/__init__.py | 30 +++++++++++++++++++++- 5 files changed, 39 insertions(+), 3 deletions(-) diff --git a/seahub/api2/endpoints/admin/logs_export.py b/seahub/api2/endpoints/admin/logs_export.py index 9e8d993e11..5e935c2161 100644 --- a/seahub/api2/endpoints/admin/logs_export.py +++ b/seahub/api2/endpoints/admin/logs_export.py @@ -11,7 +11,7 @@ from rest_framework.decorators import api_view from urllib.parse import quote from seahub.api2.authentication import TokenAuthentication -from seahub.api2.endpoints.utils import check_time_period_valid, export_logs_to_excel, event_export_status +from seahub.api2.endpoints.utils import check_time_period_valid, export_logs_to_excel from seahub.api2.permissions import IsProVersion from seahub.api2.throttling import UserRateThrottle from seahub.api2.utils import api_error diff --git a/seahub/api2/endpoints/utils.py b/seahub/api2/endpoints/utils.py index 535f48c1ae..f5c071e1d2 100644 --- a/seahub/api2/endpoints/utils.py +++ b/seahub/api2/endpoints/utils.py @@ -329,3 +329,11 @@ def delete_user_monitored_cache(params): url = urljoin(SEAFEVENTS_SERVER_URL, '/delete-repo-monitored-user-cache') resp = requests.post(url, json=params, headers=headers) return resp + +def get_seafevents_metrics(): + payload = {'exp': int(time.time()) + 300, } + token = jwt.encode(payload, SECRET_KEY, algorithm='HS256') + headers = {"Authorization": "Token %s" % token} + url = urljoin(SEAFEVENTS_SERVER_URL, '/metrics') + resp = requests.get(url, headers=headers) + return resp diff --git a/seahub/urls.py b/seahub/urls.py index d72df7219e..dffb9ad176 100644 --- a/seahub/urls.py +++ b/seahub/urls.py @@ -236,6 +236,7 @@ urlpatterns = [ path('', react_fake_view, name='libraries'), re_path(r'^robots\.txt$', TemplateView.as_view(template_name='robots.txt', content_type='text/plain')), + path('metrics/', get_metrics, name='metrics'), # revert repo re_path(r'^repo/history/revert/(?P[-0-9a-f]{36})/$', repo_revert_history, name='repo_revert_history'), diff --git a/seahub/utils/__init__.py b/seahub/utils/__init__.py index a467403f0a..6683aa4ffc 100644 --- a/seahub/utils/__init__.py +++ b/seahub/utils/__init__.py @@ -1565,4 +1565,3 @@ def transfer_repo(repo_id, new_owner, is_share, org_id=None): seafile_api.transfer_repo_to_group(repo_id, group_id, PERMISSION_READ_WRITE) else: seafile_api.set_repo_owner(repo_id, new_owner) - diff --git a/seahub/views/__init__.py b/seahub/views/__init__.py index 867df8aab5..cfcef6111f 100644 --- a/seahub/views/__init__.py +++ b/seahub/views/__init__.py @@ -1,5 +1,6 @@ # Copyright (c) 2012-2016 Seafile Ltd. # encoding: utf-8 +import base64 import os import stat import json @@ -18,7 +19,7 @@ from django.shortcuts import render, redirect from django.utils.translation import gettext as _ from django.views.decorators.http import condition from django.http import HttpResponse, Http404, \ - HttpResponseRedirect + HttpResponseRedirect, HttpResponseForbidden import seaserv from seaserv import get_repo, get_commits, \ @@ -51,6 +52,7 @@ from seahub.utils.repo import get_library_storages, parse_repo_perm, is_repo_adm from seahub.utils.file_op import check_file_lock from seahub.utils.timeutils import utc_to_local from seahub.utils.auth import get_login_bg_image_path +from seahub.api2.endpoints.utils import get_seafevents_metrics import seahub.settings as settings from seahub.settings import AVATAR_FILE_STORAGE, ENABLE_REPO_SNAPSHOT_LABEL, \ SHARE_LINK_EXPIRE_DAYS_MIN, ENABLE_METADATA_MANAGEMENT, \ @@ -73,6 +75,10 @@ from seahub.organizations.models import OrgAdminSettings, DISABLE_ORG_USER_CLEAN LIBRARY_TEMPLATES = getattr(settings, 'LIBRARY_TEMPLATES', {}) CUSTOM_NAV_ITEMS = getattr(settings, 'CUSTOM_NAV_ITEMS', '') +ENABLE_METRIC = getattr(settings, 'ENABLE_METRIC', False) +METRIC_AUTH_USER = getattr(settings, 'METRIC_AUTH_USER', None) +METRIC_AUTH_PWD = getattr(settings, 'METRIC_AUTH_PWD', None) + # Get an instance of a logger logger = logging.getLogger(__name__) @@ -1158,3 +1164,25 @@ def react_fake_view(request, **kwargs): return_dict['google_map_id'] = settings.GOOGLE_MAP_ID return render(request, "react_app.html", return_dict) + + +def check_metric_auth(auth_header): + try: + auth_decoded = base64.b64decode(auth_header.split(' ')[1]).decode('utf-8') + username, password = auth_decoded.split(':') + if username == METRIC_AUTH_USER and password == METRIC_AUTH_PWD: + return True + except Exception as e: + logger.error(e) + return False + return False + + +def get_metrics(request): + if not ENABLE_METRIC: + return Http404 + auth_header = request.META.get('HTTP_AUTHORIZATION') + if not auth_header or not check_metric_auth(auth_header): + return HttpResponseForbidden('Invalid Authentication') + metrics = get_seafevents_metrics() + return HttpResponse(metrics, content_type='text/plain')