Skip to content

Commit 7f0a9ae

Browse files
clean-up of code prior to PR. Add is_copilot switch for instantiating s3 client
1 parent 3f12ffc commit 7f0a9ae

File tree

8 files changed

+69
-92
lines changed

8 files changed

+69
-92
lines changed

.copilot/image_build_run.sh

-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
#!/usr/bin/env bash
22

3-
# Exit early if something goes wrong
43
set -e
54

65
# Add commands below to run inside the container after all the other buildpacks have been applied

.copilot/phases/build.sh

+1-7
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,3 @@
11
#!/usr/bin/env bash
22

3-
set -ex
4-
5-
#python -m pip install --upgrade pip
6-
#pip install -r requirements.txt
7-
#
8-
#npm install
9-
#npm run build
3+
set -e

.copilot/phases/install.sh

-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
#!/usr/bin/env bash
22

3-
# Exit early if something goes wrong
43
set -e
54

65
# Add commands below to run as part of the install phase

.copilot/phases/post_build.sh

-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
#!/usr/bin/env bash
22

3-
# Exit early if something goes wrong
43
set -e
54

65
# Add commands below to run as part of the post_build phase

.copilot/phases/pre_build.sh

-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
#!/usr/bin/env bash
22

3-
# Exit early if something goes wrong
43
set -e
54

65
# Add commands below to run as part of the pre_build phase

common/views.py

+43-12
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
import kombu.exceptions
1515
from botocore.exceptions import ClientError
1616
from botocore.exceptions import EndpointConnectionError
17+
from dbt_copilot_python.utility import is_copilot
1718
from django.conf import settings
1819
from django.contrib.auth.mixins import LoginRequiredMixin
1920
from django.contrib.auth.mixins import PermissionRequiredMixin
@@ -302,12 +303,23 @@ def check_celery_broker(self) -> Tuple[str, int]:
302303

303304
def check_s3(self) -> Tuple[str, int]:
304305
try:
305-
client = boto3.client(
306-
"s3",
307-
endpoint_url=settings.S3_ENDPOINT_URL,
308-
region_name=settings.HMRC_PACKAGING_S3_REGION_NAME,
306+
if is_copilot():
307+
client = boto3.client(
308+
"s3",
309+
endpoint_url=settings.S3_ENDPOINT_URL,
310+
region_name=settings.HMRC_PACKAGING_S3_REGION_NAME,
311+
)
312+
else:
313+
client = boto3.client(
314+
"s3",
315+
aws_access_key_id=settings.HMRC_PACKAGING_S3_ACCESS_KEY_ID,
316+
aws_secret_access_key=settings.HMRC_PACKAGING_S3_SECRET_ACCESS_KEY,
317+
endpoint_url=settings.S3_ENDPOINT_URL,
318+
region_name=settings.HMRC_PACKAGING_S3_REGION_NAME,
319+
)
320+
client.head_bucket(
321+
Bucket=settings.HMRC_PACKAGING_STORAGE_BUCKET_NAME,
309322
)
310-
client.head_bucket(Bucket=settings.HMRC_PACKAGING_STORAGE_BUCKET_NAME)
311323
return "OK", 200
312324
except (ClientError, EndpointConnectionError):
313325
return "S3 health check failed", 503
@@ -429,10 +441,14 @@ def get_context_data(self, **kwargs):
429441
data["APP_UPDATED_TIME"] = AppInfoView.timestamp_to_datetime_string(
430442
os.path.getmtime(__file__),
431443
)
432-
last_transaction = Transaction.objects.order_by("updated_at").last()
444+
last_transaction = Transaction.objects.order_by(
445+
"updated_at",
446+
).last()
433447
data["LAST_TRANSACTION_TIME"] = (
434448
format(
435-
last_transaction.updated_at.strftime(AppInfoView.DATETIME_FORMAT),
449+
last_transaction.updated_at.strftime(
450+
AppInfoView.DATETIME_FORMAT,
451+
),
436452
)
437453
if last_transaction
438454
else "No transactions"
@@ -519,7 +535,9 @@ def get_object(self, queryset: Optional[QuerySet] = None) -> Model:
519535
try:
520536
obj = queryset.get()
521537
except queryset.model.DoesNotExist:
522-
raise Http404(f"No {self.model.__name__} matching the query {self.kwargs}")
538+
raise Http404(
539+
f"No {self.model.__name__} matching the query {self.kwargs}",
540+
)
523541

524542
return obj
525543

@@ -652,10 +670,15 @@ def get_ordering(self):
652670
self,
653671
"sort_by_fields",
654672
), "SortingMixin requires class attribute sort_by_fields to be set"
655-
assert isinstance(self.sort_by_fields, list), "sort_by_fields must be a list"
673+
assert isinstance(
674+
self.sort_by_fields,
675+
list,
676+
), "sort_by_fields must be a list"
656677

657678
if sort_by and sort_by in self.sort_by_fields:
658-
if hasattr(self, "custom_sorting") and self.custom_sorting.get(sort_by):
679+
if hasattr(self, "custom_sorting") and self.custom_sorting.get(
680+
sort_by,
681+
):
659682
sort_by = self.custom_sorting.get(sort_by)
660683

661684
if ordered == "desc":
@@ -668,11 +691,19 @@ def get_ordering(self):
668691

669692

670693
def handler403(request, *args, **kwargs):
671-
return TemplateResponse(request=request, template="common/403.jinja", status=403)
694+
return TemplateResponse(
695+
request=request,
696+
template="common/403.jinja",
697+
status=403,
698+
)
672699

673700

674701
def handler500(request, *args, **kwargs):
675-
return TemplateResponse(request=request, template="common/500.jinja", status=500)
702+
return TemplateResponse(
703+
request=request,
704+
template="common/500.jinja",
705+
status=500,
706+
)
676707

677708

678709
class MaintenanceView(TemplateView):

scripts/web-worker-entrypoint.sh

+4-1
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
#!/bin/sh -e
22

3-
# Django Migrations
43
WORKER_COMMAND="gunicorn wsgi --bind 0.0.0.0:${PORT} --timeout 1000 --worker-class=gevent --worker-connections=1000 --workers 9"
54

5+
if [ -n "${COPILOT_ENVIRONMENT_NAME}" ]; then
6+
WORKER_COMMAND="opentelemetry-instrument ${WORKER_COMMAND}"
7+
fi
8+
69
echo "Starting worker using the command: ${WORKER_COMMAND}"
710

811
eval ${WORKER_COMMAND}

settings/common.py

+21-68
Original file line numberDiff line numberDiff line change
@@ -176,9 +176,7 @@
176176
INSTALLED_APPS.remove("django.contrib.admin")
177177

178178
MIDDLEWARE.remove("django.contrib.sessions.middleware.SessionMiddleware")
179-
MIDDLEWARE.remove(
180-
"django.contrib.auth.middleware.AuthenticationMiddleware",
181-
)
179+
MIDDLEWARE.remove("django.contrib.auth.middleware.AuthenticationMiddleware")
182180
MIDDLEWARE.remove("django.contrib.messages.middleware.MessageMiddleware")
183181
MIDDLEWARE.remove("common.models.utils.TransactionMiddleware")
184182
MIDDLEWARE.remove("common.models.utils.ValidateUserWorkBasketMiddleware")
@@ -284,8 +282,7 @@
284282
ALLOWED_HOSTS = setup_allowed_hosts(ALLOWED_HOSTS)
285283
# Govuk PaaS
286284
elif "VCAP_APPLICATION" in os.environ:
287-
# Under PaaS, if ALLOW_PAAS_URIS is set
288-
# fetch trusted domains from VCAP_APPLICATION env var
285+
# Under PaaS, if ALLOW_PAAS_URIS is set fetch trusted domains from VCAP_APPLICATION env var
289286
paas_hosts = json.loads(os.environ["VCAP_APPLICATION"])["uris"]
290287
ALLOWED_HOSTS.extend(paas_hosts)
291288

@@ -387,9 +384,7 @@
387384
# Settings about retrying uploads if the bucket or endpoint cannot be contacted.
388385
# Names correspond to celery settings for retrying tasks:
389386
# https://docs.celeryproject.org/en/master/userguide/tasks.html#automatic-retry-for-known-exceptions
390-
EXPORTER_UPLOAD_MAX_RETRIES = int(
391-
os.environ.get("EXPORTER_UPLOAD_MAX_RETRIES", "3"),
392-
)
387+
EXPORTER_UPLOAD_MAX_RETRIES = int(os.environ.get("EXPORTER_UPLOAD_MAX_RETRIES", "3"))
393388
EXPORTER_UPLOAD_RETRY_BACKOFF_MAX = int(
394389
os.environ.get("EXPORTER_UPLOAD_RETRY_BACKOFF_MAX", "600"),
395390
)
@@ -432,10 +427,7 @@
432427

433428
# HMRC AWS settings (override the defaults) - DEPRECATED.
434429
HMRC_STORAGE_BUCKET_NAME = os.environ.get("HMRC_STORAGE_BUCKET_NAME", "hmrc")
435-
HMRC_STORAGE_DIRECTORY = os.environ.get(
436-
"HMRC_STORAGE_DIRECTORY",
437-
"tohmrc/staging/",
438-
)
430+
HMRC_STORAGE_DIRECTORY = os.environ.get("HMRC_STORAGE_DIRECTORY", "tohmrc/staging/")
439431

440432

441433
# S3 settings for packaging automation.
@@ -545,18 +537,12 @@
545537
"test_sqlite_key",
546538
)
547539

548-
SQLITE_STORAGE_BUCKET_NAME = os.environ.get(
549-
"SQLITE_STORAGE_BUCKET_NAME",
550-
"sqlite",
551-
)
540+
SQLITE_STORAGE_BUCKET_NAME = os.environ.get("SQLITE_STORAGE_BUCKET_NAME", "sqlite")
552541
SQLITE_S3_ENDPOINT_URL = os.environ.get(
553542
"SQLITE_S3_ENDPOINT_URL",
554543
"https://test-sqlite-url.local/",
555544
)
556-
SQLITE_STORAGE_DIRECTORY = os.environ.get(
557-
"SQLITE_STORAGE_DIRECTORY",
558-
"sqlite/",
559-
)
545+
SQLITE_STORAGE_DIRECTORY = os.environ.get("SQLITE_STORAGE_DIRECTORY", "sqlite/")
560546

561547
# Default AWS settings.
562548
if is_copilot():
@@ -586,14 +572,8 @@
586572
"CROWN_DEPENDENCIES_API_URL_PATH",
587573
"api/v1/taricfiles/",
588574
)
589-
CROWN_DEPENDENCIES_GET_API_KEY = os.environ.get(
590-
"CROWN_DEPENDENCIES_GET_API_KEY",
591-
"",
592-
)
593-
CROWN_DEPENDENCIES_POST_API_KEY = os.environ.get(
594-
"CROWN_DEPENDENCIES_POST_API_KEY",
595-
"",
596-
)
575+
CROWN_DEPENDENCIES_GET_API_KEY = os.environ.get("CROWN_DEPENDENCIES_GET_API_KEY", "")
576+
CROWN_DEPENDENCIES_POST_API_KEY = os.environ.get("CROWN_DEPENDENCIES_POST_API_KEY", "")
597577

598578

599579
if is_copilot():
@@ -614,10 +594,7 @@
614594
CACHES["default"]["LOCATION"],
615595
)
616596

617-
CELERY_RESULT_BACKEND = os.environ.get(
618-
"CELERY_RESULT_BACKEND",
619-
CELERY_BROKER_URL,
620-
)
597+
CELERY_RESULT_BACKEND = os.environ.get("CELERY_RESULT_BACKEND", CELERY_BROKER_URL)
621598
CELERY_TRACK_STARTED = True
622599
CELERY_TASK_TRACK_STARTED = True
623600
CELERY_RESULT_PERSISTENT = True
@@ -689,19 +666,14 @@
689666

690667
# -- Google Tag Manager
691668
GOOGLE_ANALYTICS_ID = os.environ.get("GOOGLE_ANALYTICS_ID")
692-
GOOGLE_ANALYTICS_APP_ID = os.environ.get(
693-
"GOOGLE_ANALYTICS_APP_ID",
694-
GOOGLE_ANALYTICS_ID,
695-
)
669+
GOOGLE_ANALYTICS_APP_ID = os.environ.get("GOOGLE_ANALYTICS_APP_ID", GOOGLE_ANALYTICS_ID)
696670

697671
# -- Logging
698672
LOGGING = {
699673
"version": 1,
700674
"disable_existing_loggers": False,
701675
"formatters": {
702-
"default": {
703-
"format": "%(asctime)s %(name)s %(levelname)s %(message)s",
704-
},
676+
"default": {"format": "%(asctime)s %(name)s %(levelname)s %(message)s"},
705677
"asim_formatter": {
706678
"()": ASIMFormatter,
707679
},
@@ -825,9 +797,7 @@
825797

826798
# -- REST Framework
827799
REST_FRAMEWORK = {
828-
"DEFAULT_FILTER_BACKENDS": [
829-
"django_filters.rest_framework.DjangoFilterBackend",
830-
],
800+
"DEFAULT_FILTER_BACKENDS": ["django_filters.rest_framework.DjangoFilterBackend"],
831801
# Use Django's standard `django.contrib.auth` permissions,
832802
# or allow read-only access for unauthenticated users.
833803
"DEFAULT_PERMISSION_CLASSES": [
@@ -854,10 +824,7 @@
854824
PATH_COMMODITIES_ASSETS,
855825
"commodities_envelope.xsd",
856826
)
857-
PATH_XSD_COMMODITIES_TARIC = Path(
858-
PATH_COMMODITIES_ASSETS,
859-
"commodities_taric3.xsd",
860-
)
827+
PATH_XSD_COMMODITIES_TARIC = Path(PATH_COMMODITIES_ASSETS, "commodities_taric3.xsd")
861828

862829

863830
# Default username for envelope data imports
@@ -875,16 +842,12 @@
875842
"client_id": os.environ.get("HMRC_API_CLIENT_ID"),
876843
"client_secret": os.environ.get("HMRC_API_CLIENT_SECRET"),
877844
"token_url": os.environ.get("HMRC_API_TOKEN_URL", "/oauth/token"),
878-
"service_reference_number": os.environ.get(
879-
"HMRC_API_SERVICE_REFERENCE_NUMBER",
880-
),
845+
"service_reference_number": os.environ.get("HMRC_API_SERVICE_REFERENCE_NUMBER"),
881846
"device_id": str(uuid.uuid4()),
882847
}
883848

884849
SKIP_VALIDATION = is_truthy(os.getenv("SKIP_VALIDATION", False))
885-
SKIP_WORKBASKET_VALIDATION = is_truthy(
886-
os.getenv("SKIP_WORKBASKET_VALIDATION", False),
887-
)
850+
SKIP_WORKBASKET_VALIDATION = is_truthy(os.getenv("SKIP_WORKBASKET_VALIDATION", False))
888851
USE_IMPORTER_CACHE = is_truthy(os.getenv("USE_IMPORTER_CACHE", True))
889852

890853
CRISPY_ALLOWED_TEMPLATE_PACKS = ["gds"]
@@ -898,10 +861,8 @@
898861
},
899862
}
900863

901-
TRANSACTION_SCHEMA = os.getenv(
902-
"TRANSACTION_SCHEMA",
903-
"workbaskets.models.SEED_FIRST",
904-
)
864+
865+
TRANSACTION_SCHEMA = os.getenv("TRANSACTION_SCHEMA", "workbaskets.models.SEED_FIRST")
905866

906867
# Default max number of objects that will be accurately counted by LimitedPaginator.
907868
LIMITED_PAGINATOR_MAX_COUNT = 200
@@ -924,12 +885,8 @@
924885
READY_FOR_CDS_TEMPLATE_ID = os.environ.get("READY_FOR_CDS_TEMPLATE_ID")
925886
CDS_ACCEPTED_TEMPLATE_ID = os.environ.get("CDS_ACCEPTED_TEMPLATE_ID")
926887
CDS_REJECTED_TEMPLATE_ID = os.environ.get("CDS_REJECTED_TEMPLATE_ID")
927-
API_PUBLISH_SUCCESS_TEMPLATE_ID = os.environ.get(
928-
"API_PUBLISH_SUCCESS_TEMPLATE_ID",
929-
)
930-
API_PUBLISH_FAILED_TEMPLATE_ID = os.environ.get(
931-
"API_PUBLISH_FAILED_TEMPLATE_ID",
932-
)
888+
API_PUBLISH_SUCCESS_TEMPLATE_ID = os.environ.get("API_PUBLISH_SUCCESS_TEMPLATE_ID")
889+
API_PUBLISH_FAILED_TEMPLATE_ID = os.environ.get("API_PUBLISH_FAILED_TEMPLATE_ID")
933890
GOODS_REPORT_TEMPLATE_ID = os.environ.get("GOODS_REPORT_TEMPLATE_ID")
934891

935892
# Base service URL - required when constructing an absolute TAP URL to a page
@@ -951,12 +908,8 @@
951908
"django.core.files.uploadhandler.MemoryFileUploadHandler", # defaults
952909
"django.core.files.uploadhandler.TemporaryFileUploadHandler", # defaults
953910
) # Order is important
954-
DATA_MIGRATION_BATCH_SIZE = int(
955-
os.environ.get("DATA_MIGRATION_BATCH_SIZE", "10000"),
956-
)
911+
DATA_MIGRATION_BATCH_SIZE = int(os.environ.get("DATA_MIGRATION_BATCH_SIZE", "10000"))
957912

958913

959914
# Asynchronous / background (bulk) object creation and editing config.
960-
MEASURES_ASYNC_CREATION = is_truthy(
961-
os.environ.get("MEASURES_ASYNC_CREATION", "true"),
962-
)
915+
MEASURES_ASYNC_CREATION = is_truthy(os.environ.get("MEASURES_ASYNC_CREATION", "true"))

0 commit comments

Comments
 (0)