diff --git a/engine/apps/grafana_plugin/tasks/sync_v2.py b/engine/apps/grafana_plugin/tasks/sync_v2.py index 973322c7d..7f2d9bcfc 100644 --- a/engine/apps/grafana_plugin/tasks/sync_v2.py +++ b/engine/apps/grafana_plugin/tasks/sync_v2.py @@ -41,14 +41,17 @@ def sync_organizations_v2(org_ids=None): orgs_per_second = math.ceil(len(organization_qs) / SYNC_PERIOD.seconds) logger.info(f"Syncing {len(organization_qs)} organizations @ {orgs_per_second} per 1s pause") for idx, org in enumerate(organization_qs): - client = GrafanaAPIClient(api_url=org.grafana_url, api_token=org.api_token) - _, status = client.sync() - if status["status_code"] != 200: - logger.error( - f"Failed to request sync stack_slug={org.stack_slug} status_code={status['status_code']} url={status['url']} message={status['message']}" - ) - if idx % orgs_per_second == 0: - logger.info(f"Sleep 1s after {idx + 1} organizations processed") - sleep(1) + if org.api_token: + client = GrafanaAPIClient(api_url=org.grafana_url, api_token=org.api_token) + _, status = client.sync() + if status["status_code"] != 200: + logger.error( + f"Failed to request sync stack_slug={org.stack_slug} status_code={status['status_code']} url={status['url']} message={status['message']}" + ) + if idx % orgs_per_second == 0: + logger.info(f"Sleep 1s after {idx + 1} organizations processed") + sleep(1) + else: + logger.info(f"Skipping stack_slug={org.stack_slug}, api_token is not set") else: logger.info(f"Issuing sync requests already in progress lock_id={lock_id}, check slow outgoing requests") diff --git a/engine/apps/grafana_plugin/tests/test_sync_v2.py b/engine/apps/grafana_plugin/tests/test_sync_v2.py index d84de38a9..0c118da4b 100644 --- a/engine/apps/grafana_plugin/tests/test_sync_v2.py +++ b/engine/apps/grafana_plugin/tests/test_sync_v2.py @@ -6,6 +6,7 @@ from rest_framework.test import APIClient from apps.api.permissions import LegacyAccessControlRole +from apps.grafana_plugin.tasks import sync_organizations_v2 @pytest.mark.django_db @@ -44,3 +45,30 @@ def test_invalid_auth(make_organization_and_user_with_plugin_token, make_user_au assert response.status_code == status.HTTP_401_UNAUTHORIZED assert not mock_sync.called + + +@pytest.mark.parametrize( + "api_token, sync_called", + [ + ("", False), + ("abc", True), + ], +) +@pytest.mark.django_db +def test_skip_org_without_api_token(make_organization, api_token, sync_called): + organization = make_organization(api_token=api_token) + + with patch( + "apps.grafana_plugin.helpers.GrafanaAPIClient.sync", + return_value=( + None, + { + "url": "", + "connected": True, + "status_code": status.HTTP_200_OK, + "message": "", + }, + ), + ) as mock_sync: + sync_organizations_v2(org_ids=[organization.id]) + assert mock_sync.called == sync_called