-
Notifications
You must be signed in to change notification settings - Fork 7
GitHub Issue #1130: Metrics to track R & Python package usage #7881
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
cnathe
wants to merge
15
commits into
develop
Choose a base branch
from
fb_pacakgeUsage1130
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
4de8ef9
ExternalScriptEngine refactor to allow for getPackageCaptureEpilog, r…
cnathe d98a36b
RScriptEngine implementations for tracking package usages and recordi…
cnathe 76cbf5e
PythonScriptEngine implementations for tracking package usages and re…
cnathe cea599a
ScriptPackageUsageTracker to use SimpleMetricsService to increment co…
cnathe 4b91d83
add try/catches to make sure we don't faile a valid script execution
cnathe f79850e
CR feedback
cnathe 10e9b21
Merge remote-tracking branch 'origin/develop' into fb_pacakgeUsage1130
cnathe a659a9b
Merge remote-tracking branch 'origin/develop' into fb_pacakgeUsage1130
cnathe 42473bb
Code review feedback: limit # packages read and truncate long package…
cnathe e2f06e4
RserveScriptEngine implementation of package capture (given that it h…
cnathe 2f781f9
change to prepend instead of append script so that we can capture pac…
cnathe 802cbfa
revert back to epilog instead of prolog
cnathe c17e00f
change to python epilog to track packages
cnathe 8dacba1
change to python epilog to track packages
cnathe f0aa7cc
claude cr feedback
cnathe File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
92 changes: 92 additions & 0 deletions
92
api/src/org/labkey/api/reports/report/ScriptPackageUsageTracker.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,92 @@ | ||
| /* | ||
| * Copyright (c) 2026 LabKey Corporation | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
| package org.labkey.api.reports.report; | ||
|
|
||
| import org.apache.logging.log4j.Logger; | ||
| import org.labkey.api.reports.ExternalScriptEngine; | ||
| import org.labkey.api.usageMetrics.SimpleMetricsService; | ||
| import org.labkey.api.util.logging.LogHelper; | ||
|
|
||
| import java.util.Map; | ||
| import java.util.Set; | ||
|
|
||
| /** | ||
| * Tracks which packages/modules are loaded by scripts run on this server (R reports, assay transform scripts, Python | ||
| * scripts, and anything else that runs through {@link ExternalScriptEngine}). Populated by a language-specific epilog | ||
| * appended to each script that writes the loaded packages to a sidecar file, which the engine reads back after the | ||
| * script has run successfully. Usage is tracked per language (e.g. "r", "python"). | ||
| * <p> | ||
| * Note that this only sees scripts that ran to completion: a script that fails, or that exits early via q() or | ||
| * sys.exit(), never reaches the epilog and so reports nothing. Counts are a lower bound. | ||
| * | ||
| * Each load is recorded via {@link SimpleMetricsService}, which persists a cumulative per-package load count across | ||
| * restarts and reports it to mothership under "simpleMetricCounts". The package name is the metric name and the feature | ||
| * area is "<language>PackageUsage". | ||
| */ | ||
| public class ScriptPackageUsageTracker | ||
| { | ||
| private static final Logger LOG = LogHelper.getLogger(ScriptPackageUsageTracker.class, "Tracks R & Python package usage by server-side scripts"); | ||
|
|
||
| private static final String MODULE_NAME = "API"; | ||
| private static final String FEATURE_AREA_SUFFIX = "PackageUsage"; | ||
| private static final int MAX_METRIC_NAME_LENGTH = 255; | ||
|
|
||
| /** | ||
| * Packages that ship with a given language's runtime and are always present, so aren't interesting as "library | ||
| * usage". R's base packages are filtered here; Python needs no entry because the capture epilog only reports names | ||
| * that map to an installed distribution, which the standard library never does. | ||
| */ | ||
| private static final Map<String, Set<String>> BASE_PACKAGES = Map.of( | ||
| "r", Set.of("base", "compiler", "datasets", "graphics", "grDevices", "grid", "methods", "parallel", "splines", "stats", "stats4", "tcltk", "tools", "utils") | ||
| ); | ||
|
|
||
| private ScriptPackageUsageTracker() | ||
| { | ||
| } | ||
|
|
||
| private static boolean isBasePackage(String language, String packageName) | ||
| { | ||
| return BASE_PACKAGES.getOrDefault(language, Set.of()).contains(packageName); | ||
| } | ||
|
|
||
| /** | ||
| * Record that the given package was loaded by a script run in the given language (e.g. "r", "python"). Safe to call | ||
| * repeatedly; base packages and blank names are ignored. | ||
| */ | ||
| public static void record(String language, String packageName) | ||
| { | ||
| if (packageName == null || packageName.isBlank() || isBasePackage(language, packageName)) | ||
| return; | ||
|
|
||
| try | ||
| { | ||
| SimpleMetricsService.get().increment(MODULE_NAME, language + FEATURE_AREA_SUFFIX, truncateMetricName(packageName)); | ||
| } | ||
| catch (Exception e) | ||
| { | ||
| LOG.warn("Failed to record {} package usage for '{}'", language, packageName, e); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * The package name is used as the metric name, and the names come from whatever the script actually loaded rather | ||
| * than from a fixed list, so cap the length at what the DB column holds. | ||
| */ | ||
| private static String truncateMetricName(String packageName) | ||
| { | ||
| return packageName.length() <= MAX_METRIC_NAME_LENGTH ? packageName : packageName.substring(0, MAX_METRIC_NAME_LENGTH); | ||
| } | ||
| } |
65 changes: 65 additions & 0 deletions
65
api/src/org/labkey/api/reports/report/python/PythonScriptEngine.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| /* | ||
| * Copyright (c) 2026 LabKey Corporation | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
| package org.labkey.api.reports.report.python; | ||
|
|
||
| import org.jetbrains.annotations.Nullable; | ||
| import org.labkey.api.reports.ExternalScriptEngine; | ||
| import org.labkey.api.reports.ExternalScriptEngineDefinition; | ||
|
|
||
| import javax.script.ScriptContext; | ||
|
|
||
| /** | ||
| * Script engine for locally-executed Python scripts (Python assay transform scripts configured as an | ||
| * external ".py" engine). Behaves like the base {@link ExternalScriptEngine} except that it appends a capture epilog to | ||
| * track which Python packages each script loads; see | ||
| * {@link org.labkey.api.reports.report.ScriptPackageUsageTracker}. | ||
| */ | ||
| public class PythonScriptEngine extends ExternalScriptEngine | ||
| { | ||
| private static final String PACKAGES_FILE = "labkeyPythonPackages.txt"; | ||
|
|
||
| // Python appended to a user script to capture the packages it loaded. | ||
| // try/except means a capture failure can never break the script run. | ||
| private static final String PACKAGE_CAPTURE_EPILOG = """ | ||
| # --- LabKey Python package usage capture --- | ||
| try: | ||
| import importlib.metadata as _lk_md, os as _lk_os, sys as _lk_sys | ||
| _lk_dists = _lk_md.packages_distributions() | ||
| _lk_tops = {m.split('.')[0] for m in list(_lk_sys.modules)} - set(_lk_sys.stdlib_module_names) | ||
| _lk_names = sorted({d for t in _lk_tops if t and not t.startswith('_') for d in _lk_dists.get(t, ())}) | ||
| with open(_lk_os.path.join(_lk_os.getcwd(), '%s'), 'w') as _lk_f: | ||
| _lk_f.write('\\n'.join(_lk_names)) | ||
| except Exception: | ||
| pass | ||
| """.formatted(PACKAGES_FILE); | ||
|
|
||
| public PythonScriptEngine(ExternalScriptEngineDefinition def) | ||
| { | ||
| super(def); | ||
| } | ||
|
|
||
| @Override | ||
| protected @Nullable String getPackageCaptureEpilog(ScriptContext context) | ||
| { | ||
| return PACKAGE_CAPTURE_EPILOG; | ||
| } | ||
|
|
||
| @Override | ||
| protected void recordPackageUsage(ScriptContext context) | ||
| { | ||
| readPackageSidecar(context, PACKAGES_FILE, "python"); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.