Cotton code
157 lines · 6.4 KB · ShellRaw
#!/usr/bin/env bash# Read-only process inventory. Exit 1 means orphans; exit 2 means inspection failed.set -euo pipefailcd "$(dirname "${BASH_SOURCE[0]}")/../.."exec python3 - "$@" <<'PY'import globimport jsonimport osimport reimport shleximport subprocessimport sysif sys.argv[1:] not in ([], ['--json']):    print('usage: scripts/ci/orphan-processes.sh [--json]', file=sys.stderr)    sys.exit(2)def read(command):    return subprocess.check_output(command, text=True, stderr=subprocess.DEVNULL)try:    # lstart has five whitespace-separated fields on both macOS and Linux.    listing = read(['ps', '-axww', '-o', 'pid=,ppid=,lstart=,command='])    trees = read(['git', 'worktree', 'list', '--porcelain', '-z'])except (OSError, subprocess.CalledProcessError) as error:    print('orphan-processes: cannot inspect processes or worktrees: ' + str(error), file=sys.stderr)    sys.exit(2)worktrees = [os.path.realpath(line[9:]) for line in re.split('[\n\0]', trees)             if line.startswith('worktree ') and os.path.isdir(line[9:])]processes = {}for line in listing.splitlines():    parts = line.split(None, 7)    if len(parts) == 8 and parts[0].isdigit() and parts[1].isdigit():        pid, ppid = map(int, parts[:2])        processes[pid] = dict(pid=pid, ppid=ppid, started=' '.join(parts[2:7]), command=parts[7])claims = set()for path in glob.glob(os.path.join(os.environ.get('COTTON_CLAIMS_DIR', os.path.expanduser('~/.cottondb/claims')), '*.json')):    try:        with open(path) as claim:            pid = int(json.load(claim).get('pid', 0))        if pid in processes:            claims.add(pid)    except (OSError, ValueError, TypeError, AttributeError):        continuedef paths(command):    try:        return shlex.split(command)    except ValueError:        return command.split()def in_tree(path):    path = os.path.realpath(os.path.expanduser(path))    return any(path == tree or path.startswith(tree + os.sep) for tree in worktrees)def cwd(pid):    if sys.platform != 'darwin':        try:            return os.readlink('/proc/%d/cwd' % pid)        except OSError:            pass    try:        output = read(['lsof', '-a', '-p', str(pid), '-d', 'cwd', '-Fn'])        return next((line[1:] for line in output.splitlines() if line.startswith('n')), '')    except (OSError, subprocess.CalledProcessError):        return ''app = '/Applications/CottonDB.app/'INTERPRETERS = {'bash', 'sh', 'zsh', 'dash', 'python', 'python3', 'node', 'perl', 'ruby', 'env'}allowed = set(claims)for pid, row in processes.items():    if row['command'].startswith(app):        allowed.add(pid)# App helpers and children of a claimed job belong to that live process.while True:    children = {pid for pid, row in processes.items() if row['ppid'] in allowed}    if children <= allowed:        break    allowed |= children# Do not classify this inspector or its invoking shell by their script arguments.self_pids = set()pid = os.getpid()while pid and pid not in self_pids:    self_pids.add(pid)    pid = processes.get(pid, {}).get('ppid', 0)orphans = []for pid, row in processes.items():    if pid in allowed or pid in self_pids:        continue    command = row['command']    tokens = paths(command)    # A Cotton path in an unrelated tool's arguments does not make that tool    # a Cotton process (for example a runner with cotton/config.yaml).    executable = tokens[0] if tokens else ''    # An interpreter running a script is that interpreter's process, whatever    # the script is called (bash ~/.claude/scripts/cotton-session-launcher.sh is    # the phone-launch poller, not a Cotton server). Only a Cotton binary counts.    if os.path.basename(executable) in INTERPRETERS:        continue    # ps does not quote an executable path with spaces ("/Applications/Cotton    # Dev.app/Contents/Helpers/cotton-whatsapp-link"); read it up to the first    # argument. A space followed by "-" or "/" starts an argument, so a Cotton    # path inside the arguments (a toolchain compiling under    # $TMPDIR/cotton-ui-tests-stub/...) never names the executable.    unquoted = re.match(r'^(/.*?/(?:cotton(?:db)?(?:[-_][\w.-]+)?|qa-headless-[\w.-]+))(?=\s|$)', command, re.I)    if unquoted and not re.search(r'\s[-/]', unquoted.group(1)):        executable = unquoted.group(1)    cotton = re.fullmatch(r'cotton(?:db)?(?:[-_][\w.-]+)?|qa-headless-[\w.-]+', os.path.basename(executable), re.I)    # A helper the app launches with a relative command and cwd / (the    # session host: "Contents/Helpers/cotton-session-host serve") is the app's.    if not executable.startswith('/') and os.path.exists(os.path.join(app, executable)):        continue    if not cotton and 'CottonDB.app' not in executable:        continue    directory = cwd(pid)    # ps does not quote executable paths containing spaces. Match a complete    # worktree prefix too, with a path boundary so sibling lanes cannot pass.    if (directory and in_tree(directory)) or any(        command.startswith(tree + '/') or any(token.startswith(tree + '/') for token in tokens)        for tree in worktrees    ):        continue    # A commit is a whole hex path component or the hex tail of one    # (cotton-headless-<sha>, qa-headless-<sha>); a hex run inside a longer    # name (macOS's /var/folders/xx/31c0000gn/T) is not one.    match = re.search(r'(?:^|[/\s._-])([0-9a-f]{7,40})(?=[/\s._-]|$)', command, re.I)    commit = match.group(1) if match else 'unknown'    cli = re.fullmatch(r'cotton-(?:headless|server)|qa-headless-[\w.-]+', os.path.basename(executable), re.I)    if not match and cli and os.path.isfile(executable) and os.access(executable, os.X_OK):        try:            version = subprocess.run([executable, '--version'], capture_output=True, text=True, timeout=2)            match = re.search(r'(?<![0-9a-f])([0-9a-f]{7,40})(?![0-9a-f])', version.stdout, re.I)            if match:                commit = match.group(1)        except (OSError, subprocess.TimeoutExpired):            pass    orphans.append(dict(pid=pid, started=row['started'], command=command, commit=commit))if sys.argv[1:] == ['--json']:    print(json.dumps(orphans, indent=2))else:    for row in orphans:        print('ORPHAN pid={pid} started={started} commit={commit} command={command}'.format(**row))    if not orphans:        print('orphan-processes: no orphan Cotton processes')sys.exit(1 if orphans else 0)PY