Esempio n. 1
0
def send_license_usage():
    license = License.objects.first_valid()
    user = User.objects.first()
    if not license:
        return
    try:
        date_from = (timezone.now() - relativedelta(days=1)).replace(hour=0, minute=0, second=0, microsecond=0)
        date_to = timezone.now().replace(hour=0, minute=0, second=0, microsecond=0)
        events_count = sync_execute(
            "select count(1) from events where timestamp >= %(date_from)s and timestamp < %(date_to)s and not startsWith(event, '$$')",
            {"date_from": date_from, "date_to": date_to},
        )[0][0]
        response = requests.post(
            "https://license.posthog.com/licenses/usage",
            data={"date": date_from.strftime("%Y-%m-%d"), "key": license.key, "events_count": events_count,},
        )

        response.raise_for_status()
        if not response.ok:
            posthoganalytics.capture(
                user.distinct_id,  # type: ignore
                "send license usage data error",
                {
                    "error": response.content,
                    "status_code": response.status_code,
                    "date": date_from.strftime("%Y-%m-%d"),
                    "events_count": events_count,
                    "organization_name": user.current_organization.name,  # type: ignore
                },
            )
            return

        posthoganalytics.capture(
            user.distinct_id,  # type: ignore
            "send license usage data",
            {
                "date": date_from.strftime("%Y-%m-%d"),
                "events_count": events_count,
                "license_keys": get_instance_licenses(),
                "organization_name": user.current_organization.name,  # type: ignore
            },
        )
    except Exception as err:
        posthoganalytics.capture(
            user.distinct_id,  # type: ignore
            "send license usage data error",
            {
                "error": str(err),
                "date": date_from.strftime("%Y-%m-%d"),
                "organization_name": user.current_organization.name,  # type: ignore
            },
        )
Esempio n. 2
0
def send_all_reports(*, dry_run: bool = False) -> List[OrgReport]:
    """
    Generic way to generate and send org usage reports.
    Specify Postgres or ClickHouse for event queries.
    """
    period_start, period_end = get_previous_day()
    realm = get_instance_realm()
    license_keys = get_instance_licenses()
    metadata: OrgReportMetadata = {
        "posthog_version": VERSION,
        "deployment_infrastructure": os.getenv("DEPLOYMENT", "unknown"),
        "realm": realm,
        "period": {
            "start_inclusive": period_start.isoformat(),
            "end_inclusive": period_end.isoformat()
        },
        "site_url": os.getenv("SITE_URL", "unknown"),
        "license_keys": license_keys,
        "product": get_product_name(realm, license_keys),
    }
    org_data: Dict[str, OrgData] = {}
    org_reports: List[OrgReport] = []

    for team in Team.objects.exclude(organization__for_internal_metrics=True):
        org = team.organization
        organization_id = str(org.id)
        if organization_id in org_data:
            org_data[organization_id]["teams"].append(team.id)
        else:
            org_data[organization_id] = {
                "teams": [team.id],
                "user_count": get_org_user_count(organization_id),
                "name": org.name,
                "created_at": str(org.created_at),
            }

    for organization_id, org in org_data.items():
        org_owner = get_org_owner_or_first_user(organization_id)
        if not org_owner:
            continue
        distinct_id = org_owner.distinct_id
        try:
            month_start = period_start.replace(day=1)
            usage = get_org_usage(
                team_ids=org["teams"],
                period_start=period_start,
                period_end=period_end,
                month_start=month_start,
            )
            report: dict = {
                **metadata,
                **usage,
                "organization_id": organization_id,
                "organization_name": org["name"],
                "organization_created_at": org["created_at"],
                "organization_user_count": org["user_count"],
                "team_count": len(org["teams"]),
            }
            org_reports.append(report)  # type: ignore
        except Exception as err:
            logger.warning("Organization usage report calculation failed", err)
            if not dry_run:
                report_org_usage_failure(organization_id, distinct_id,
                                         str(err))
        if not dry_run:
            report_org_usage(organization_id, distinct_id, report)
            time.sleep(0.25)

    return org_reports