Preview: cl-node-modules-storage
Size: 48.56 KB
/usr/sbin/cl-node-modules-storage
#!/opt/cloudlinux/venv/bin/python3 -bb
# coding:utf-8
# Copyright © Cloud Linux GmbH & Cloud Linux Software, Inc 2010-2026 All Rights Reserved
#
# Licensed under CLOUD LINUX LICENSE AGREEMENT
# http://cloudlinux.com/docs/LICENSE.TXT
"""Root administrator controls for shared Node modules storage.
Every command answers with one JSON object on stdout carrying
``"result": "success"`` and a ``"timestamp"`` -- the same contract as
`cloudlinux-selector`, so a future UI reads this tool the way it reads the
others. A failure is the same object with the message in ``result`` and a
non-zero exit code.
This file is the only supported way to change the configuration. The config
lives on the CageFS-mounted side (see ``node_modules_storage.CONFIG_PATH``),
so an atomic replace here is visible inside every cage at once -- there is
no refresh step, and none to forget.
"""
import argparse
import json
import os
import pwd
import stat
import subprocess
import sys
import time
from urllib.parse import urlsplit, urlunsplit
from clcommon.utils import is_ubuntu
from clselector import node_modules_storage as storage
from clselector.node_modules_storage import engine_available as _engine_available
DELIVERY_SOCKET = '/opt/cl-bun/run/delivery.sock'
DELIVERY_SERVICE = 'cl-bun-deliveryd.service'
DELIVERY_SOCKET_UNIT = 'cl-bun-deliveryd.socket'
PRUNE_TIMER_UNIT = 'cl-node-modules-storage-prune.timer'
SYSTEMD_QUERY_TIMEOUT = 5.0
ADMIN_LOCK_TIMEOUT = 120
SOFT_STORAGE_LIMIT_WARN_FRACTION = 0.8
REGISTRY_CONFIGURATION_WARNING = (
'Shared node_modules Store delivery is blocked until exactly one registry '
'is configured.')
# The last answer of this process, for the flag consumer to classify.
LAST_PAYLOAD = None
# CLI flag <-> config limit key. Kept in one place so `set` and `status`
# agree on names.
LIMIT_FLAGS = {
'deliveries_per_hour': 'account_deliveries_per_hour',
'deliveries_per_day': 'account_deliveries_per_day',
'concurrent_deliveries': 'concurrent_deliveries',
'delivery_queue_timeout': 'delivery_queue_timeout_seconds',
'soft_storage_limit_gb': 'soft_storage_limit_gb',
}
# The two whose new value only takes hold on a daemon restart.
RESTART_LIMITS = frozenset(
('concurrent_deliveries', 'delivery_queue_timeout_seconds'))
class Refusal(storage.StorageError):
"""A refusal the administrator resolves; ``category`` names it in the reply."""
def __init__(self, category, message):
super().__init__(message)
self.category = category
class JsonArgumentParser(argparse.ArgumentParser):
"""Keep usage failures inside the CLI's one-JSON-object contract."""
def error(self, message):
_emit({'result': '%s: %s' % (self.prog, message),
'usage': self.format_usage().strip()}, code=2)
self.exit(2)
def _delivery_module():
"""The delivery transaction, imported on demand.
`status` and the configuration commands have no business paying for its
imports; only `reclaim-staging` walks storage the way delivery does.
"""
import cloudlinux_bun_delivery
return cloudlinux_bun_delivery
def _ensure_engine():
"""Install on explicit activation, before taking the configuration lock."""
if _engine_available():
return
env = os.environ.copy()
command = ['yum', '-y', 'install', 'cl-bun']
if is_ubuntu():
command = ['apt-get', '-y', '--no-remove', 'install', 'cl-bun']
env['DEBIAN_FRONTEND'] = 'noninteractive'
print('Installing cl-bun; this may take several minutes.', file=sys.stderr, flush=True)
try:
result = subprocess.run(command, capture_output=True, text=True,
errors='replace', env=env,
stdin=subprocess.DEVNULL)
output = (result.stdout + '\n' + result.stderr).strip()
except OSError as exc:
output = str(exc)
# Only a usable engine decides: installer prose and exit statuses differ
# between yum 3, dnf and apt, and none of them proves the binary is there.
if not _engine_available():
raise Refusal(
'engine', 'Could not install a usable cl-bun engine. As root, run %s (or '
'reinstall the package if it is already installed) and retry '
'cl-node-modules-storage enable. %s'
% (' '.join(command), output[-2000:]))
def manual_control():
"""An explicit administrator command owns both ON and OFF until released."""
return os.path.lexists(storage.CONFIG_PATH + '.manual')
def _mark_manual_control():
marker = storage.CONFIG_PATH + '.manual'
if os.path.isdir(marker) and not os.path.islink(marker):
raise storage.StorageError(
'%s is a directory; remove it and retry' % marker)
parent = os.path.dirname(storage.CONFIG_PATH)
storage._reject_symlink_ancestors(parent)
os.makedirs(parent, mode=0o755, exist_ok=True)
storage._atomic_write(marker, {})
def _flag_request_is_current(command):
# Imported only by the systemd flag consumer. Ordinary administrator
# operations and delivery keep their existing local configuration API.
from cl_node_modules_storage_flags import wanted
return not manual_control() and wanted() is (command == 'enable')
def main(argv=None, from_flag=False):
parser = JsonArgumentParser(prog='cl-node-modules-storage', allow_abbrev=False)
commands = parser.add_subparsers(dest='command')
commands.add_parser('status', help='show the configuration and daemon state')
commands.add_parser('reconcile', help='validate and publish storage device metadata')
remote = ('; takes this server out of remote (feature-flag) management '
'until %s.manual is removed' % storage.CONFIG_PATH)
enable = commands.add_parser('enable', help='switch shared storage on' + remote,
description='switch shared storage on' + remote)
enable.add_argument('--storage-path', metavar='PATH',
help='the storage directory, replacing the current one; '
'a multi-path set is edited with storage-list')
enable.add_argument('--soft-storage-limit-gb', type=int, metavar='GB',
help='recorded-usage threshold for each storage directory '
'(0 disables it; concurrent admissions may overshoot)')
commands.add_parser('disable', help='switch shared storage off' + remote,
description='switch shared storage off' + remote)
commands.add_parser('prune', help='remove unused storage entries')
reclaim = commands.add_parser(
'reclaim-staging',
help='remove abandoned delivery staging trees that ordinary cleanup '
'cannot reclaim (see retained_staging in status)')
reclaim.add_argument('--storage', metavar='PATH',
help='only this configured storage directory; '
'by default every one of them')
set_cmd = commands.add_parser(
'set', help='change the storage path, the registry allowlist or a limit')
set_cmd.add_argument('--storage-path', metavar='PATH',
help='replace the storage directory; a multi-path set '
'is edited with storage-list --add/--remove')
set_cmd.add_argument('--allowed-registries', metavar='URL[,URL...]',
help='set exactly one registry URL for the shared cache; '
'changing it requires empty selected storage')
set_cmd.add_argument('--deliveries-per-hour', type=int)
set_cmd.add_argument('--deliveries-per-day', type=int)
set_cmd.add_argument('--concurrent-deliveries', type=int)
set_cmd.add_argument('--delivery-queue-timeout', type=int)
set_cmd.add_argument('--soft-storage-limit-gb', type=int)
storage_list = commands.add_parser(
'storage-list',
help='show the storage paths; --add/--remove edit them '
'(each path serves the accounts whose home is on its filesystem)')
storage_list.add_argument('--add', metavar='PATH[,PATH...]')
storage_list.add_argument('--remove', metavar='PATH[,PATH...]')
exclude_list = commands.add_parser(
'exclude-list',
help='show the excluded accounts; --add/--remove edit the list '
'(excluded accounts take the ordinary npm path)')
exclude_list.add_argument('--add', metavar='USER[,USER...]')
exclude_list.add_argument('--remove', metavar='USER[,USER...]')
args = parser.parse_args(argv)
if args.command is None:
parser.error('an action is required')
if args.command == 'set' and not (args.storage_path
or args.allowed_registries is not None
or any(getattr(args, flag) is not None
for flag in LIMIT_FLAGS)):
parser.error('set needs --storage-path, --allowed-registries '
'or a limit to change')
if args.command == 'status':
reader = (storage.read_config if os.geteuid() == 0
else storage.read_public_config)
return _emit(_status_payload(reader(storage.CONFIG_PATH)))
if args.command == 'exclude-list' and os.geteuid() != 0:
return _emit({'result': 'cl-node-modules-storage must run as root'},
code=2)
if args.command == 'exclude-list' and not (args.add or args.remove):
excluded = storage.read_config(storage.CONFIG_PATH)['excluded_users']
return _emit({'result': 'success', 'excluded_users': excluded})
if args.command == 'storage-list' and not (args.add or args.remove):
reader = (storage.read_config if os.geteuid() == 0
else storage.read_public_config)
return _emit({'result': 'success',
'storage_paths': reader(storage.CONFIG_PATH)['storage_paths']})
if os.geteuid() != 0:
return _emit({'result': 'cl-node-modules-storage must run as root'},
code=2)
manual = not from_flag and args.command in ('enable', 'disable')
try:
if manual:
# Take ownership before installation or a lock wait, including a
# failed attempt: automation must not later retry what the
# administrator controls. The atomic marker needs no lock -- the
# flag consumer rechecks it under config_lock before publishing.
_mark_manual_control()
if from_flag and not _flag_request_is_current(args.command):
return _emit({'result': 'success', 'changed': False,
'message': 'Shared Store policy or ownership changed; request skipped'})
if args.command == 'enable':
# Reject unsupported hosts before installing a package. The same
# gates run again under config_lock before publishing enabled state.
if not storage.nodejs_selector_supported():
raise Refusal('selector',
'Node.js Selector is not supported by this control panel')
if not storage.protected_hardlinks_enabled():
raise Refusal('hardlinks', 'Shared Store requires fs.protected_hardlinks=1')
current = storage.read_config(storage.CONFIG_PATH)
if (os.path.lexists(storage.CONFIG_PATH)
and storage._read_raw(storage.CONFIG_PATH) is None):
# read_config shows defaults for it; update_config refuses it.
raise Refusal(
'paths', '%s is unreadable (malformed, a symlink or not a '
'root-owned file); fix or remove it and retry'
% storage.CONFIG_PATH)
_require_configured_paths(args, current)
_require_single_registry(current['allowed_registries'])
_registry(current['allowed_registries'][0])
paths = _target_paths(args, current)
# A path that does not exist yet covers no account: create it
# first, as the same checks under config_lock do.
_validate_storage_paths(paths)
refusal = _coverage_refusal(paths, current['excluded_users'])
if refusal is not None:
if manual:
refusal['manual_control'] = True
return _emit(refusal)
_ensure_engine()
mutates_config = (
args.command in ('enable', 'disable', 'set', 'reconcile')
or (args.command in ('storage-list', 'exclude-list')
and (args.add or args.remove)))
if mutates_config:
# Keep each supported read-modify-write transaction together so
# simultaneous administrator edits cannot lose one another.
with storage.config_lock(timeout=ADMIN_LOCK_TIMEOUT):
if from_flag and not _flag_request_is_current(args.command):
return _emit({'result': 'success', 'changed': False,
'message': 'Shared Store policy or ownership changed; request skipped'})
code = _dispatch(args, parser)
if code is not None:
return code
# `disable` published OFF under the lock; stopping the daemon may
# wait for a delivery drain and must not hold other commands.
stopped = _stop_delivery_service()
payload = _status_payload(storage.read_config(storage.CONFIG_PATH))
if not stopped:
payload['warnings'] = payload.get('warnings', []) + [
'delivery policy is disabled, but the resident service could '
'not be stopped; socket activation remains configured']
return _emit(payload)
return _dispatch(args, parser)
except (storage.StorageError, OSError) as exc:
payload = {'result': 'cl-node-modules-storage: %s' % exc}
if isinstance(exc, Refusal):
payload['refusal'] = exc.category
elif str(exc) == 'storage lock wait timed out':
# Raised by the storage library for config_lock and storage_lock.
payload['refusal'] = 'lock'
if manual:
payload['manual_control'] = True
return _emit(payload)
def _dispatch(args, parser):
current = storage.read_config(storage.CONFIG_PATH)
warning = None
enabled_registry = None
if args.command == 'enable' and not storage.nodejs_selector_supported():
raise Refusal('selector',
'Node.js Selector is not supported by this control panel')
if args.command == 'enable' and not storage.protected_hardlinks_enabled():
raise Refusal('hardlinks', 'Shared Store requires fs.protected_hardlinks=1')
if args.command == 'enable' and not _engine_available():
raise Refusal('engine', storage.ENGINE_UNAVAILABLE)
if args.command == 'enable':
_require_configured_paths(args, current)
_require_single_registry(current['allowed_registries'])
enabled_registry = _registry(current['allowed_registries'][0])
if args.command == 'reconcile':
changed = storage.reconcile_storage_devices(storage.CONFIG_PATH)
return _emit({'result': 'success',
'storage_devices': 'updated' if changed else 'current'})
if args.command == 'prune':
# Every configured storage in turn; the summaries add up, and each
# prune refreshes that storage's recorded size for the soft-limit gate.
totals = {'removed': 0, 'bytes': 0, 'kept': 0, 'skipped': 0, 'poisoned': 0}
warnings = []
for path in current['storage_paths']:
try:
summary = storage.prune_storage(path)
except storage.StorageError as exc:
# Daily maintenance is opportunistic. One missing or busy
# store must not hide successful cleanup of the other stores
# or leave the timer failed until an administrator intervenes.
warnings.append(
'storage maintenance skipped for %s: %s' % (path, exc))
continue
for key in totals:
totals[key] += summary[key]
warnings.extend(summary.get('warnings', []))
totals['result'] = 'success'
totals['storage_paths'] = current['storage_paths']
if warnings:
totals['warnings'] = sorted(set(warnings))
return _emit(totals)
if args.command == 'reclaim-staging':
paths = None
if args.storage:
if args.storage not in current['storage_paths']:
raise storage.StorageError(
'%s is not a configured storage directory' % args.storage)
paths = [args.storage]
summary = _delivery_module().reclaim_retained_staging(
current, storage_paths=paths)
entries = summary['entries']
failed = sum(1 for entry in entries if entry['result'] == 'failed')
return _emit({
# Bytes that are still held: a script reclaiming space must not
# read a zero exit as "the store is clean now".
'result': ('success' if not failed else
'%d staging tree(s) could not be reclaimed' % failed),
'storage_paths': paths or current['storage_paths'],
'removed': summary['removed'],
'skipped': sum(1 for entry in entries
if entry['result'] == 'skipped'),
'failed': failed,
'entries': entries,
})
if args.command == 'disable':
# The caller stops the service and answers after releasing the lock.
storage.update_config(storage.CONFIG_PATH, enabled=False)
return None
if args.command == 'exclude-list':
excluded = set(current['excluded_users'])
excluded |= _users(args.add)
excluded -= _users(args.remove)
storage.update_config(storage.CONFIG_PATH, excluded_users=sorted(excluded))
return _emit(_status_payload(storage.read_config(storage.CONFIG_PATH)))
# Enabling delivery and changing the storage set must refuse before
# writing if that would leave an account home on an uncovered filesystem.
paths = _target_paths(args, current)
kwargs = {'storage_paths': paths}
if args.command == 'enable':
kwargs['enabled'] = True
if enabled_registry != current['allowed_registries'][0]:
kwargs['allowed_registries'] = [enabled_registry]
if args.soft_storage_limit_gb is not None:
storage.validate_limits({'soft_storage_limit_gb': args.soft_storage_limit_gb})
kwargs['limits'] = {'soft_storage_limit_gb': args.soft_storage_limit_gb}
if args.command == 'set':
limits, warning = _limit_updates(args, parser)
if limits:
kwargs['limits'] = limits
if args.allowed_registries is not None:
registries = _registries(args.allowed_registries)
_require_single_registry(registries)
kwargs['allowed_registries'] = registries
# Validate (and possibly create) paths only when this command activates or
# changes storage. Limit/registry updates must not touch storage paths.
if args.command == 'enable' or paths != current['storage_paths']:
_validate_storage_paths(paths)
if paths != current['storage_paths']:
# Only a change to the set is judged: a list written by an older
# CLI, which appended, must not lock the administrator out of every
# other `set` and `enable` until it is repaired.
_reject_shared_filesystem(paths)
if args.command == 'enable' or paths != current['storage_paths']:
# Coverage gates activation and changes to the storage set. A later
# uncovered account must not prevent unrelated limit or registry
# updates while the administrator arranges another storage/exclusion.
refusal = _coverage_refusal(paths, current['excluded_users'])
if refusal is not None:
if args.command == 'enable' and manual_control():
refusal['manual_control'] = True
return _emit(refusal)
registry_changed = (
args.command == 'set' and args.allowed_registries is not None
and [item.rstrip('/') for item in kwargs['allowed_registries']]
!= [item.rstrip('/') for item in current['allowed_registries']])
target_limits = dict(current['limits'])
target_limits.update(kwargs.get('limits', {}))
refresh_soft_limit = (
target_limits['soft_storage_limit_gb'] > 0
and (args.command == 'enable'
or paths != current['storage_paths']
or (args.command == 'set'
and args.soft_storage_limit_gb is not None)))
if refresh_soft_limit:
# Measuring a store walks all of it. The exclusive global lock stops
# every delivery on the server, so the snapshot is taken outside it;
# a measurement is advisory telemetry and a delivery started during
# it rechecks the threshold under the per-store cache lock anyway.
for path in paths:
storage.refresh_usage(path)
if registry_changed or refresh_soft_limit:
# Bun's package cache is not registry-namespaced. Serialize with all
# deliveries while changing its registry or publishing the config
# that enables a soft limit.
with storage.storage_lock(True, timeout=ADMIN_LOCK_TIMEOUT):
if (registry_changed
and not all(storage.storage_cache_is_empty(path)
for path in paths)):
raise storage.StorageError(
'cannot change the registry while a selected storage '
'contains cache data; select an empty storage path first')
storage.update_config(storage.CONFIG_PATH, **kwargs)
else:
storage.update_config(storage.CONFIG_PATH, **kwargs)
payload = _status_payload(storage.read_config(storage.CONFIG_PATH))
if warning:
payload['warnings'] = payload.get('warnings', []) + [warning]
return _emit(payload)
def _require_single_registry(registries):
if len(registries) != 1:
raise Refusal(
'registry', 'exactly one registry must be configured for shared storage')
def _validate_storage_paths(paths):
"""Create or check each storage directory; a bad one is the administrator's."""
for path in paths:
try:
storage.validate_storage_path(path)
except storage.StorageError as exc:
raise Refusal('paths', str(exc))
def _require_configured_paths(args, current):
"""Refuse a bare `enable` over configured storage paths that are all invalid.
The reader then shows the default path, and enabling would silently
replace the administrator's setting with it. `enable --storage-path`
names a replacement on purpose, so it repairs such a file instead.
"""
if current['storage_configured'] or getattr(args, 'storage_path', None):
return
raw = storage._read_raw(storage.CONFIG_PATH)
if raw is not None and ('storage_paths' in raw or 'storage_path' in raw):
raise Refusal(
'paths', 'the configured storage paths in %s are invalid; fix them '
'with storage-list --add/--remove or name a replacement with '
'enable --storage-path PATH' % storage.CONFIG_PATH)
def _target_paths(args, current):
"""The storage-path list a mutation is proposing.
`--storage-path` on `enable` and `set` names *the* storage: it replaces
what is there, on a fresh server (where the displayed default is a
suggestion, not a choice) and on a configured one alike. Appending would
leave two storages on one filesystem, and delivery only ever picks the
first on the venv's device, so the path just "set" would be dead. A
multi-path set has no single path to replace; it is edited with
`storage-list --add/--remove`, and `--storage-path` says so.
"""
paths = list(current['storage_paths']) if current['storage_configured'] else []
if args.command in ('enable', 'set') and getattr(args, 'storage_path', None):
if len(paths) > 1:
raise storage.StorageError(
'%d storage paths are configured (%s); --storage-path replaces a '
'single one. Edit the set with storage-list --add PATH / '
'--remove PATH instead.' % (len(paths), ', '.join(paths)))
paths = [args.storage_path]
if not paths:
paths = list(current['storage_paths'])
if args.command == 'storage-list':
for path in _split(args.add):
if path not in paths:
paths.append(path)
remove = _split(args.remove)
paths = [p for p in paths if p not in remove]
if not paths:
raise storage.StorageError(
'refusing to remove the last storage path; at least one is required')
return paths
def _reject_shared_filesystem(paths):
"""Refuse two storages on one filesystem, naming both.
Delivery selects the first configured storage on the venv's device, so a
second one there can never be chosen: it would only ever be a dead
entry the administrator believes is in use. Paths that cannot be
stat'ed are left to the coverage sweep and to delivery to report.
"""
seen = {}
for path in paths:
try:
device = os.stat(path).st_dev
except OSError:
continue
if device in seen:
raise storage.StorageError(
'%s and %s are on the same filesystem; delivery would only ever '
'use %s. One storage per filesystem: drop one with '
'storage-list --remove PATH.' % (seen[device], path, seen[device]))
seen[device] = path
def _limit_updates(args, parser):
"""(dict of config-key -> int, restart-warning-or-None) from `set` flags."""
updates = {}
for flag, key in LIMIT_FLAGS.items():
value = getattr(args, flag)
if value is not None:
updates[key] = value
storage.validate_limits(updates)
warning = None
if RESTART_LIMITS & set(updates):
warning = ('concurrent-deliveries / delivery-queue-timeout apply to an '
'active service after: systemctl try-restart '
'cl-bun-deliveryd.service; a standby service reads them on '
'next activation')
return updates, warning
def _coverage_refusal(storage_paths, excluded):
"""A refusal payload naming accounts no proposed storage covers, or None."""
_total, uncovered = storage.home_device_coverage(storage_paths)
uncovered = [name for name in uncovered if name not in excluded]
if not uncovered:
return None
shown = ', '.join(uncovered[:10])
more = '' if len(uncovered) <= 10 else ' and %d more' % (len(uncovered) - 10)
return {
'refusal': 'coverage',
'result': ('%d account(s) have a home on a filesystem no storage covers '
'and would fail delivery: %s%s. Add a storage path on their '
'filesystem (storage-list --add) or exclude them '
'(exclude-list --add).' % (len(uncovered), shown, more)),
'uncovered_count': len(uncovered),
'uncovered_users': uncovered[:10],
}
def _split(value):
"""The house list convention: one argument, comma-separated, spaces
tolerated, empty entries dropped."""
return [item.strip() for item in (value or '').split(',') if item.strip()]
def _registries(value):
"""The single registry a `set --allowed-registries` call proposes.
Store one canonical, unambiguous HTTPS authority/path. The caller rejects
zero or multiple entries because Bun's shared cache has one global
namespace.
"""
registries = _split(value)
return [_registry(registry) for registry in registries]
def _registry(registry):
try:
parsed = urlsplit(registry)
hostname = parsed.hostname
port = parsed.port
except ValueError:
parsed = None
hostname = None
port = None
if (parsed is None or parsed.scheme.lower() != 'https' or not hostname
or parsed.username is not None or parsed.password is not None
or parsed.query or parsed.fragment or '%' in registry
or '\\' in registry
or any(ord(char) < 0x21 or ord(char) == 0x7f
for char in registry)):
# Never echo the value: it may carry credentials or a token.
raise Refusal('registry', 'not a registry URL (safe HTTPS required, '
'without credentials, query or fragment)')
try:
hostname = hostname.encode('idna').decode('ascii').lower()
except UnicodeError:
raise Refusal('registry', 'not a registry URL (safe HTTPS required, '
'without credentials, query or fragment)')
authority = '[%s]' % hostname if ':' in hostname else hostname
if port is not None and port != 443:
authority += ':%d' % port
path = parsed.path.rstrip('/') + '/'
return urlunsplit(('https', authority, path, '', ''))
def _users(value):
users = set()
for name in _split(value):
_validate_user(name)
users.add(name)
return users
def _emit(payload, code=None):
"""One JSON object per invocation; exit code says how it went."""
global LAST_PAYLOAD
payload.setdefault('result', 'success')
payload['timestamp'] = time.time()
LAST_PAYLOAD = payload
print(json.dumps(payload, sort_keys=True))
if code is not None:
return code
return 0 if payload['result'] == 'success' else 1
def _storage_is_usable(path, warnings, enabled):
"""Would a delivery be able to open this storage right now?
A store whose mode or ownership has drifted (`chmod 0777`, a
non-root-private ancestor) refuses every delivery, and nothing else in
`status` shows it: the recorded accounting still reads healthy. The
store is `0700`, so only root can answer; a non-root caller reports
unknown rather than a verdict it could not have observed. Open only --
`status` never creates or repairs anything.
A host that never enabled the feature has no store yet -- `enable`
creates it -- and that absence is not a fault worth a warning. The
verdict is therefore given only while delivery is enabled or the
directory exists; otherwise it is unknown.
"""
if os.geteuid() != storage.ROOT_UID:
return None
if not enabled and not os.path.lexists(path):
return None
try:
fd, _created = storage._open_storage_dir(path)
except storage.StorageError as exc:
warnings.append('storage %s is unusable: %s; delivery refuses until '
'it is repaired' % (path, exc))
return False
os.close(fd)
return True
def _status_payload(config):
service_active = _systemd_unit_active(DELIVERY_SERVICE)
socket_active = _systemd_unit_active(DELIVERY_SOCKET_UNIT)
prune_timer_active = _systemd_unit_active(PRUNE_TIMER_UNIT)
gateway_state = ('active' if service_active else
'standby' if socket_active else 'inactive')
warnings = []
try:
supported = storage.nodejs_selector_supported()
except storage.StorageError as exc:
supported = None
warnings.append(str(exc))
if supported is False:
warnings.append('Node.js Selector is not supported by this control panel')
if config.get('exclusions_valid', True) is False:
warnings.append(
'account exclusion policy is unreadable; Shared Store delivery '
'is blocked until it is repaired')
if not storage.protected_hardlinks_enabled():
warnings.append(
'Shared Store requires fs.protected_hardlinks=1; delivery is unsafe '
'until the kernel setting is restored')
if config['enabled'] and not _engine_available():
warnings.append(storage.ENGINE_UNAVAILABLE)
if len(config['allowed_registries']) != 1:
warnings.append(REGISTRY_CONFIGURATION_WARNING)
coverage = None
try:
coverage = storage.home_device_coverage(config['storage_paths'])
uncovered = [name for name in coverage[1]
if name not in config['excluded_users']]
except storage.StorageError as exc:
# Anyone may read `status`, and the panel's account list is not
# readable by anyone (cPanel's /etc/userplans is root-only): report
# the coverage as unknown rather than failing the whole command for
# a non-root caller. Mutations run as root and still refuse.
uncovered = None
warnings.append('cannot check account home coverage: %s' % exc)
soft_limit = config['limits']['soft_storage_limit_gb']
storages = []
for index, path in enumerate(config['storage_paths']):
# `status` must not connect to the activation socket: observing the
# gateway must never start its service. The root-owned accounting
# snapshot is the same durable source the daemon would return.
entry = _storage_usage(path, soft_limit)
entry['usable'] = _storage_is_usable(path, warnings, config['enabled'])
storages.append(entry)
if entry['stale']:
warnings.append(
'storage %s accounting is incomplete (%s); the recorded size '
'is a floor, not a total' % (path, entry['stale_reason']))
if entry['retained_staging']:
warnings.append(
'storage %s has %d staging tree(s) under %s: an in-flight '
'delivery, or a previous tree kept after a failed rollback; '
'run cl-node-modules-storage reclaim-staging'
% (path, entry['retained_staging'],
DELIVERY_STAGING_DIRECTORY))
if soft_limit and entry['used_bytes'] is not None:
if entry['used_bytes'] >= soft_limit * (1 << 30) * SOFT_STORAGE_LIMIT_WARN_FRACTION:
warnings.append('storage %s is at %d%% of its %d GB soft limit'
% (path, int(100 * entry['used_bytes']
/ (soft_limit * (1 << 30))), soft_limit))
if config['enabled'] and not socket_active:
warnings.append(
"delivery socket activation is inactive; accounts' own npm "
'installs cannot be delivered while it is down')
if config['enabled'] and uncovered:
warnings.append('%d account(s) have a home no storage covers and cannot '
'be delivered' % len(uncovered))
payload = {
'result': 'success',
'enabled': config['enabled'],
'manual_control': manual_control(),
'feature_status': ('unknown' if supported is None else
'unsupported' if not supported else
'enabled' if config['enabled'] else 'disabled'),
'storage_paths': config['storage_paths'],
'storages': storages,
'excluded_users': config['excluded_users'],
'allowed_registries': config['allowed_registries'],
'uncovered_users': None if uncovered is None else len(uncovered),
'limits': config['limits'],
# Keep `daemon` as the compact compatibility field, but make the two
# systemd states explicit. `standby` means the socket is listening and
# will start the inactive service only when rollback/delivery needs it.
'daemon': gateway_state,
'daemon_service': 'active' if service_active else 'inactive',
'socket_activation': 'active' if socket_active else 'inactive',
'prune_timer': 'active' if prune_timer_active else 'inactive',
'last_prune_trigger': _systemd_timer_last_trigger(PRUNE_TIMER_UNIT),
}
# Aggregate telemetry belongs to the local administrator only. The
# daemon socket remains the deliberately small unprivileged size API.
if os.geteuid() == 0:
(active_users, active_applications,
eligible_users, eligible_applications) = _shared_node_modules_counts()
if active_users is None:
warnings.append('shared-node-modules active counts are unavailable')
if eligible_users is None:
warnings.append('shared-node-modules eligibility counts are unavailable')
payload['telemetry'] = _aggregate_telemetry(
storages, active_users, active_applications,
eligible_users, eligible_applications)
# The same install values `cloudlinux-summary` publishes.
causes = []
installs = storage.read_install_counters(causes=causes)
if installs['delivered'] is None:
# `summary` publishes these as -42; say why, so it can be fixed.
warnings.append('install counters are unknown: %s' % (
causes[0] if causes else 'the install record is unreadable'))
payload['telemetry'].update({
'home_covered': (None if coverage is None or supported is not True
else storage.shared_node_modules_home_covered(
config, supported=supported,
coverage=coverage)),
'installs_delivered': installs['delivered'],
'installs_failed': installs['failed'],
'installs_broken': installs['broken'],
'installs_ssh': installs['ssh'],
'installs_fallback_unsupported_source':
installs['fallback_unsupported_source'],
'installs_fallback_registry_not_allowed':
installs['fallback_registry_not_allowed'],
'installs_fallback_lockfile_mismatch':
installs['fallback_lockfile_mismatch'],
'installs_fallback_unsupported_manifest':
installs['fallback_unsupported_manifest'],
'installs_ci': installs['ci'],
'last_install_at': installs['last_install_at'],
})
# Maintenance through the Store (CLOS-7898), here only.
payload['telemetry'].update(
('installs_' + name, installs[name])
for name in storage.MAINTENANCE_COUNTERS)
# Which applications the Store cannot serve, for the administrator
# alone (status is root-only); the summary carries none of it.
fallbacks = storage.read_fallbacks(causes=causes)
if fallbacks['total'] is None:
warnings.append('fallback registry is unknown: %s' % (
causes[-1] if causes else 'the registry is unreadable'))
payload['telemetry'].update(storage.fallback_aggregates(fallbacks))
applications = None if fallbacks['applications'] is None else []
for key, entry in (fallbacks['applications'] or {}).items():
uid, app_root = key.split(':', 1)
try:
user = pwd.getpwuid(int(uid)).pw_name
except (KeyError, OSError):
# No account, or NSS timing out: the number stands.
user = uid
applications.append(dict(
{name: entry[name] for name in
('reason', 'detail', 'first_at', 'last_at', 'count')},
user=user, app_root=app_root))
if applications:
applications.sort(key=lambda item: item['last_at'], reverse=True)
payload['telemetry']['fallback_applications'] = {
'total': fallbacks['total'], 'by_reason': fallbacks['by_reason'],
'note': storage.FALLBACK_NOTE, 'applications': applications}
poisoned = payload['telemetry']['poisoned_entries']
if poisoned:
warnings.append(
'%d poisoned shared-storage cache entry or entries detected; '
'run prune and investigate ownership changes' % poisoned)
if warnings:
payload['warnings'] = warnings
return payload
def _systemd_unit_active(unit):
"""Read a unit state without touching the delivery socket."""
try:
return subprocess.run(
['systemctl', 'is-active', '--quiet', unit],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0
except OSError:
return False
def _systemd_timer_last_trigger(unit):
"""Return systemd's bounded human timestamp without activating a unit."""
try:
process = subprocess.run(
['systemctl', 'show', '--property=LastTriggerUSec', '--value', unit],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
universal_newlines=True, timeout=SYSTEMD_QUERY_TIMEOUT)
except (OSError, subprocess.SubprocessError):
return None
if process.returncode != 0:
return None
value = process.stdout.strip()
if not value or value == 'n/a':
return None
return value[:128]
def _stop_delivery_service():
"""Drain the resident worker; the socket unit remains the gateway."""
try:
return subprocess.run(
['systemctl', 'stop', DELIVERY_SERVICE],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0
except OSError:
return False
def _shared_node_modules_counts():
"""Best-effort active and eligible counts, never names in the result."""
try:
from clselect.clselectnodejs.apps_manager import ApplicationsManager
info = ApplicationsManager().get_applications_users_info()
if ('warning' in info or 'available_versions' not in info
or not isinstance(info['available_versions'], dict)):
return None, None, None, None
active_users = set()
eligible_users = set()
active_applications = 0
eligible_applications = 0
for version in info.get('available_versions', {}).values():
users = version.get('users')
if users is None:
continue
if not isinstance(users, dict):
return None, None, None, None
for user, user_info in users.items():
for app in user_info.get('applications', {}).values():
if app.get('shared_node_modules', {}).get('active'):
active_users.add(user)
active_applications += 1
if app.get('shared_node_modules', {}).get('eligible'):
eligible_users.add(user)
eligible_applications += 1
return (len(active_users), active_applications,
len(eligible_users), eligible_applications)
except Exception:
return None, None, None, None
def _active_shared_node_modules_counts():
"""Compatibility helper for callers that only need active totals."""
return _shared_node_modules_counts()[:2]
DELIVERY_STAGING_DIRECTORY = '.delivery-staging'
def _retained_staging(path):
"""How many post-swap staging trees one storage still holds.
Delivery renames the account's previous tree under `.delivery-staging`
and removes it once the swap has landed; startup cleanup reclaims what an
interrupted transaction left. One retained tree is therefore bytes that
nothing else in `status` accounts for, and the administrator has no other
way to see it.
One non-descending, descriptor-relative listing: only root-owned `0700`
directories are staging trees -- the lifetime lease file, a loosened
directory and a symlink are not -- and nothing here follows or opens
them. The store is `0700`, so a non-root `status` reports unknown rather
than a zero it could not have observed.
"""
if os.geteuid() != storage.ROOT_UID:
return None
try:
root_fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
except OSError:
return None
try:
try:
staging_fd = os.open(
DELIVERY_STAGING_DIRECTORY,
os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=root_fd)
except OSError:
return 0
try:
retained = 0
for name in os.listdir(staging_fd):
try:
info = os.stat(name, dir_fd=staging_fd,
follow_symlinks=False)
except OSError:
continue
if (stat.S_ISDIR(info.st_mode)
and info.st_uid == storage.ROOT_UID
and stat.S_IMODE(info.st_mode) == 0o700):
retained += 1
return retained
except OSError:
return None
finally:
os.close(staging_fd)
finally:
os.close(root_fd)
def _storage_usage(path, soft_limit_gb):
"""One storage directory's size for `status`.
Read the durable record directly, or (as root, when never yet recorded)
perform one live walk. It never writes: delivery and prune own the record.
"""
used = measured_at = None
accounting = None
measured_by = None
usage = storage.read_usage(path)
if usage is not None:
measured_by = 'recorded'
used = usage['used_bytes']
measured_at = usage['measured_at']
if os.geteuid() == 0:
accounting = usage
elif os.geteuid() == 0:
try:
accounting = storage.measure_storage_usage(path)
used = accounting['used_bytes']
measured_by = 'cli'
except storage.StorageError:
pass
return {
'path': path,
'used_bytes': used,
'used_gb': None if used is None else round(used / (1 << 30), 2),
'soft_storage_limit_gb': soft_limit_gb,
'measured_by': measured_by,
'measured_at': measured_at,
'allocated_bytes': None if accounting is None else accounting.get('allocated_bytes'),
'shared_inodes': None if accounting is None else accounting.get('shared_inodes'),
'shared_links': None if accounting is None else accounting.get('shared_links'),
'estimated_saved_bytes': (None if accounting is None
else accounting.get('estimated_saved_bytes')),
'deduplication_ratio': (None if accounting is None
else accounting.get('deduplication_ratio')),
'poisoned_entries': (None if accounting is None
else accounting.get('poisoned_entries')),
'retained_staging': _retained_staging(path),
# A measurement that stopped at one of its own bounds counted part of
# the store: the number is a floor, and saying so is the difference
# between a small store and one too big to walk.
'stale': bool(accounting is not None and accounting.get('stale')),
'stale_reason': (None if accounting is None
else accounting.get('stale_reason')),
}
def _aggregate_telemetry(storages, active_users, active_applications,
eligible_users, eligible_applications):
"""Aggregate root-only accounting without retaining tenant identifiers."""
names = ('used_bytes', 'allocated_bytes', 'estimated_saved_bytes',
'shared_inodes', 'shared_links', 'poisoned_entries')
totals = {}
for name in names:
values = [entry.get(name) for entry in storages]
totals[name] = (sum(values) if all(type(value) is int and value >= 0
for value in values) else None)
stale = any(bool(entry.get('stale')) for entry in storages)
if stale and not totals['poisoned_entries']:
# A walk that stopped at its bound may not have reached a poisoned
# entry, and `0` reads as "no poisoning". Not knowing must not look
# like good news. Entries it did reach are conclusive and stay.
totals['poisoned_entries'] = None
measured = [entry.get('measured_at') for entry in storages]
measured_at = (min(measured) if measured and all(
type(value) in (int, float) for value in measured) else None)
allocated = totals['allocated_bytes']
saved = totals['estimated_saved_bytes']
return {
'active_users': active_users,
'active_applications': active_applications,
'eligible_users': eligible_users,
'eligible_applications': eligible_applications,
'cache_used_bytes': totals['used_bytes'],
'cache_allocated_bytes': allocated,
'estimated_saved_bytes': saved,
'shared_inodes': totals['shared_inodes'],
'shared_links': totals['shared_links'],
'poisoned_entries': totals['poisoned_entries'],
'deduplication_ratio': ((allocated + saved) / float(allocated)
if allocated else (1.0 if allocated == 0 and saved == 0
else None)),
# The oldest snapshot bounds freshness; a missing one makes the
# aggregate timestamp unknown rather than falsely current.
'measured_at': measured_at,
# Any contributing storage that stopped at a measurement bound makes
# the totals floors, not sizes. Summing them without saying so
# published a partial measurement as a total.
'stale': stale,
}
def _validate_user(user):
if not user or any(ch in user for ch in (' ', '\t', '\n', '/', ':')):
raise storage.StorageError('not an account name: %r' % user)
if __name__ == '__main__':
sys.exit(main())
Directory Contents
Dirs: 0 × Files: 660