Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions ci_runners/drain.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,14 +88,16 @@ def read_path(path: str) -> dict | None:
return None


def refusal(state: dict | None, host: Mapping[str, object], cls: str) -> str:
def refusal(state: dict | None, host: Mapping[str, object], cls: str, pool: str | None = None) -> str:
"""Why a part of runner class ``cls`` may not start here, or empty: the host or the
class's pool is drained, or the state is unreadable. Pure."""
if state is None:
return UNREADABLE
if state['host'] is not None:
return 'drained: host'
pool = inventory.pool_of(host, cls)
if f'class:{cls}' in state['pools']:
return f'drained: class {cls}'
pool = pool or inventory.pool_of(host, cls)
if pool is not None and pool in state['pools']:
return f'drained: pool {pool}'
return ''
Expand All @@ -105,11 +107,15 @@ def pool_key(host: Mapping[str, object], name: str) -> str:
"""The inventory key of the pool ``name`` names, by key or by class; ValueError if
none, or for the home pool, which no drain stops (issue #232). Pure."""
pools = host['pools']
if name == 'class:part' and inventory.pools_of(host, 'part'):
return name
if name in pools and name == inventory.home_pool(host):
raise ValueError(f'{name} is the home pool: presence never stops it and no part reads its drain '
'(drain the host, or the light pool)')
if name in pools:
return name
if name == 'part' and len(inventory.pools_of(host, name)) > 1:
return 'class:part'
key = inventory.pool_of(host, name)
if key is None:
raise ValueError(f'no pool or class {name!r} on this host (pools: {", ".join(sorted(pools))})')
Expand Down
1 change: 1 addition & 0 deletions ci_runners/flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,7 @@ def route_public(parts: Sequence[Mapping], repo: str) -> list[dict]:
bad = [f'{p.get("id")}: needs {p.get("needs")!r}: a public repository runs cpu and light parts on '
'hosted runners and gpu parts on its own pool only (decision 18.7)'
for p in parts if p.get('needs') not in PUBLIC_LABELS]
bad += [f'{p.get("id")}: cores is not supported for public repositories' for p in parts if 'cores' in p]
repo = repo.lower()
if repo not in PUBLIC_CALLERS or repo == policy.SELF:
bad += [f'{p.get("id")}: needs \'gpu\': {repo or "this repository"} is not opted in to the public GPU pool '
Expand Down
62 changes: 54 additions & 8 deletions ci_runners/inventory.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,13 @@ def _num(v: object) -> bool:
return type(v) in (int, float) and math.isfinite(v) and v > 0


#: the classes whose runners take one host CI slot (design §4.3, §7)
CI_SLOT_CLASSES = ('part', 'compile')

_CPU_WIDTH_CANDIDATE = re.compile(r'ci-cpu-[0-9]+\Z')
CPU_WIDTH_LABEL = re.compile(r'ci-cpu-[1-9][0-9]*\Z')


def cpu_ranges(v: object) -> list[tuple[int, int]] | None:
"""A cpuset list such as ``0-3,8-9`` as its ``(first, last)`` ranges, or None where it
is not one (a range downwards, a CPU above MAX_CPU). Pure."""
Expand Down Expand Up @@ -305,6 +312,9 @@ def load(text: str) -> Inventory:
if 'tunnel' in h:
_check_table(f'hosts.{role}.tunnel', h['tunnel'], TUNNEL_KEYS)
seen: dict[tuple[str, bool], str] = {}
widths: set[str] = set()
slot_ranges = []
slot_pools = []
for pool, v in h['pools'].items():
if isinstance(v, dict) and v.get('per_card') and not h['gpus']:
raise InventoryError(f'hosts.{role}.pools.{pool}: per_card on a host without gpus')
Expand All @@ -320,14 +330,48 @@ def load(text: str) -> Inventory:
if pool.startswith('pub-gpu'): # its runners' names would read as the public pool's (C2c)
raise InventoryError(f'hosts.{role}.pools.{pool}: a private pool\'s key starts with pub-gpu')
_check_private_labels(f'hosts.{role}.pools.{pool}', role, pool, v)
if (cls, pub) in seen and cls != HOME_CLASS: # the home pool: _check_home
where = f'hosts.{role}.pools.{pool}'
labels = labels_of(h, pool) or []
if not pub and cls in CI_SLOT_CLASSES:
slot_pools.append(pool)
sized = [label for label in labels if _CPU_WIDTH_CANDIDATE.fullmatch(label)]
if sized:
cap = sized[0]
if len(sized) != 1 or not CPU_WIDTH_LABEL.fullmatch(cap) or cls != 'part' or pub:
raise InventoryError(f'{where}: expected one ci-cpu-N label on a private part pool')
if cap in widths:
raise InventoryError(f'{where}: duplicate CPU pool width {cap}')
widths.add(cap)
other = {label for key in h['pools'] if key != pool for label in labels_of(h, key) or []}
if not any(label.startswith(role + '-') and not label.startswith('ci-') and label not in other
for label in labels):
raise InventoryError(f'{where}: sized pool needs a unique host-local label')
if not v.get('slot') or any('ci-cpu-' + str(sum(hi - lo + 1 for lo, hi in cpu_ranges(c))) != cap
for c in v['slot']['cpus']):
raise InventoryError(f'{where}: each slot.cpus entry must match {cap}')
if (cls, pub) in seen and cls != HOME_CLASS and not sized: # the home pool: _check_home
raise InventoryError(f'hosts.{role}.pools.{pool}: class {cls} is also the class of {seen[cls, pub]}')
if isinstance(v, dict) and 'slot' in v: # one cpuset per runner (16.2)
n = len(h['gpus']) if v.get('per_card') else v['count']
if len(v['slot']['cpus']) != n:
raise InventoryError(f'hosts.{role}.pools.{pool}: slot.cpus has {len(v["slot"]["cpus"])} '
f'cpusets for {n} runners')
seen[cls, pub] = pool
slot_ranges.extend((lo, hi, pool, bool(sized))
for c in v['slot']['cpus'] for lo, hi in cpu_ranges(c))
if not sized:
seen[cls, pub] = pool
if widths:
if h['slots'] < len(slot_pools):
raise InventoryError(f'hosts.{role}.slots: {h["slots"]} shared CI slots for {len(slot_pools)} pools '
f'({", ".join(slot_pools)}); sized CPU pools need at least one slot per pool')
ranges = sorted(slot_ranges)
for i, (_, hi, pool, sized) in enumerate(ranges):
for j in range(i + 1, len(ranges)):
lo, _, other, other_sized = ranges[j]
if lo > hi:
break
if sized or other_sized:
raise InventoryError(f'hosts.{role}.pools: overlapping slot CPUs in {pool} and {other}')
_check_home(role, h)
if any(pub for _, pub in seen) and ('gpu', False) not in seen:
raise InventoryError(f'hosts.{role}: a public pool shares the cards of the host\'s own gpu pool: name one')
Expand Down Expand Up @@ -470,14 +514,16 @@ def pool_class(host: Mapping[str, object], pool: str) -> str:
return _class(pool, host['pools'][pool])


def pools_of(host: Mapping[str, object], cls: str) -> list[str]:
return [p for p, v in host['pools'].items() if _class(p, v) == cls]


def pool_of(host: Mapping[str, object], cls: str) -> str | None:
"""The pool of ``host`` whose runners have class ``cls``, or None: one at most, but for
class light beside the home pool (``home_pool``), where it is the light pool, the one
with a ``ci-`` label (issue #232). Pure."""
mine = [p for p, v in host['pools'].items() if _class(p, v) == cls]
if len(mine) > 1:
"""The unique pool of this class, excluding the home pool when it shares light."""
mine = pools_of(host, cls)
if len(mine) > 1 and cls == HOME_CLASS:
mine = [p for p in mine if p != home_pool(host)]
return mine[0] if mine else None
return mine[0] if len(mine) == 1 else None


def probe_keys(v: object) -> list[str]:
Expand Down
32 changes: 26 additions & 6 deletions ci_runners/part.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@
#: (design §4.3 ``record``): a retry on another host takes its attempt from the name (13.3)
RECORD_REF = re.compile(r'[a-z0-9][a-z0-9-]{0,30}:[^/:]+/[^/:]+/[0-9]+-[0-9]+/'
r'(?P<id>[A-Za-z0-9][A-Za-z0-9_.-]{0,63})-(?P<n>[1-9][0-9]{0,2})')
SLOT_CLASSES = ('part', 'compile') # the classes whose parts take one host CI slot (design §4.3, §7)
SLOT_CLASSES = inventory.CI_SLOT_CLASSES
EVERY_SLOT = 'nightly' # the class whose parts take every slot and every card lease (decision 12.8)
LOCKS = ('none', 's', 'x', 'l') # the ``lock`` input: hold the host lock for the command, or not
#: what each class's ``part`` accepts (design §4.8): ``(least cards, most cards, locks,
Expand Down Expand Up @@ -308,6 +308,18 @@ def record(self) -> dict[str, object]:
return out


def runner_pool(host: Mapping[str, object], cls: str, env: Mapping[str, str]) -> tuple[str | None, str]:
"""Resolve the setup-provided pool key, or use the unambiguous legacy class."""
key = env.get('CI_RUNNER_POOL')
if key is not None:
if key not in inventory.pools_of(host, cls):
return None, f'CI_RUNNER_POOL {key!r} is not a {cls} pool here'
return key, ''
if cls == 'part' and len(inventory.pools_of(host, cls)) > 1:
return None, 'CI_RUNNER_POOL is required on a host with multiple CPU pools'
return inventory.pool_of(host, cls), ''


def runner_slot(host: Mapping[str, object], cls: str, env: Mapping[str, str]) -> tuple[RunnerSlot | None, str]:
"""The slot of the runner whose job environment is ``env`` and whose class is ``cls``
(decision 16.2), as ``(slot, '')``; ``(None, '')`` where the runner has none (no
Expand All @@ -316,12 +328,16 @@ def runner_slot(host: Mapping[str, object], cls: str, env: Mapping[str, str]) ->
without a ``slot`` table, out of the table's range, or on a per-card pool another
card's slot than ``CI_RUNNER_CARD``'s. Never a fallback to the runner without a slot.
Pure."""
pool, why = runner_pool(host, cls, env)
if why:
return None, why
raw = env.get('CI_RUNNER_SLOT', '')
if raw == '':
if pool and any(inventory.CPU_WIDTH_LABEL.fullmatch(label) for label in inventory.labels_of(host, pool) or []):
return None, 'CI_RUNNER_SLOT is required for a sized CPU pool'
return None, ''
if not SLOT_INDEX.fullmatch(raw):
return None, f'CI_RUNNER_SLOT {raw!r} is no slot index'
pool = inventory.pool_of(host, cls)
spec = host['pools'][pool] if pool else None
table = spec.get('slot') if isinstance(spec, dict) else None
if not table:
Expand Down Expand Up @@ -986,6 +1002,8 @@ def queue_capped(inv: inventory.Inventory, runner: str) -> bool:
if runner not in names:
return True
pool = pools[names.index(runner)]
if len(inventory.pools_of(inv.host, 'part')) > 1 and inventory.pool_class(inv.host, pool) in SLOT_CLASSES:
return sum(inventory.pool_class(inv.host, key) in SLOT_CLASSES for key in pools) > int(inv.host['slots'])
return pools.count(pool) > int(inv.host['slots'])


Expand Down Expand Up @@ -1256,8 +1274,10 @@ def execute(self, a: Inputs) -> tuple[int, dict[str, object]]:
'attempt': attempt, 'retries': proj.retries, 'fallback': fallback, 'inputs': dataclasses.asdict(a),
'start_epoch': time.time(), 'boot_start': boot_id(), 'executor': os.getpid(),
'release': self.release}
if inventory.pool_labels(self.inv, cls):
rec['pool_labels'] = inventory.pool_labels(self.inv, cls)
pool, _ = runner_pool(h, cls, self.env)
labels = inventory.labels_of(h, pool) if pool else None
if labels:
rec['pool_labels'] = labels
_write_json(os.path.join(record, 'record.json'), rec)
for sig in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP):
signal.signal(sig, self._on_signal)
Expand Down Expand Up @@ -1292,7 +1312,7 @@ def execute(self, a: Inputs) -> tuple[int, dict[str, object]]:
drain_mod.publish(str(h['data']))
except OSError:
pass
why = drain_mod.refusal(drain_mod.read(str(h['data'])), h, cls) # decision 13.1
why = drain_mod.refusal(drain_mod.read(str(h['data'])), h, cls, pool) # decision 13.1
if why:
return self._away(record, rec, a, why, cls)
why = self.busy(a, cls, proj.retries) # decisions 13.2, 13.6
Expand Down Expand Up @@ -1431,7 +1451,7 @@ def execute(self, a: Inputs) -> tuple[int, dict[str, object]]:
argv = scope_argv(self.unit, proj.name, memory, sup, self.oom_policy()) if self.scope else sup
if self.stopped:
return self._end(record, rec, a, stopped=True)
why = drain_mod.refusal(drain_mod.read(str(h['data'])), h, cls) # drained while it waited (13.1)
why = drain_mod.refusal(drain_mod.read(str(h['data'])), h, cls, pool) # drained while it waited (13.1)
if why:
return self._away(record, rec, a, why, cls)
# the supervisor keeps the host lock with the slot: the command's own requests find it
Expand Down
4 changes: 2 additions & 2 deletions ci_runners/presence.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@
LOAD_ON, LOAD_OFF = 0.5, 0.25 # a slot's CPUs busy with others: holds at half of them, clears below a quarter
HOLD = 77 # check's exit while a cause holds: ExecCondition= skips the start (1-254), and no other error maps to it
LOST_HORIZON = 12 * 3600 # s: the part records read for a lost part (the longest part, 600 min, and its queue)
SLOT_CLASSES = ('part', 'compile') # the classes whose parts take one host CI slot (part.SLOT_CLASSES)
SLOT_CLASSES = inventory.CI_SLOT_CLASSES
EVERY_SLOT = 'nightly' # the class whose part takes every slot (part.EVERY_SLOT)
CARD_CLASSES = {'gpu', 'multi'} # the classes whose runners lease cards: its own (gpu), every card (multi)
TIMING = 'compile' # the exclusive timing class (16.1 ci-timing)
Expand Down Expand Up @@ -570,7 +570,7 @@ def causes(inv: inventory.Inventory, rs: Sequence[Runner], f: Facts, units: Mapp
out: dict[str, list[str]] = {}
for r in rs:
why = []
d = drain_mod.refusal(f.drain, h, r.cls)
d = drain_mod.refusal(f.drain, h, r.cls, r.pool)
if d:
why.append(d)
if f.health:
Expand Down
Loading
Loading