183 lines
6.5 KiB
Python
183 lines
6.5 KiB
Python
from datetime import UTC, datetime, timedelta
|
|
|
|
from django.conf import settings
|
|
from django.contrib.auth.mixins import PermissionRequiredMixin
|
|
from django.db import transaction
|
|
from django.db.models import Q
|
|
from django.http import Http404
|
|
from django.shortcuts import redirect
|
|
from django.utils import timezone
|
|
from django.utils.decorators import method_decorator
|
|
from django.views.decorators.cache import never_cache
|
|
from django.views.generic import DetailView
|
|
|
|
from .access import TenantScopeMixin, is_tenant
|
|
from .independent_websites import active_websites
|
|
from .models import HostingAccount, HostingMailbox, WebsiteUsage
|
|
from .sftp import site_is_active
|
|
from .tasks import collect_mailbox_usage, collect_website_usage
|
|
|
|
|
|
def managed_sites(account):
|
|
from coulobre.web_node import WebSite
|
|
|
|
sites = [website.spec for website in active_websites(account)]
|
|
if site_is_active(account):
|
|
sites.insert(0, WebSite(account.pk, account.primary_domain))
|
|
return sites
|
|
|
|
|
|
def access_log_entry(line):
|
|
try:
|
|
timestamp, size, status, method, path = line.split(" ", 4)
|
|
return {
|
|
"time": datetime.fromtimestamp(int(timestamp), tz=UTC),
|
|
"bytes": int(size),
|
|
"status": int(status),
|
|
"method": method,
|
|
"path": path,
|
|
}
|
|
except (ValueError, OverflowError, OSError):
|
|
return {"raw": line}
|
|
|
|
|
|
@method_decorator(never_cache, name="dispatch")
|
|
class WebsiteUsageView(TenantScopeMixin, PermissionRequiredMixin, DetailView):
|
|
queryset = HostingAccount.objects.filter(retired_at__isnull=True)
|
|
context_object_name = "account"
|
|
customer_relation = "customer"
|
|
permission_required = (
|
|
"hosting.view_hostingaccount",
|
|
"hosting.view_websiteusage",
|
|
)
|
|
template_name = "hosting/website_usage.html"
|
|
|
|
def dispatch(self, request, *args, **kwargs):
|
|
if not settings.WEBSITE_USAGE:
|
|
raise Http404
|
|
return super().dispatch(request, *args, **kwargs)
|
|
|
|
def can_view_mailboxes(self):
|
|
user = self.request.user
|
|
return is_tenant(user) or user.has_perm("hosting.view_hostingmailbox")
|
|
|
|
def get_context_data(self, **kwargs):
|
|
snapshots = {
|
|
row.node_key: row
|
|
for row in self.object.website_usage.all()
|
|
if row.report and row.observed_at
|
|
}
|
|
rows = []
|
|
for site in managed_sites(self.object):
|
|
snapshot = snapshots.get(site.node_key)
|
|
rows.append(
|
|
(
|
|
site,
|
|
snapshot
|
|
if snapshot and snapshot.domain == site.domain
|
|
else None,
|
|
)
|
|
)
|
|
month = timezone.now().strftime("%Y-%m")
|
|
report_rows = [
|
|
reading.report
|
|
for _, reading in rows
|
|
if reading and reading.report.get("month") == month
|
|
]
|
|
totals = [
|
|
report["traffic_bytes"]
|
|
for report in report_rows
|
|
if report.get("traffic_bytes") is not None
|
|
]
|
|
complete = len(totals) == len(rows) and all(
|
|
not report.get("partial") for report in report_rows
|
|
)
|
|
limits = {
|
|
website.spec.node_key: website.storage_limit_mib
|
|
for website in active_websites(self.object)
|
|
}
|
|
current_limit = getattr(self.object, "storage_limit", None)
|
|
if (
|
|
current_limit
|
|
and current_limit.domain == self.object.primary_domain
|
|
):
|
|
limits[str(self.object.pk)] = current_limit.applied_mib
|
|
return super().get_context_data(
|
|
sites=[
|
|
(
|
|
site,
|
|
reading,
|
|
limits.get(site.node_key),
|
|
[
|
|
access_log_entry(line)
|
|
for line in reading.report.get("access_lines", ())
|
|
]
|
|
if reading
|
|
else (),
|
|
)
|
|
for site, reading in rows
|
|
],
|
|
month=month,
|
|
total_traffic=sum(totals) if totals else None,
|
|
complete=complete,
|
|
mailboxes=HostingMailbox.objects.filter(
|
|
mail_domain__account=self.object
|
|
).select_related("mail_domain")
|
|
if self.can_view_mailboxes()
|
|
else None,
|
|
**kwargs,
|
|
)
|
|
|
|
def post(self, request, *args, **kwargs):
|
|
account = self.get_object()
|
|
with transaction.atomic():
|
|
account = HostingAccount.objects.select_for_update().get(
|
|
pk=account.pk
|
|
)
|
|
now = timezone.now()
|
|
for site in managed_sites(account):
|
|
snapshot, _ = WebsiteUsage.objects.get_or_create(
|
|
account=account,
|
|
node_key=site.node_key,
|
|
defaults={"domain": site.domain},
|
|
)
|
|
if (
|
|
snapshot.domain == site.domain
|
|
and snapshot.requested_at
|
|
and snapshot.requested_at > now - timedelta(minutes=1)
|
|
):
|
|
continue
|
|
if snapshot.domain != site.domain:
|
|
snapshot.report = {}
|
|
snapshot.observed_at = None
|
|
snapshot.domain = site.domain
|
|
snapshot.requested_at = now
|
|
snapshot.save()
|
|
transaction.on_commit(
|
|
lambda pk=snapshot.pk: collect_website_usage.delay(
|
|
pk, now.isoformat()
|
|
),
|
|
robust=True,
|
|
)
|
|
if (
|
|
settings.LOCAL_MAILBOX_PROVISIONING
|
|
and self.can_view_mailboxes()
|
|
):
|
|
mailboxes = HostingMailbox.objects.filter(
|
|
mail_domain__account=account,
|
|
provisioning__finished_at__isnull=False,
|
|
provisioning__problem="",
|
|
).filter(
|
|
Q(usage_requested_at__isnull=True)
|
|
| Q(usage_requested_at__lte=now - timedelta(minutes=1))
|
|
)
|
|
for pk in list(mailboxes.values_list("pk", flat=True)):
|
|
mailboxes.filter(pk=pk).update(usage_requested_at=now)
|
|
transaction.on_commit(
|
|
lambda pk=pk: collect_mailbox_usage.delay(
|
|
pk, now.isoformat()
|
|
),
|
|
robust=True,
|
|
)
|
|
return redirect("panel:website_usage", pk=account.pk)
|